import { createRequire as __detaCreateRequire } from 'node:module'; const require = __detaCreateRequire(import.meta.url); 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 __require = /* @__PURE__ */ ((x4) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x4, { get: (a3, b5) => (typeof require !== "undefined" ? require : a3)[b5] }) : x4)(function(x4) { if (typeof require !== "undefined") return require.apply(this, arguments); throw Error('Dynamic require of "' + x4 + '" is not supported'); }); var __esm = (fn2, res, err2) => function __init() { if (err2) throw err2[0]; try { return fn2 && (res = (0, fn2[__getOwnPropNames(fn2)[0]])(fn2 = 0)), res; } catch (e5) { throw err2 = [e5], e5; } }; var __commonJS = (cb, mod) => function __require2() { try { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; } catch (e5) { throw mod = 0, e5; } }; var __export = (target, all) => { for (var name24 in all) __defProp(target, name24, { get: all[name24], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // node_modules/@vercel/oidc/dist/get-context.js var require_get_context = __commonJS({ "node_modules/@vercel/oidc/dist/get-context.js"(exports, module) { "use strict"; var __defProp3 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export3 = (target, all) => { for (var name24 in all) __defProp3(target, name24, { get: all[name24], enumerable: true }); }; var __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod); var get_context_exports = {}; __export3(get_context_exports, { SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT, getContext: () => getContext3 }); module.exports = __toCommonJS(get_context_exports); var SYMBOL_FOR_REQ_CONTEXT = /* @__PURE__ */ Symbol.for("@vercel/request-context"); function getContext3() { const fromSymbol = globalThis; return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {}; } } }); // node_modules/@vercel/oidc/dist/token-error.js var require_token_error = __commonJS({ "node_modules/@vercel/oidc/dist/token-error.js"(exports, module) { "use strict"; var __defProp3 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export3 = (target, all) => { for (var name24 in all) __defProp3(target, name24, { get: all[name24], enumerable: true }); }; var __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod); var token_error_exports = {}; __export3(token_error_exports, { VercelOidcTokenError: () => VercelOidcTokenError }); module.exports = __toCommonJS(token_error_exports); var VercelOidcTokenError = class extends Error { constructor(message, cause) { super(message); this.name = "VercelOidcTokenError"; this.cause = cause; } toString() { if (this.cause) { return `${this.name}: ${this.message}: ${this.cause}`; } return `${this.name}: ${this.message}`; } }; } }); // node_modules/@vercel/oidc/dist/token-io.js var require_token_io = __commonJS({ "node_modules/@vercel/oidc/dist/token-io.js"(exports, module) { "use strict"; var __create2 = Object.create; var __defProp3 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export3 = (target, all) => { for (var name24 in all) __defProp3(target, name24, { get: all[name24], enumerable: true }); }; var __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod); var token_io_exports = {}; __export3(token_io_exports, { findRootDir: () => findRootDir, getUserDataDir: () => getUserDataDir }); module.exports = __toCommonJS(token_io_exports); var import_path = __toESM2(__require("path")); var import_fs = __toESM2(__require("fs")); var import_os = __toESM2(__require("os")); var import_token_error = require_token_error(); function findRootDir() { try { let dir = process.cwd(); while (dir !== import_path.default.dirname(dir)) { const pkgPath = import_path.default.join(dir, ".vercel"); if (import_fs.default.existsSync(pkgPath)) { return dir; } dir = import_path.default.dirname(dir); } } catch (e5) { 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/@vercel/oidc/dist/auth-config.js var require_auth_config = __commonJS({ "node_modules/@vercel/oidc/dist/auth-config.js"(exports, module) { "use strict"; var __create2 = Object.create; var __defProp3 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export3 = (target, all) => { for (var name24 in all) __defProp3(target, name24, { get: all[name24], enumerable: true }); }; var __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod); var auth_config_exports = {}; __export3(auth_config_exports, { isValidAccessToken: () => isValidAccessToken, readAuthConfig: () => readAuthConfig, writeAuthConfig: () => writeAuthConfig }); module.exports = __toCommonJS(auth_config_exports); var fs2 = __toESM2(__require("fs")); var path = __toESM2(__require("path")); var import_token_util = require_token_util(); function getAuthConfigPath() { const dataDir = (0, import_token_util.getVercelDataDir)(); if (!dataDir) { throw new Error( `Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.` ); } return path.join(dataDir, "auth.json"); } function readAuthConfig() { try { const authPath = getAuthConfigPath(); if (!fs2.existsSync(authPath)) { return null; } const content = fs2.readFileSync(authPath, "utf8"); if (!content) { return null; } return JSON.parse(content); } catch (error40) { return null; } } function writeAuthConfig(config2) { const authPath = getAuthConfigPath(); const authDir = path.dirname(authPath); if (!fs2.existsSync(authDir)) { fs2.mkdirSync(authDir, { mode: 504, recursive: true }); } fs2.writeFileSync(authPath, JSON.stringify(config2, null, 2), { mode: 384 }); } function isValidAccessToken(authConfig, expirationBufferMs = 0) { if (!authConfig.token) return false; if (typeof authConfig.expiresAt !== "number") return true; const nowInSeconds = Math.floor(Date.now() / 1e3); const bufferInSeconds = expirationBufferMs / 1e3; return authConfig.expiresAt >= nowInSeconds + bufferInSeconds; } } }); // node_modules/@vercel/oidc/dist/oauth.js var require_oauth = __commonJS({ "node_modules/@vercel/oidc/dist/oauth.js"(exports, module) { "use strict"; var __defProp3 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export3 = (target, all) => { for (var name24 in all) __defProp3(target, name24, { get: all[name24], enumerable: true }); }; var __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod); var oauth_exports = {}; __export3(oauth_exports, { processTokenResponse: () => processTokenResponse, refreshTokenRequest: () => refreshTokenRequest }); module.exports = __toCommonJS(oauth_exports); var import_os = __require("os"); var VERCEL_ISSUER = "https://vercel.com"; var VERCEL_CLI_CLIENT_ID = "cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp"; var userAgent = `@vercel/oidc node-${process.version} ${(0, import_os.platform)()} (${(0, import_os.arch)()}) ${(0, import_os.hostname)()}`; var _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 || typeof metadata.token_endpoint !== "string") { throw new Error("Invalid OAuth discovery response"); } const endpoint = metadata.token_endpoint; _tokenEndpoint = endpoint; return endpoint; } async function refreshTokenRequest(options) { const tokenEndpoint = await getTokenEndpoint(); return await fetch(tokenEndpoint, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "user-agent": userAgent }, body: new URLSearchParams({ client_id: VERCEL_CLI_CLIENT_ID, grant_type: "refresh_token", ...options }) }); } async function processTokenResponse(response) { const json3 = await response.json(); if (!response.ok) { const errorMsg = typeof json3 === "object" && json3 && "error" in json3 ? String(json3.error) : "Token refresh failed"; return [new Error(errorMsg)]; } if (typeof json3 !== "object" || json3 === null) { return [new Error("Invalid token response")]; } if (typeof json3.access_token !== "string") { return [new Error("Missing access_token in response")]; } if (json3.token_type !== "Bearer") { return [new Error("Invalid token_type in response")]; } if (typeof json3.expires_in !== "number") { return [new Error("Missing expires_in in response")]; } return [null, json3]; } } }); // node_modules/@vercel/oidc/dist/auth-errors.js var require_auth_errors = __commonJS({ "node_modules/@vercel/oidc/dist/auth-errors.js"(exports, module) { "use strict"; var __defProp3 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export3 = (target, all) => { for (var name24 in all) __defProp3(target, name24, { get: all[name24], enumerable: true }); }; var __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod); var auth_errors_exports = {}; __export3(auth_errors_exports, { AccessTokenMissingError: () => AccessTokenMissingError2, RefreshAccessTokenFailedError: () => RefreshAccessTokenFailedError2 }); module.exports = __toCommonJS(auth_errors_exports); var AccessTokenMissingError2 = class extends Error { constructor() { super( "No authentication found. Please log in with the Vercel CLI (vercel login)." ); this.name = "AccessTokenMissingError"; } }; var RefreshAccessTokenFailedError2 = class extends Error { constructor(cause) { super("Failed to refresh authentication token.", { cause }); this.name = "RefreshAccessTokenFailedError"; } }; } }); // node_modules/@vercel/oidc/dist/token-util.js var require_token_util = __commonJS({ "node_modules/@vercel/oidc/dist/token-util.js"(exports, module) { "use strict"; var __create2 = Object.create; var __defProp3 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __getProtoOf2 = Object.getPrototypeOf; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export3 = (target, all) => { for (var name24 in all) __defProp3(target, name24, { get: all[name24], enumerable: true }); }; var __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod); var token_util_exports = {}; __export3(token_util_exports, { assertVercelOidcTokenResponse: () => assertVercelOidcTokenResponse, findProjectInfo: () => findProjectInfo, getTokenPayload: () => getTokenPayload, getVercelDataDir: () => getVercelDataDir, getVercelOidcToken: () => getVercelOidcToken3, getVercelToken: () => getVercelToken2, isExpired: () => isExpired, loadToken: () => loadToken, saveToken: () => saveToken }); module.exports = __toCommonJS(token_util_exports); var path = __toESM2(__require("path")); var fs2 = __toESM2(__require("fs")); var import_token_error = require_token_error(); var import_token_io = require_token_io(); var import_auth_config = require_auth_config(); var import_oauth = require_oauth(); var import_auth_errors = require_auth_errors(); function getVercelDataDir() { const vercelFolder = "com.vercel.cli"; const dataDir = (0, import_token_io.getUserDataDir)(); if (!dataDir) { return null; } return path.join(dataDir, vercelFolder); } async function getVercelToken2(options) { const authConfig = (0, import_auth_config.readAuthConfig)(); if (!authConfig?.token) { throw new import_auth_errors.AccessTokenMissingError(); } if ((0, import_auth_config.isValidAccessToken)(authConfig, options?.expirationBufferMs)) { return authConfig.token; } if (!authConfig.refreshToken) { (0, import_auth_config.writeAuthConfig)({}); throw new import_auth_errors.RefreshAccessTokenFailedError("No refresh token available"); } try { const tokenResponse = await (0, import_oauth.refreshTokenRequest)({ refresh_token: authConfig.refreshToken }); const [tokensError, tokens] = await (0, import_oauth.processTokenResponse)(tokenResponse); if (tokensError || !tokens) { (0, import_auth_config.writeAuthConfig)({}); throw new import_auth_errors.RefreshAccessTokenFailedError(tokensError); } const updatedConfig = { token: tokens.access_token, expiresAt: Math.floor(Date.now() / 1e3) + tokens.expires_in }; if (tokens.refresh_token) { updatedConfig.refreshToken = tokens.refresh_token; } (0, import_auth_config.writeAuthConfig)(updatedConfig); return updatedConfig.token; } catch (error40) { (0, import_auth_config.writeAuthConfig)({}); if (error40 instanceof import_auth_errors.AccessTokenMissingError || error40 instanceof import_auth_errors.RefreshAccessTokenFailedError) { throw error40; } throw new import_auth_errors.RefreshAccessTokenFailedError(error40); } } async function getVercelOidcToken3(authToken, projectId, teamId) { const url2 = `https://api.vercel.com/v1/projects/${projectId}/token?source=vercel-oidc-refresh${teamId ? `&teamId=${teamId}` : ""}`; const res = await fetch(url2, { method: "POST", headers: { Authorization: `Bearer ${authToken}` } }); if (!res.ok) { throw new import_token_error.VercelOidcTokenError( `Failed to refresh OIDC token: ${res.statusText}` ); } const tokenRes = await res.json(); assertVercelOidcTokenResponse(tokenRes); return tokenRes; } function assertVercelOidcTokenResponse(res) { if (!res || typeof res !== "object") { throw new TypeError( "Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again" ); } if (!("token" in res) || typeof res.token !== "string") { throw new TypeError( "Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again" ); } } function findProjectInfo() { const dir = (0, import_token_io.findRootDir)(); if (!dir) { throw new import_token_error.VercelOidcTokenError( "Unable to find project root directory. Have you linked your project with `vc link?`" ); } const prjPath = path.join(dir, ".vercel", "project.json"); if (!fs2.existsSync(prjPath)) { throw new import_token_error.VercelOidcTokenError( "project.json not found, have you linked your project with `vc link?`" ); } const prj = JSON.parse(fs2.readFileSync(prjPath, "utf8")); if (typeof prj.projectId !== "string" && typeof prj.orgId !== "string") { throw new TypeError( "Expected a string-valued projectId property. Try running `vc link` to re-link your project." ); } return { projectId: prj.projectId, teamId: prj.orgId }; } function saveToken(token2, 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(token2); fs2.mkdirSync(path.dirname(tokenPath), { mode: 504, recursive: true }); fs2.writeFileSync(tokenPath, tokenJson); fs2.chmodSync(tokenPath, 432); return; } 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 (!fs2.existsSync(tokenPath)) { return null; } const token2 = JSON.parse(fs2.readFileSync(tokenPath, "utf8")); assertVercelOidcTokenResponse(token2); return token2; } function getTokenPayload(token2) { const tokenParts = token2.split("."); if (tokenParts.length !== 3) { throw new import_token_error.VercelOidcTokenError( "Invalid token. Please run `vc env pull` and try again" ); } const base643 = tokenParts[1].replace(/-/g, "+").replace(/_/g, "/"); const padded = base643.padEnd( base643.length + (4 - base643.length % 4) % 4, "=" ); return JSON.parse(Buffer.from(padded, "base64").toString("utf8")); } function isExpired(token2, bufferMs = 0) { return token2.exp * 1e3 < Date.now() + bufferMs; } } }); // node_modules/@vercel/oidc/dist/token.js var require_token = __commonJS({ "node_modules/@vercel/oidc/dist/token.js"(exports, module) { "use strict"; var __defProp3 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export3 = (target, all) => { for (var name24 in all) __defProp3(target, name24, { get: all[name24], enumerable: true }); }; var __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod); var token_exports = {}; __export3(token_exports, { refreshToken: () => refreshToken }); module.exports = __toCommonJS(token_exports); var import_token_error = require_token_error(); var import_token_util = require_token_util(); async function refreshToken(options) { let projectId = options?.project; let teamId = options?.team; if (!projectId && !teamId) { const projectInfo = (0, import_token_util.findProjectInfo)(); projectId = projectInfo.projectId; teamId = projectInfo.teamId; } else if (!projectId || !teamId) { const projectInfo = (0, import_token_util.findProjectInfo)(); projectId = projectId ?? projectInfo.projectId; teamId = teamId ?? projectInfo.teamId; } if (!projectId) { throw new import_token_error.VercelOidcTokenError( "Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`" ); } let maybeToken = (0, import_token_util.loadToken)(projectId); if (!maybeToken || (0, import_token_util.isExpired)((0, import_token_util.getTokenPayload)(maybeToken.token), options?.expirationBufferMs)) { const authToken = await (0, import_token_util.getVercelToken)({ expirationBufferMs: options?.expirationBufferMs }); 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; return; } } }); // node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js var require_get_vercel_oidc_token = __commonJS({ "node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports, module) { "use strict"; var __defProp3 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export3 = (target, all) => { for (var name24 in all) __defProp3(target, name24, { get: all[name24], enumerable: true }); }; var __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod); var get_vercel_oidc_token_exports = {}; __export3(get_vercel_oidc_token_exports, { getVercelOidcToken: () => getVercelOidcToken3, getVercelOidcTokenSync: () => getVercelOidcTokenSync2 }); module.exports = __toCommonJS(get_vercel_oidc_token_exports); var import_get_context = require_get_context(); var import_token_error = require_token_error(); async function getVercelOidcToken3(options) { let token2 = ""; let err2; try { token2 = getVercelOidcTokenSync2(); } catch (error40) { err2 = error40; } try { const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([ await Promise.resolve().then(() => __toESM(require_token_util())), await Promise.resolve().then(() => __toESM(require_token())) ]); if (!token2 || isExpired(getTokenPayload(token2), options?.expirationBufferMs)) { await refreshToken(options); token2 = getVercelOidcTokenSync2(); } } catch (error40) { let message = err2 instanceof Error ? err2.message : ""; if (error40 instanceof Error) { message = `${message} ${error40.message}`; } if (message) { throw new import_token_error.VercelOidcTokenError(message); } throw error40; } return token2; } function getVercelOidcTokenSync2() { const token2 = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN; if (!token2) { 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 token2; } } }); // node_modules/@vercel/oidc/dist/index.js var require_dist = __commonJS({ "node_modules/@vercel/oidc/dist/index.js"(exports, module) { "use strict"; var __defProp3 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export3 = (target, all) => { for (var name24 in all) __defProp3(target, name24, { get: all[name24], enumerable: true }); }; var __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod); var src_exports = {}; __export3(src_exports, { AccessTokenMissingError: () => import_auth_errors.AccessTokenMissingError, RefreshAccessTokenFailedError: () => import_auth_errors.RefreshAccessTokenFailedError, getContext: () => import_get_context.getContext, getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken, getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync, getVercelToken: () => import_token_util.getVercelToken }); module.exports = __toCommonJS(src_exports); var import_get_vercel_oidc_token = require_get_vercel_oidc_token(); var import_get_context = require_get_context(); var import_auth_errors = require_auth_errors(); var import_token_util = require_token_util(); } }); // node_modules/fflate/esm/index.mjs var esm_exports = {}; __export(esm_exports, { AsyncCompress: () => AsyncGzip, AsyncDecompress: () => AsyncDecompress, AsyncDeflate: () => AsyncDeflate, AsyncGunzip: () => AsyncGunzip, AsyncGzip: () => AsyncGzip, AsyncInflate: () => AsyncInflate, AsyncUnzipInflate: () => AsyncUnzipInflate, AsyncUnzlib: () => AsyncUnzlib, AsyncZipDeflate: () => AsyncZipDeflate, AsyncZlib: () => AsyncZlib, Compress: () => Gzip, DecodeUTF8: () => DecodeUTF8, Decompress: () => Decompress, Deflate: () => Deflate, EncodeUTF8: () => EncodeUTF8, FlateErrorCode: () => FlateErrorCode, Gunzip: () => Gunzip, Gzip: () => Gzip, Inflate: () => Inflate, Unzip: () => Unzip, UnzipInflate: () => UnzipInflate, UnzipPassThrough: () => UnzipPassThrough, Unzlib: () => Unzlib, Zip: () => Zip, ZipDeflate: () => ZipDeflate, ZipPassThrough: () => ZipPassThrough, Zlib: () => Zlib, compress: () => gzip, compressSync: () => gzipSync, decompress: () => decompress, decompressSync: () => decompressSync, deflate: () => deflate, deflateSync: () => deflateSync, gunzip: () => gunzip, gunzipSync: () => gunzipSync, gzip: () => gzip, gzipSync: () => gzipSync, inflate: () => inflate, inflateSync: () => inflateSync, strFromU8: () => strFromU8, strToU8: () => strToU8, unzip: () => unzip, unzipSync: () => unzipSync, unzlib: () => unzlib, unzlibSync: () => unzlibSync, zip: () => zip, zipSync: () => zipSync, zlib: () => zlib, zlibSync: () => zlibSync }); import { createRequire } from "module"; function StrmOpt(opts, cb) { if (typeof opts == "function") cb = opts, opts = {}; this.ondata = cb; return opts; } function deflate(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != "function") err(7); return cbify(data, opts, [ bDflt ], function(ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb); } function deflateSync(data, opts) { return dopt(data, opts || {}, 0, 0); } function inflate(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != "function") err(7); return cbify(data, opts, [ bInflt ], function(ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb); } function inflateSync(data, opts) { return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary); } function gzip(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != "function") err(7); return cbify(data, opts, [ bDflt, gze, function() { return [gzipSync]; } ], function(ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb); } function gzipSync(data, opts) { if (!opts) opts = {}; var c2 = crc(), l13 = data.length; c2.p(data); var d2 = dopt(data, opts, gzhl(opts), 8), s2 = d2.length; return gzh(d2, opts), wbytes(d2, s2 - 8, c2.d()), wbytes(d2, s2 - 4, l13), d2; } function gunzip(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != "function") err(7); return cbify(data, opts, [ bInflt, guze, function() { return [gunzipSync]; } ], function(ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb); } function gunzipSync(data, opts) { var st2 = gzs(data); if (st2 + 8 > data.length) err(6, "invalid gzip data"); return inflt(data.subarray(st2, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary); } function zlib(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != "function") err(7); return cbify(data, opts, [ bDflt, zle, function() { return [zlibSync]; } ], function(ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb); } function zlibSync(data, opts) { if (!opts) opts = {}; var a3 = adler(); a3.p(data); var d2 = dopt(data, opts, opts.dictionary ? 6 : 2, 4); return zlh(d2, opts), wbytes(d2, d2.length - 4, a3.d()), d2; } function unzlib(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != "function") err(7); return cbify(data, opts, [ bInflt, zule, function() { return [unzlibSync]; } ], function(ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb); } function unzlibSync(data, opts) { return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary); } function decompress(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != "function") err(7); return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzip(data, opts, cb) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflate(data, opts, cb) : unzlib(data, opts, cb); } function decompressSync(data, opts) { return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzipSync(data, opts) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflateSync(data, opts) : unzlibSync(data, opts); } function strToU8(str, latin1) { if (latin1) { var ar_1 = new u8(str.length); for (var i4 = 0; i4 < str.length; ++i4) ar_1[i4] = str.charCodeAt(i4); return ar_1; } if (te2) return te2.encode(str); var l13 = str.length; var ar2 = new u8(str.length + (str.length >> 1)); var ai2 = 0; var w3 = function(v2) { ar2[ai2++] = v2; }; for (var i4 = 0; i4 < l13; ++i4) { if (ai2 + 5 > ar2.length) { var n5 = new u8(ai2 + 8 + (l13 - i4 << 1)); n5.set(ar2); ar2 = n5; } var c2 = str.charCodeAt(i4); if (c2 < 128 || latin1) w3(c2); else if (c2 < 2048) w3(192 | c2 >> 6), w3(128 | c2 & 63); else if (c2 > 55295 && c2 < 57344) c2 = 65536 + (c2 & 1023 << 10) | str.charCodeAt(++i4) & 1023, w3(240 | c2 >> 18), w3(128 | c2 >> 12 & 63), w3(128 | c2 >> 6 & 63), w3(128 | c2 & 63); else w3(224 | c2 >> 12), w3(128 | c2 >> 6 & 63), w3(128 | c2 & 63); } return slc(ar2, 0, ai2); } function strFromU8(dat, latin1) { if (latin1) { var r4 = ""; for (var i4 = 0; i4 < dat.length; i4 += 16384) r4 += String.fromCharCode.apply(null, dat.subarray(i4, i4 + 16384)); return r4; } else if (td) { return td.decode(dat); } else { var _a25 = dutf8(dat), s2 = _a25.s, r4 = _a25.r; if (r4.length) err(8); return s2; } } function zip(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != "function") err(7); var r4 = {}; fltn(data, "", r4, opts); var k = Object.keys(r4); var lft = k.length, o3 = 0, tot = 0; var slft = lft, files = new Array(lft); var term = []; var tAll = function() { for (var i5 = 0; i5 < term.length; ++i5) term[i5](); }; var cbd = function(a3, b5) { mt2(function() { cb(a3, b5); }); }; mt2(function() { cbd = cb; }); var cbf = function() { var out = new u8(tot + 22), oe = o3, cdl = tot - o3; tot = 0; for (var i5 = 0; i5 < slft; ++i5) { var f2 = files[i5]; try { var l13 = f2.c.length; wzh(out, tot, f2, f2.f, f2.u, l13); var badd = 30 + f2.f.length + exfl(f2.extra); var loc = tot + badd; out.set(f2.c, loc); wzh(out, o3, f2, f2.f, f2.u, l13, tot, f2.m), o3 += 16 + badd + (f2.m ? f2.m.length : 0), tot = loc + l13; } catch (e5) { return cbd(e5, null); } } wzf(out, o3, files.length, cdl, oe); cbd(null, out); }; if (!lft) cbf(); var _loop_1 = function(i5) { var fn2 = k[i5]; var _a25 = r4[fn2], file2 = _a25[0], p2 = _a25[1]; var c2 = crc(), size = file2.length; c2.p(file2); var f2 = strToU8(fn2), s2 = f2.length; var com = p2.comment, m3 = com && strToU8(com), ms2 = m3 && m3.length; var exl = exfl(p2.extra); var compression = p2.level == 0 ? 0 : 8; var cbl = function(e5, d2) { if (e5) { tAll(); cbd(e5, null); } else { var l13 = d2.length; files[i5] = mrg(p2, { size, crc: c2.d(), c: d2, f: f2, m: m3, u: s2 != fn2.length || m3 && com.length != ms2, compression }); o3 += 30 + s2 + exl + l13; tot += 76 + 2 * (s2 + exl) + (ms2 || 0) + l13; if (!--lft) cbf(); } }; if (s2 > 65535) cbl(err(11, 0, 1), null); if (!compression) cbl(null, file2); else if (size < 16e4) { try { cbl(null, deflateSync(file2, p2)); } catch (e5) { cbl(e5, null); } } else term.push(deflate(file2, p2, cbl)); }; for (var i4 = 0; i4 < slft; ++i4) { _loop_1(i4); } return tAll; } function zipSync(data, opts) { if (!opts) opts = {}; var r4 = {}; var files = []; fltn(data, "", r4, opts); var o3 = 0; var tot = 0; for (var fn2 in r4) { var _a25 = r4[fn2], file2 = _a25[0], p2 = _a25[1]; var compression = p2.level == 0 ? 0 : 8; var f2 = strToU8(fn2), s2 = f2.length; var com = p2.comment, m3 = com && strToU8(com), ms2 = m3 && m3.length; var exl = exfl(p2.extra); if (s2 > 65535) err(11); var d2 = compression ? deflateSync(file2, p2) : file2, l13 = d2.length; var c2 = crc(); c2.p(file2); files.push(mrg(p2, { size: file2.length, crc: c2.d(), c: d2, f: f2, m: m3, u: s2 != fn2.length || m3 && com.length != ms2, o: o3, compression })); o3 += 30 + s2 + exl + l13; tot += 76 + 2 * (s2 + exl) + (ms2 || 0) + l13; } var out = new u8(tot + 22), oe = o3, cdl = tot - o3; for (var i4 = 0; i4 < files.length; ++i4) { var f2 = files[i4]; wzh(out, f2.o, f2, f2.f, f2.u, f2.c.length); var badd = 30 + f2.f.length + exfl(f2.extra); out.set(f2.c, f2.o + badd); wzh(out, o3, f2, f2.f, f2.u, f2.c.length, f2.o, f2.m), o3 += 16 + badd + (f2.m ? f2.m.length : 0); } wzf(out, o3, files.length, cdl, oe); return out; } function unzip(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != "function") err(7); var term = []; var tAll = function() { for (var i5 = 0; i5 < term.length; ++i5) term[i5](); }; var files = {}; var cbd = function(a3, b5) { mt2(function() { cb(a3, b5); }); }; mt2(function() { cbd = cb; }); var e5 = data.length - 22; for (; b4(data, e5) != 101010256; --e5) { if (!e5 || data.length - e5 > 65558) { cbd(err(13, 0, 1), null); return tAll; } } ; var lft = b2(data, e5 + 8); if (lft) { var c2 = lft; var o3 = b4(data, e5 + 16); var z2 = b4(data, e5 - 20) == 117853008; if (z2) { var ze2 = b4(data, e5 - 12); z2 = b4(data, ze2) == 101075792; if (z2) { c2 = lft = b4(data, ze2 + 32); o3 = b4(data, ze2 + 48); } } var fltr = opts && opts.filter; var _loop_3 = function(i5) { var _a25 = zh(data, o3, z2), c_1 = _a25[0], sc2 = _a25[1], su = _a25[2], fn2 = _a25[3], no = _a25[4], off = _a25[5], b5 = slzh(data, off); o3 = no; var cbl = function(e6, d2) { if (e6) { tAll(); cbd(e6, null); } else { if (d2) files[fn2] = d2; if (!--lft) cbd(null, files); } }; if (!fltr || fltr({ name: fn2, size: sc2, originalSize: su, compression: c_1 })) { if (!c_1) cbl(null, slc(data, b5, b5 + sc2)); else if (c_1 == 8) { var infl = data.subarray(b5, b5 + sc2); if (su < 524288 || sc2 > 0.8 * su) { try { cbl(null, inflateSync(infl, { out: new u8(su) })); } catch (e6) { cbl(e6, null); } } else term.push(inflate(infl, { size: su }, cbl)); } else cbl(err(14, "unknown compression type " + c_1, 1), null); } else cbl(null, null); }; for (var i4 = 0; i4 < c2; ++i4) { _loop_3(i4); } } else cbd(null, {}); return tAll; } function unzipSync(data, opts) { var files = {}; var e5 = data.length - 22; for (; b4(data, e5) != 101010256; --e5) { if (!e5 || data.length - e5 > 65558) err(13); } ; var c2 = b2(data, e5 + 8); if (!c2) return {}; var o3 = b4(data, e5 + 16); var z2 = b4(data, e5 - 20) == 117853008; if (z2) { var ze2 = b4(data, e5 - 12); z2 = b4(data, ze2) == 101075792; if (z2) { c2 = b4(data, ze2 + 32); o3 = b4(data, ze2 + 48); } } var fltr = opts && opts.filter; for (var i4 = 0; i4 < c2; ++i4) { var _a25 = zh(data, o3, z2), c_2 = _a25[0], sc2 = _a25[1], su = _a25[2], fn2 = _a25[3], no = _a25[4], off = _a25[5], b5 = slzh(data, off); o3 = no; if (!fltr || fltr({ name: fn2, size: sc2, originalSize: su, compression: c_2 })) { if (!c_2) files[fn2] = slc(data, b5, b5 + sc2); else if (c_2 == 8) files[fn2] = inflateSync(data.subarray(b5, b5 + sc2), { out: new u8(su) }); else err(14, "unknown compression type " + c_2); } } return files; } var require2, _a24, Worker, isMarkedAsUntransferable, workerAdd, wk, u8, u16, i32, fleb, fdeb, clim, freb, _a24, fl, revfl, _b18, fd, revfd, rev, x2, i, hMap, flt, i, i, i, i, fdt, i, flm, flrm, fdm, fdrm, max, bits, bits16, shft, slc, FlateErrorCode, ec, err, inflt, wbits, wbits16, hTree, ln2, lc2, clen, wfblk, wblk, deo, et2, dflt, crct, crc, adler, dopt, mrg, wcln, ch, cbfs, wrkr, bInflt, bDflt, gze, guze, zle, zule, pbf, gopt, cbify, astrm, astrmify, b2, b4, b8, wbytes, gzh, gzs, gzl, gzhl, zlh, zls, Deflate, AsyncDeflate, Inflate, AsyncInflate, Gzip, AsyncGzip, Gunzip, AsyncGunzip, Zlib, AsyncZlib, Unzlib, AsyncUnzlib, Decompress, AsyncDecompress, fltn, te2, td, tds, dutf8, DecodeUTF8, EncodeUTF8, dbf, slzh, zh, z64hs, exfl, wzh, wzf, ZipPassThrough, ZipDeflate, AsyncZipDeflate, Zip, UnzipPassThrough, UnzipInflate, AsyncUnzipInflate, Unzip, mt2; var init_esm = __esm({ "node_modules/fflate/esm/index.mjs"() { require2 = createRequire("/"); workerAdd = ";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global"; try { _a24 = require2("worker_threads"), Worker = _a24.Worker, isMarkedAsUntransferable = _a24.isMarkedAsUntransferable; } catch (e5) { } wk = Worker ? function(c2, _2, msg, transfer, cb) { var done = false; var w3 = new Worker(c2 + workerAdd, { eval: true }).on("error", function(e5) { return cb(e5, null); }).on("message", function(m3) { return cb(null, m3); }).on("exit", function(c3) { if (c3 && !done) cb(new Error("exited with code " + c3), null); }); if (isMarkedAsUntransferable) transfer = transfer.filter(function(t4) { return !isMarkedAsUntransferable(t4); }); w3.postMessage(msg, transfer); w3.terminate = function() { done = true; return Worker.prototype.terminate.call(w3); }; return w3; } : function(_2, __, ___, ____, cb) { setImmediate(function() { return cb(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"), null); }); var NOP = function() { }; return { terminate: NOP, postMessage: NOP }; }; u8 = Uint8Array; u16 = Uint16Array; i32 = Int32Array; fleb = new u8([ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0 ]); fdeb = new u8([ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0 ]); clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); freb = function(eb, start) { var b5 = new u16(31); for (var i4 = 0; i4 < 31; ++i4) { b5[i4] = start += 1 << eb[i4 - 1]; } var r4 = new i32(b5[30]); for (var i4 = 1; i4 < 30; ++i4) { for (var j2 = b5[i4]; j2 < b5[i4 + 1]; ++j2) { r4[j2] = j2 - b5[i4] << 5 | i4; } } return { b: b5, r: r4 }; }; _a24 = freb(fleb, 2); fl = _a24.b; revfl = _a24.r; fl[28] = 258, revfl[258] = 28; _b18 = freb(fdeb, 0); fd = _b18.b; revfd = _b18.r; rev = new u16(32768); for (i = 0; i < 32768; ++i) { x2 = (i & 43690) >> 1 | (i & 21845) << 1; x2 = (x2 & 52428) >> 2 | (x2 & 13107) << 2; x2 = (x2 & 61680) >> 4 | (x2 & 3855) << 4; rev[i] = ((x2 & 65280) >> 8 | (x2 & 255) << 8) >> 1; } hMap = (function(cd, mb, r4) { var s2 = cd.length; var i4 = 0; var l13 = new u16(mb); for (; i4 < s2; ++i4) { if (cd[i4]) ++l13[cd[i4] - 1]; } var le2 = new u16(mb); for (i4 = 1; i4 < mb; ++i4) { le2[i4] = le2[i4 - 1] + l13[i4 - 1] << 1; } var co; if (r4) { co = new u16(1 << mb); var rvb = 15 - mb; for (i4 = 0; i4 < s2; ++i4) { if (cd[i4]) { var sv = i4 << 4 | cd[i4]; var r_1 = mb - cd[i4]; var v2 = le2[cd[i4] - 1]++ << r_1; for (var m3 = v2 | (1 << r_1) - 1; v2 <= m3; ++v2) { co[rev[v2] >> rvb] = sv; } } } } else { co = new u16(s2); for (i4 = 0; i4 < s2; ++i4) { if (cd[i4]) { co[i4] = rev[le2[cd[i4] - 1]++] >> 15 - cd[i4]; } } } return co; }); flt = new u8(288); for (i = 0; i < 144; ++i) flt[i] = 8; for (i = 144; i < 256; ++i) flt[i] = 9; for (i = 256; i < 280; ++i) flt[i] = 7; for (i = 280; i < 288; ++i) flt[i] = 8; fdt = new u8(32); for (i = 0; i < 32; ++i) fdt[i] = 5; flm = /* @__PURE__ */ hMap(flt, 9, 0); flrm = /* @__PURE__ */ hMap(flt, 9, 1); fdm = /* @__PURE__ */ hMap(fdt, 5, 0); fdrm = /* @__PURE__ */ hMap(fdt, 5, 1); max = function(a3) { var m3 = a3[0]; for (var i4 = 1; i4 < a3.length; ++i4) { if (a3[i4] > m3) m3 = a3[i4]; } return m3; }; bits = function(d2, p2, m3) { var o3 = p2 / 8 | 0; return (d2[o3] | d2[o3 + 1] << 8) >> (p2 & 7) & m3; }; bits16 = function(d2, p2) { var o3 = p2 / 8 | 0; return (d2[o3] | d2[o3 + 1] << 8 | d2[o3 + 2] << 16) >> (p2 & 7); }; shft = function(p2) { return (p2 + 7) / 8 | 0; }; slc = function(v2, s2, e5) { if (s2 == null || s2 < 0) s2 = 0; if (e5 == null || e5 > v2.length) e5 = v2.length; return new u8(v2.subarray(s2, e5)); }; FlateErrorCode = { UnexpectedEOF: 0, InvalidBlockType: 1, InvalidLengthLiteral: 2, InvalidDistance: 3, StreamFinished: 4, NoStreamHandler: 5, InvalidHeader: 6, NoCallback: 7, InvalidUTF8: 8, ExtraFieldTooLong: 9, InvalidDate: 10, FilenameTooLong: 11, StreamFinishing: 12, InvalidZipData: 13, UnknownCompressionMethod: 14 }; ec = [ "unexpected EOF", "invalid block type", "invalid length/literal", "invalid distance", "stream finished", "no stream handler", , // determined by compression function "no callback", "invalid UTF-8 data", "extra field too long", "date not in range 1980-2099", "filename too long", "stream finishing", "invalid zip data" // determined by unknown compression method ]; err = function(ind, msg, nt2) { var e5 = new Error(msg || ec[ind]); e5.code = ind; if (Error.captureStackTrace) Error.captureStackTrace(e5, err); if (!nt2) throw e5; return e5; }; inflt = function(dat, st2, buf, dict) { var sl = dat.length, dl = dict ? dict.length : 0; if (!sl || st2.f && !st2.l) return buf || new u8(0); var noBuf = !buf; var resize = noBuf || st2.i != 2; var noSt = st2.i; if (noBuf) buf = new u8(sl * 3); var cbuf = function(l14) { var bl = buf.length; if (l14 > bl) { var nbuf = new u8(Math.max(bl * 2, l14)); nbuf.set(buf); buf = nbuf; } }; var final = st2.f || 0, pos = st2.p || 0, bt2 = st2.b || 0, lm = st2.l, dm = st2.d, lbt = st2.m, dbt = st2.n; var tbts = sl * 8; do { if (!lm) { final = bits(dat, pos, 1); var type = bits(dat, pos + 1, 3); pos += 3; if (!type) { var s2 = shft(pos) + 4, l13 = dat[s2 - 4] | dat[s2 - 3] << 8, t4 = s2 + l13; if (t4 > sl) { if (noSt) err(0); break; } if (resize) cbuf(bt2 + l13); buf.set(dat.subarray(s2, t4), bt2); st2.b = bt2 += l13, st2.p = pos = t4 * 8, st2.f = final; continue; } else if (type == 1) lm = flrm, dm = fdrm, lbt = 9, dbt = 5; else if (type == 2) { var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; var tl = hLit + bits(dat, pos + 5, 31) + 1; pos += 14; var ldt = new u8(tl); var clt = new u8(19); for (var i4 = 0; i4 < hcLen; ++i4) { clt[clim[i4]] = bits(dat, pos + i4 * 3, 7); } pos += hcLen * 3; var clb = max(clt), clbmsk = (1 << clb) - 1; var clm = hMap(clt, clb, 1); for (var i4 = 0; i4 < tl; ) { var r4 = clm[bits(dat, pos, clbmsk)]; pos += r4 & 15; var s2 = r4 >> 4; if (s2 < 16) { ldt[i4++] = s2; } else { var c2 = 0, n5 = 0; if (s2 == 16) n5 = 3 + bits(dat, pos, 3), pos += 2, c2 = ldt[i4 - 1]; else if (s2 == 17) n5 = 3 + bits(dat, pos, 7), pos += 3; else if (s2 == 18) n5 = 11 + bits(dat, pos, 127), pos += 7; while (n5--) ldt[i4++] = c2; } } var lt2 = ldt.subarray(0, hLit), dt2 = ldt.subarray(hLit); lbt = max(lt2); dbt = max(dt2); lm = hMap(lt2, lbt, 1); dm = hMap(dt2, dbt, 1); } else err(1); if (pos > tbts) { if (noSt) err(0); break; } } if (resize) cbuf(bt2 + 131072); var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; var lpos = pos; for (; ; lpos = pos) { var c2 = lm[bits16(dat, pos) & lms], sym = c2 >> 4; pos += c2 & 15; if (pos > tbts) { if (noSt) err(0); break; } if (!c2) err(2); if (sym < 256) buf[bt2++] = sym; else if (sym == 256) { lpos = pos, lm = null; break; } else { var add = sym - 254; if (sym > 264) { var i4 = sym - 257, b5 = fleb[i4]; add = bits(dat, pos, (1 << b5) - 1) + fl[i4]; pos += b5; } var d2 = dm[bits16(dat, pos) & dms], dsym = d2 >> 4; if (!d2) err(3); pos += d2 & 15; var dt2 = fd[dsym]; if (dsym > 3) { var b5 = fdeb[dsym]; dt2 += bits16(dat, pos) & (1 << b5) - 1, pos += b5; } if (pos > tbts) { if (noSt) err(0); break; } if (resize) cbuf(bt2 + 131072); var end = bt2 + add; if (bt2 < dt2) { var shift = dl - dt2, dend = Math.min(dt2, end); if (shift + bt2 < 0) err(3); for (; bt2 < dend; ++bt2) buf[bt2] = dict[shift + bt2]; } for (; bt2 < end; ++bt2) buf[bt2] = buf[bt2 - dt2]; } } st2.l = lm, st2.p = lpos, st2.b = bt2, st2.f = final; if (lm) final = 1, st2.m = lbt, st2.d = dm, st2.n = dbt; } while (!final); return bt2 != buf.length && noBuf ? slc(buf, 0, bt2) : buf.subarray(0, bt2); }; wbits = function(d2, p2, v2) { v2 <<= p2 & 7; var o3 = p2 / 8 | 0; d2[o3] |= v2; d2[o3 + 1] |= v2 >> 8; }; wbits16 = function(d2, p2, v2) { v2 <<= p2 & 7; var o3 = p2 / 8 | 0; d2[o3] |= v2; d2[o3 + 1] |= v2 >> 8; d2[o3 + 2] |= v2 >> 16; }; hTree = function(d2, mb) { var t4 = []; for (var i4 = 0; i4 < d2.length; ++i4) { if (d2[i4]) t4.push({ s: i4, f: d2[i4] }); } var s2 = t4.length; var t22 = t4.slice(); if (!s2) return { t: et2, l: 0 }; if (s2 == 1) { var v2 = new u8(t4[0].s + 1); v2[t4[0].s] = 1; return { t: v2, l: 1 }; } t4.sort(function(a3, b5) { return a3.f - b5.f; }); t4.push({ s: -1, f: 25001 }); var l13 = t4[0], r4 = t4[1], i0 = 0, i1 = 1, i22 = 2; t4[0] = { s: -1, f: l13.f + r4.f, l: l13, r: r4 }; while (i1 != s2 - 1) { l13 = t4[t4[i0].f < t4[i22].f ? i0++ : i22++]; r4 = t4[i0 != i1 && t4[i0].f < t4[i22].f ? i0++ : i22++]; t4[i1++] = { s: -1, f: l13.f + r4.f, l: l13, r: r4 }; } var maxSym = t22[0].s; for (var i4 = 1; i4 < s2; ++i4) { if (t22[i4].s > maxSym) maxSym = t22[i4].s; } var tr2 = new u16(maxSym + 1); var mbt = ln2(t4[i1 - 1], tr2, 0); if (mbt > mb) { var i4 = 0, dt2 = 0; var lft = mbt - mb, cst = 1 << lft; t22.sort(function(a3, b5) { return tr2[b5.s] - tr2[a3.s] || a3.f - b5.f; }); for (; i4 < s2; ++i4) { var i2_1 = t22[i4].s; if (tr2[i2_1] > mb) { dt2 += cst - (1 << mbt - tr2[i2_1]); tr2[i2_1] = mb; } else break; } dt2 >>= lft; while (dt2 > 0) { var i2_2 = t22[i4].s; if (tr2[i2_2] < mb) dt2 -= 1 << mb - tr2[i2_2]++ - 1; else ++i4; } for (; i4 >= 0 && dt2; --i4) { var i2_3 = t22[i4].s; if (tr2[i2_3] == mb) { --tr2[i2_3]; ++dt2; } } mbt = mb; } return { t: new u8(tr2), l: mbt }; }; ln2 = function(n5, l13, d2) { return n5.s == -1 ? Math.max(ln2(n5.l, l13, d2 + 1), ln2(n5.r, l13, d2 + 1)) : l13[n5.s] = d2; }; lc2 = function(c2) { var s2 = c2.length; while (s2 && !c2[--s2]) ; var cl = new u16(++s2); var cli = 0, cln = c2[0], cls = 1; var w3 = function(v2) { cl[cli++] = v2; }; for (var i4 = 1; i4 <= s2; ++i4) { if (c2[i4] == cln && i4 != s2) ++cls; else { if (!cln && cls > 2) { for (; cls > 138; cls -= 138) w3(32754); if (cls > 2) { w3(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305); cls = 0; } } else if (cls > 3) { w3(cln), --cls; for (; cls > 6; cls -= 6) w3(8304); if (cls > 2) w3(cls - 3 << 5 | 8208), cls = 0; } while (cls--) w3(cln); cls = 1; cln = c2[i4]; } } return { c: cl.subarray(0, cli), n: s2 }; }; clen = function(cf, cl) { var l13 = 0; for (var i4 = 0; i4 < cl.length; ++i4) l13 += cf[i4] * cl[i4]; return l13; }; wfblk = function(out, pos, dat) { var s2 = dat.length; var o3 = shft(pos + 2); out[o3] = s2 & 255; out[o3 + 1] = s2 >> 8; out[o3 + 2] = out[o3] ^ 255; out[o3 + 3] = out[o3 + 1] ^ 255; for (var i4 = 0; i4 < s2; ++i4) out[o3 + i4 + 4] = dat[i4]; return (o3 + 4 + s2) * 8; }; wblk = function(dat, out, final, syms, lf, df, eb, li2, bs2, bl, p2) { wbits(out, p2++, final); ++lf[256]; var _a25 = hTree(lf, 15), dlt = _a25.t, mlb = _a25.l; var _b19 = hTree(df, 15), ddt = _b19.t, mdb = _b19.l; var _c = lc2(dlt), lclt = _c.c, nlc = _c.n; var _d = lc2(ddt), lcdt = _d.c, ndc = _d.n; var lcfreq = new u16(19); for (var i4 = 0; i4 < lclt.length; ++i4) ++lcfreq[lclt[i4] & 31]; for (var i4 = 0; i4 < lcdt.length; ++i4) ++lcfreq[lcdt[i4] & 31]; var _e2 = hTree(lcfreq, 7), lct = _e2.t, mlcb = _e2.l; var nlcc = 19; for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) ; var flen = bl + 5 << 3; var ftlen = clen(lf, flt) + clen(df, fdt) + eb; var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]; if (bs2 >= 0 && flen <= ftlen && flen <= dtlen) return wfblk(out, p2, dat.subarray(bs2, bs2 + bl)); var lm, ll, dm, dl; wbits(out, p2, 1 + (dtlen < ftlen)), p2 += 2; if (dtlen < ftlen) { lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; var llm = hMap(lct, mlcb, 0); wbits(out, p2, nlc - 257); wbits(out, p2 + 5, ndc - 1); wbits(out, p2 + 10, nlcc - 4); p2 += 14; for (var i4 = 0; i4 < nlcc; ++i4) wbits(out, p2 + 3 * i4, lct[clim[i4]]); p2 += 3 * nlcc; var lcts = [lclt, lcdt]; for (var it2 = 0; it2 < 2; ++it2) { var clct = lcts[it2]; for (var i4 = 0; i4 < clct.length; ++i4) { var len = clct[i4] & 31; wbits(out, p2, llm[len]), p2 += lct[len]; if (len > 15) wbits(out, p2, clct[i4] >> 5 & 127), p2 += clct[i4] >> 12; } } } else { lm = flm, ll = flt, dm = fdm, dl = fdt; } for (var i4 = 0; i4 < li2; ++i4) { var sym = syms[i4]; if (sym > 255) { var len = sym >> 18 & 31; wbits16(out, p2, lm[len + 257]), p2 += ll[len + 257]; if (len > 7) wbits(out, p2, sym >> 23 & 31), p2 += fleb[len]; var dst = sym & 31; wbits16(out, p2, dm[dst]), p2 += dl[dst]; if (dst > 3) wbits16(out, p2, sym >> 5 & 8191), p2 += fdeb[dst]; } else { wbits16(out, p2, lm[sym]), p2 += ll[sym]; } } wbits16(out, p2, lm[256]); return p2 + ll[256]; }; deo = /* @__PURE__ */ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); et2 = /* @__PURE__ */ new u8(0); dflt = function(dat, lvl, plvl, pre, post, st2) { var s2 = st2.z || dat.length; var o3 = new u8(pre + s2 + 5 * (1 + Math.ceil(s2 / 7e3)) + post); var w3 = o3.subarray(pre, o3.length - post); var lst = st2.l; var pos = (st2.r || 0) & 7; if (lvl) { if (pos) w3[0] = st2.r >> 3; var opt = deo[lvl - 1]; var n5 = opt >> 13, c2 = opt & 8191; var msk_1 = (1 << plvl) - 1; var prev = st2.p || new u16(32768), head = st2.h || new u16(msk_1 + 1); var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; var hsh = function(i5) { return (dat[i5] ^ dat[i5 + 1] << bs1_1 ^ dat[i5 + 2] << bs2_1) & msk_1; }; var syms = new i32(25e3); var lf = new u16(288), df = new u16(32); var lc_1 = 0, eb = 0, i4 = st2.i || 0, li2 = 0, wi2 = st2.w || 0, bs2 = 0; for (; i4 + 2 < s2; ++i4) { var hv = hsh(i4); var imod = i4 & 32767, pimod = head[hv]; prev[imod] = pimod; head[hv] = imod; if (wi2 <= i4) { var rem = s2 - i4; if ((lc_1 > 7e3 || li2 > 24576) && (rem > 423 || !lst)) { pos = wblk(dat, w3, 0, syms, lf, df, eb, li2, bs2, i4 - bs2, pos); li2 = lc_1 = eb = 0, bs2 = i4; for (var j2 = 0; j2 < 286; ++j2) lf[j2] = 0; for (var j2 = 0; j2 < 30; ++j2) df[j2] = 0; } var l13 = 2, d2 = 0, ch_1 = c2, dif = imod - pimod & 32767; if (rem > 2 && hv == hsh(i4 - dif)) { var maxn = Math.min(n5, rem) - 1; var maxd = Math.min(32767, i4); var ml = Math.min(258, rem); while (dif <= maxd && --ch_1 && imod != pimod) { if (dat[i4 + l13] == dat[i4 + l13 - dif]) { var nl = 0; for (; nl < ml && dat[i4 + nl] == dat[i4 + nl - dif]; ++nl) ; if (nl > l13) { l13 = nl, d2 = dif; if (nl > maxn) break; var mmd = Math.min(dif, nl - 2); var md = 0; for (var j2 = 0; j2 < mmd; ++j2) { var ti2 = i4 - dif + j2 & 32767; var pti = prev[ti2]; var cd = ti2 - pti & 32767; if (cd > md) md = cd, pimod = ti2; } } } imod = pimod, pimod = prev[imod]; dif += imod - pimod & 32767; } } if (d2) { syms[li2++] = 268435456 | revfl[l13] << 18 | revfd[d2]; var lin = revfl[l13] & 31, din = revfd[d2] & 31; eb += fleb[lin] + fdeb[din]; ++lf[257 + lin]; ++df[din]; wi2 = i4 + l13; ++lc_1; } else { syms[li2++] = dat[i4]; ++lf[dat[i4]]; } } } for (i4 = Math.max(i4, wi2); i4 < s2; ++i4) { syms[li2++] = dat[i4]; ++lf[dat[i4]]; } pos = wblk(dat, w3, lst, syms, lf, df, eb, li2, bs2, i4 - bs2, pos); if (!lst) { st2.r = pos & 7 | w3[pos / 8 | 0] << 3; pos -= 7; st2.h = head, st2.p = prev, st2.i = i4, st2.w = wi2; } } else { for (var i4 = st2.w || 0; i4 < s2 + lst; i4 += 65535) { var e5 = i4 + 65535; if (e5 >= s2) { w3[pos / 8 | 0] = lst; e5 = s2; } pos = wfblk(w3, pos + 1, dat.subarray(i4, e5)); } st2.i = s2; } return slc(o3, 0, pre + shft(pos) + post); }; crct = /* @__PURE__ */ (function() { var t4 = new Int32Array(256); for (var i4 = 0; i4 < 256; ++i4) { var c2 = i4, k = 9; while (--k) c2 = (c2 & 1 && -306674912) ^ c2 >>> 1; t4[i4] = c2; } return t4; })(); crc = function() { var c2 = -1; return { p: function(d2) { var cr2 = c2; for (var i4 = 0; i4 < d2.length; ++i4) cr2 = crct[cr2 & 255 ^ d2[i4]] ^ cr2 >>> 8; c2 = cr2; }, d: function() { return ~c2; } }; }; adler = function() { var a3 = 1, b5 = 0; return { p: function(d2) { var n5 = a3, m3 = b5; var l13 = d2.length | 0; for (var i4 = 0; i4 != l13; ) { var e5 = Math.min(i4 + 2655, l13); for (; i4 < e5; ++i4) m3 += n5 += d2[i4]; n5 = (n5 & 65535) + 15 * (n5 >> 16), m3 = (m3 & 65535) + 15 * (m3 >> 16); } a3 = n5, b5 = m3; }, d: function() { a3 %= 65521, b5 %= 65521; return (a3 & 255) << 24 | (a3 & 65280) << 8 | (b5 & 255) << 8 | b5 >> 8; } }; }; dopt = function(dat, opt, pre, post, st2) { if (!st2) { st2 = { l: 1 }; if (opt.dictionary) { var dict = opt.dictionary.subarray(-32768); var newDat = new u8(dict.length + dat.length); newDat.set(dict); newDat.set(dat, dict.length); dat = newDat; st2.w = dict.length; } } return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st2.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st2); }; mrg = function(a3, b5) { var o3 = {}; for (var k in a3) o3[k] = a3[k]; for (var k in b5) o3[k] = b5[k]; return o3; }; wcln = function(fn2, fnStr, td2) { var dt2 = fn2(); var st2 = fn2.toString(); var ks2 = st2.slice(st2.indexOf("[") + 1, st2.lastIndexOf("]")).replace(/\s+/g, "").split(","); for (var i4 = 0; i4 < dt2.length; ++i4) { var v2 = dt2[i4], k = ks2[i4]; if (typeof v2 == "function") { fnStr += ";" + k + "="; var st_1 = v2.toString(); if (v2.prototype) { if (st_1.indexOf("[native code]") != -1) { var spInd = st_1.indexOf(" ", 8) + 1; fnStr += st_1.slice(spInd, st_1.indexOf("(", spInd)); } else { fnStr += st_1; for (var t4 in v2.prototype) fnStr += ";" + k + ".prototype." + t4 + "=" + v2.prototype[t4].toString(); } } else fnStr += st_1; } else td2[k] = v2; } return fnStr; }; ch = []; cbfs = function(v2) { var tl = []; for (var k in v2) { if (v2[k].buffer) { tl.push((v2[k] = new v2[k].constructor(v2[k])).buffer); } } return tl; }; wrkr = function(fns, init, id, cb) { if (!ch[id]) { var fnStr = "", td_1 = {}, m3 = fns.length - 1; for (var i4 = 0; i4 < m3; ++i4) fnStr = wcln(fns[i4], fnStr, td_1); ch[id] = { c: wcln(fns[m3], fnStr, td_1), e: td_1 }; } var td2 = mrg({}, ch[id].e); return wk(ch[id].c + ";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=" + init.toString() + "}", id, td2, cbfs(td2), cb); }; bInflt = function() { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; }; bDflt = function() { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et2, hMap, wbits, wbits16, hTree, ln2, lc2, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; }; gze = function() { return [gzh, gzhl, wbytes, crc, crct]; }; guze = function() { return [gzs, gzl]; }; zle = function() { return [zlh, wbytes, adler]; }; zule = function() { return [zls]; }; pbf = function(msg) { return postMessage(msg, [msg.buffer]); }; gopt = function(o3) { return o3 && { out: o3.size && new u8(o3.size), dictionary: o3.dictionary }; }; cbify = function(dat, opts, fns, init, id, cb) { var w3 = wrkr(fns, init, id, function(err2, dat2) { w3.terminate(); cb(err2, dat2); }); w3.postMessage([dat, opts], opts.consume ? [dat.buffer] : []); return function() { w3.terminate(); }; }; astrm = function(strm) { strm.ondata = function(dat, final) { return postMessage([dat, final], [dat.buffer]); }; return function(ev) { if (ev.data[0]) { strm.push(ev.data[0], ev.data[1]); postMessage([ev.data[0].length]); } else strm.flush(ev.data[1]); }; }; astrmify = function(fns, strm, opts, init, id, flush, ext) { var t4; var w3 = wrkr(fns, init, id, function(err2, dat) { if (err2) w3.terminate(), strm.ondata.call(strm, err2); else if (!Array.isArray(dat)) ext(dat); else if (dat.length == 1) { strm.queuedSize -= dat[0]; if (strm.ondrain) strm.ondrain(dat[0]); } else { if (dat[1]) w3.terminate(); strm.ondata.call(strm, err2, dat[0], dat[1]); } }); w3.postMessage(opts); strm.queuedSize = 0; strm.push = function(d2, f2) { if (!strm.ondata) err(5); if (t4) strm.ondata(err(4, 0, 1), null, !!f2); strm.queuedSize += d2.length; w3.postMessage([d2, t4 = f2], d2.buffer instanceof ArrayBuffer ? [d2.buffer] : []); }; strm.terminate = function() { w3.terminate(); }; if (flush) { strm.flush = function(sync) { w3.postMessage([0, sync]); }; } }; b2 = function(d2, b5) { return d2[b5] | d2[b5 + 1] << 8; }; b4 = function(d2, b5) { return (d2[b5] | d2[b5 + 1] << 8 | d2[b5 + 2] << 16 | d2[b5 + 3] << 24) >>> 0; }; b8 = function(d2, b5) { return b4(d2, b5) + b4(d2, b5 + 4) * 4294967296; }; wbytes = function(d2, b5, v2) { for (; v2; ++b5) d2[b5] = v2, v2 >>>= 8; }; gzh = function(c2, o3) { var fn2 = o3.filename; c2[0] = 31, c2[1] = 139, c2[2] = 8, c2[8] = o3.level < 2 ? 4 : o3.level == 9 ? 2 : 0, c2[9] = 3; if (o3.mtime != 0) wbytes(c2, 4, Math.floor(new Date(o3.mtime || Date.now()) / 1e3)); if (fn2) { c2[3] = 8; for (var i4 = 0; i4 <= fn2.length; ++i4) c2[i4 + 10] = fn2.charCodeAt(i4); } }; gzs = function(d2) { if (d2[0] != 31 || d2[1] != 139 || d2[2] != 8) err(6, "invalid gzip data"); var flg = d2[3]; var st2 = 10; if (flg & 4) st2 += (d2[10] | d2[11] << 8) + 2; for (var zs2 = (flg >> 3 & 1) + (flg >> 4 & 1); zs2 > 0; zs2 -= !d2[st2++]) ; return st2 + (flg & 2); }; gzl = function(d2) { var l13 = d2.length; return (d2[l13 - 4] | d2[l13 - 3] << 8 | d2[l13 - 2] << 16 | d2[l13 - 1] << 24) >>> 0; }; gzhl = function(o3) { return 10 + (o3.filename ? o3.filename.length + 1 : 0); }; zlh = function(c2, o3) { var lv = o3.level, fl2 = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; c2[0] = 120, c2[1] = fl2 << 6 | (o3.dictionary && 32); c2[1] |= 31 - (c2[0] << 8 | c2[1]) % 31; if (o3.dictionary) { var h2 = adler(); h2.p(o3.dictionary); wbytes(c2, 2, h2.d()); } }; zls = function(d2, dict) { if ((d2[0] & 15) != 8 || d2[0] >> 4 > 7 || (d2[0] << 8 | d2[1]) % 31) err(6, "invalid zlib data"); if ((d2[1] >> 5 & 1) == +!dict) err(6, "invalid zlib data: " + (d2[1] & 32 ? "need" : "unexpected") + " dictionary"); return (d2[1] >> 3 & 4) + 2; }; Deflate = /* @__PURE__ */ (function() { function Deflate2(opts, cb) { if (typeof opts == "function") cb = opts, opts = {}; this.ondata = cb; this.o = opts || {}; this.s = { l: 0, i: 32768, w: 32768, z: 32768 }; this.b = new u8(98304); if (this.o.dictionary) { var dict = this.o.dictionary.subarray(-32768); this.b.set(dict, 32768 - dict.length); this.s.i = 32768 - dict.length; } } Deflate2.prototype.p = function(c2, f2) { this.ondata(dopt(c2, this.o, 0, 0, this.s), f2); }; Deflate2.prototype.push = function(chunk, final) { if (!this.ondata) err(5); if (this.s.l) err(4); var endLen = chunk.length + this.s.z; if (endLen > this.b.length) { if (endLen > 2 * this.b.length - 32768) { var newBuf = new u8(endLen & -32768); newBuf.set(this.b.subarray(0, this.s.z)); this.b = newBuf; } var split = this.b.length - this.s.z; this.b.set(chunk.subarray(0, split), this.s.z); this.s.z = this.b.length; this.p(this.b, false); this.b.set(this.b.subarray(-32768)); this.b.set(chunk.subarray(split), 32768); this.s.z = chunk.length - split + 32768; this.s.i = 32766, this.s.w = 32768; } else { this.b.set(chunk, this.s.z); this.s.z += chunk.length; } this.s.l = final & 1; if (this.s.z > this.s.w + 8191 || final) { this.p(this.b, final || false); this.s.w = this.s.i, this.s.i -= 2; } if (final) { this.s = this.o = {}; this.b = et2; } }; Deflate2.prototype.flush = function(sync) { if (!this.ondata) err(5); if (this.s.l) err(4); this.p(this.b, false); this.s.w = this.s.i, this.s.i -= 2; if (sync) { var c2 = new u8(6); c2[0] = this.s.r >> 3; var ep = wfblk(c2, this.s.r, et2); this.s.r = 0; this.ondata(c2.subarray(0, ep >> 3), false); } }; return Deflate2; })(); AsyncDeflate = /* @__PURE__ */ (function() { function AsyncDeflate2(opts, cb) { astrmify([ bDflt, function() { return [astrm, Deflate]; } ], this, StrmOpt.call(this, opts, cb), function(ev) { var strm = new Deflate(ev.data); onmessage = astrm(strm); }, 6, 1); } return AsyncDeflate2; })(); Inflate = /* @__PURE__ */ (function() { function Inflate2(opts, cb) { if (typeof opts == "function") cb = opts, opts = {}; this.ondata = cb; var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768); this.s = { i: 0, b: dict ? dict.length : 0 }; this.o = new u8(32768); this.p = new u8(0); if (dict) this.o.set(dict); } Inflate2.prototype.e = function(c2) { if (!this.ondata) err(5); if (this.d) err(4); if (!this.p.length) this.p = c2; else if (c2.length) { var n5 = new u8(this.p.length + c2.length); n5.set(this.p), n5.set(c2, this.p.length), this.p = n5; } }; Inflate2.prototype.c = function(final) { this.s.i = +(this.d = final || false); var bts = this.s.b; var dt2 = inflt(this.p, this.s, this.o); this.ondata(slc(dt2, bts, this.s.b), this.d); this.o = slc(dt2, this.s.b - 32768), this.s.b = this.o.length; this.p = slc(this.p, this.s.p / 8 | 0), this.s.p &= 7; }; Inflate2.prototype.push = function(chunk, final) { this.e(chunk), this.c(final); }; return Inflate2; })(); AsyncInflate = /* @__PURE__ */ (function() { function AsyncInflate2(opts, cb) { astrmify([ bInflt, function() { return [astrm, Inflate]; } ], this, StrmOpt.call(this, opts, cb), function(ev) { var strm = new Inflate(ev.data); onmessage = astrm(strm); }, 7, 0); } return AsyncInflate2; })(); Gzip = /* @__PURE__ */ (function() { function Gzip2(opts, cb) { this.c = crc(); this.l = 0; this.v = 1; Deflate.call(this, opts, cb); } Gzip2.prototype.push = function(chunk, final) { this.c.p(chunk); this.l += chunk.length; Deflate.prototype.push.call(this, chunk, final); }; Gzip2.prototype.p = function(c2, f2) { var raw = dopt(c2, this.o, this.v && gzhl(this.o), f2 && 8, this.s); if (this.v) gzh(raw, this.o), this.v = 0; if (f2) wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l); this.ondata(raw, f2); }; Gzip2.prototype.flush = function(sync) { Deflate.prototype.flush.call(this, sync); }; return Gzip2; })(); AsyncGzip = /* @__PURE__ */ (function() { function AsyncGzip2(opts, cb) { astrmify([ bDflt, gze, function() { return [astrm, Deflate, Gzip]; } ], this, StrmOpt.call(this, opts, cb), function(ev) { var strm = new Gzip(ev.data); onmessage = astrm(strm); }, 8, 1); } return AsyncGzip2; })(); Gunzip = /* @__PURE__ */ (function() { function Gunzip2(opts, cb) { this.v = 1; this.r = 0; Inflate.call(this, opts, cb); } Gunzip2.prototype.push = function(chunk, final) { Inflate.prototype.e.call(this, chunk); this.r += chunk.length; if (this.v) { var p2 = this.p.subarray(this.v - 1); var s2 = p2.length > 3 ? gzs(p2) : 4; if (s2 > p2.length) { if (!final) return; } else if (this.v > 1 && this.onmember) { this.onmember(this.r - p2.length); } this.p = p2.subarray(s2), this.v = 0; } Inflate.prototype.c.call(this, 0); if (this.s.f && !this.s.l) { this.v = shft(this.s.p) + 9; this.s = { i: 0 }; this.o = new u8(0); this.push(new u8(0), final); } else if (final) { Inflate.prototype.c.call(this, final); } }; return Gunzip2; })(); AsyncGunzip = /* @__PURE__ */ (function() { function AsyncGunzip2(opts, cb) { var _this = this; astrmify([ bInflt, guze, function() { return [astrm, Inflate, Gunzip]; } ], this, StrmOpt.call(this, opts, cb), function(ev) { var strm = new Gunzip(ev.data); strm.onmember = function(offset) { return postMessage(offset); }; onmessage = astrm(strm); }, 9, 0, function(offset) { return _this.onmember && _this.onmember(offset); }); } return AsyncGunzip2; })(); Zlib = /* @__PURE__ */ (function() { function Zlib2(opts, cb) { this.c = adler(); this.v = 1; Deflate.call(this, opts, cb); } Zlib2.prototype.push = function(chunk, final) { this.c.p(chunk); Deflate.prototype.push.call(this, chunk, final); }; Zlib2.prototype.p = function(c2, f2) { var raw = dopt(c2, this.o, this.v && (this.o.dictionary ? 6 : 2), f2 && 4, this.s); if (this.v) zlh(raw, this.o), this.v = 0; if (f2) wbytes(raw, raw.length - 4, this.c.d()); this.ondata(raw, f2); }; Zlib2.prototype.flush = function(sync) { Deflate.prototype.flush.call(this, sync); }; return Zlib2; })(); AsyncZlib = /* @__PURE__ */ (function() { function AsyncZlib2(opts, cb) { astrmify([ bDflt, zle, function() { return [astrm, Deflate, Zlib]; } ], this, StrmOpt.call(this, opts, cb), function(ev) { var strm = new Zlib(ev.data); onmessage = astrm(strm); }, 10, 1); } return AsyncZlib2; })(); Unzlib = /* @__PURE__ */ (function() { function Unzlib2(opts, cb) { Inflate.call(this, opts, cb); this.v = opts && opts.dictionary ? 2 : 1; } Unzlib2.prototype.push = function(chunk, final) { Inflate.prototype.e.call(this, chunk); if (this.v) { if (this.p.length < 6 && !final) return; this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0; } if (final) { if (this.p.length < 4) err(6, "invalid zlib data"); this.p = this.p.subarray(0, -4); } Inflate.prototype.c.call(this, final); }; return Unzlib2; })(); AsyncUnzlib = /* @__PURE__ */ (function() { function AsyncUnzlib2(opts, cb) { astrmify([ bInflt, zule, function() { return [astrm, Inflate, Unzlib]; } ], this, StrmOpt.call(this, opts, cb), function(ev) { var strm = new Unzlib(ev.data); onmessage = astrm(strm); }, 11, 0); } return AsyncUnzlib2; })(); Decompress = /* @__PURE__ */ (function() { function Decompress2(opts, cb) { this.o = StrmOpt.call(this, opts, cb) || {}; this.G = Gunzip; this.I = Inflate; this.Z = Unzlib; } Decompress2.prototype.i = function() { var _this = this; this.s.ondata = function(dat, final) { _this.ondata(dat, final); }; }; Decompress2.prototype.push = function(chunk, final) { if (!this.ondata) err(5); if (!this.s) { if (this.p && this.p.length) { var n5 = new u8(this.p.length + chunk.length); n5.set(this.p), n5.set(chunk, this.p.length); } else this.p = chunk; if (this.p.length > 2) { this.s = this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8 ? new this.G(this.o) : (this.p[0] & 15) != 8 || this.p[0] >> 4 > 7 || (this.p[0] << 8 | this.p[1]) % 31 ? new this.I(this.o) : new this.Z(this.o); this.i(); this.s.push(this.p, final); this.p = null; } } else this.s.push(chunk, final); }; return Decompress2; })(); AsyncDecompress = /* @__PURE__ */ (function() { function AsyncDecompress2(opts, cb) { Decompress.call(this, opts, cb); this.queuedSize = 0; this.G = AsyncGunzip; this.I = AsyncInflate; this.Z = AsyncUnzlib; } AsyncDecompress2.prototype.i = function() { var _this = this; this.s.ondata = function(err2, dat, final) { _this.ondata(err2, dat, final); }; this.s.ondrain = function(size) { _this.queuedSize -= size; if (_this.ondrain) _this.ondrain(size); }; }; AsyncDecompress2.prototype.push = function(chunk, final) { this.queuedSize += chunk.length; Decompress.prototype.push.call(this, chunk, final); }; return AsyncDecompress2; })(); fltn = function(d2, p2, t4, o3) { for (var k in d2) { var val = d2[k], n5 = p2 + k, op = o3; if (Array.isArray(val)) op = mrg(o3, val[1]), val = val[0]; if (ArrayBuffer.isView(val)) t4[n5] = [val, op]; else { t4[n5 += "/"] = [new u8(0), op]; fltn(val, n5, t4, o3); } } }; te2 = typeof TextEncoder != "undefined" && /* @__PURE__ */ new TextEncoder(); td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder(); tds = 0; try { td.decode(et2, { stream: true }); tds = 1; } catch (e5) { } dutf8 = function(d2) { for (var r4 = "", i4 = 0; ; ) { var c2 = d2[i4++]; var eb = (c2 > 127) + (c2 > 223) + (c2 > 239); if (i4 + eb > d2.length) return { s: r4, r: slc(d2, i4 - 1) }; if (!eb) r4 += String.fromCharCode(c2); else if (eb == 3) { c2 = ((c2 & 15) << 18 | (d2[i4++] & 63) << 12 | (d2[i4++] & 63) << 6 | d2[i4++] & 63) - 65536, r4 += String.fromCharCode(55296 | c2 >> 10, 56320 | c2 & 1023); } else if (eb & 1) r4 += String.fromCharCode((c2 & 31) << 6 | d2[i4++] & 63); else r4 += String.fromCharCode((c2 & 15) << 12 | (d2[i4++] & 63) << 6 | d2[i4++] & 63); } }; DecodeUTF8 = /* @__PURE__ */ (function() { function DecodeUTF82(cb) { this.ondata = cb; if (tds) this.t = new TextDecoder(); else this.p = et2; } DecodeUTF82.prototype.push = function(chunk, final) { if (!this.ondata) err(5); final = !!final; if (this.t) { this.ondata(this.t.decode(chunk, { stream: true }), final); if (final) { if (this.t.decode().length) err(8); this.t = null; } return; } if (!this.p) err(4); var dat = new u8(this.p.length + chunk.length); dat.set(this.p); dat.set(chunk, this.p.length); var _a25 = dutf8(dat), s2 = _a25.s, r4 = _a25.r; if (final) { if (r4.length) err(8); this.p = null; } else this.p = r4; this.ondata(s2, final); }; return DecodeUTF82; })(); EncodeUTF8 = /* @__PURE__ */ (function() { function EncodeUTF82(cb) { this.ondata = cb; } EncodeUTF82.prototype.push = function(chunk, final) { if (!this.ondata) err(5); if (this.d) err(4); this.ondata(strToU8(chunk), this.d = final || false); }; return EncodeUTF82; })(); dbf = function(l13) { return l13 == 1 ? 3 : l13 < 6 ? 2 : l13 == 9 ? 1 : 0; }; slzh = function(d2, b5) { return b5 + 30 + b2(d2, b5 + 26) + b2(d2, b5 + 28); }; zh = function(d2, b5, z2) { var fnl = b2(d2, b5 + 28), efl = b2(d2, b5 + 30), fn2 = strFromU8(d2.subarray(b5 + 46, b5 + 46 + fnl), !(b2(d2, b5 + 8) & 2048)), es2 = b5 + 46 + fnl; var _a25 = z64hs(d2, es2, efl, z2, b4(d2, b5 + 20), b4(d2, b5 + 24), b4(d2, b5 + 42)), sc2 = _a25[0], su = _a25[1], off = _a25[2]; return [b2(d2, b5 + 10), sc2, su, fn2, es2 + efl + b2(d2, b5 + 32), off]; }; z64hs = function(d2, b5, l13, z2, sc2, su, off) { var nsc = sc2 == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e5 = b5 + l13; var nf = nsc + nsu + noff; if (z2 && nf) { for (; b5 + 4 < e5; b5 += 4 + b2(d2, b5 + 2)) { if (b2(d2, b5) == 1) { return [ nsc ? b8(d2, b5 + 4 + 8 * nsu) : sc2, nsu ? b8(d2, b5 + 4) : su, noff ? b8(d2, b5 + 4 + 8 * (nsu + nsc)) : off, 1 ]; } } if (z2 < 2) err(13); } return [sc2, su, off, 0]; }; exfl = function(ex) { var le2 = 0; if (ex) { for (var k in ex) { var l13 = ex[k].length; if (l13 > 65535) err(9); le2 += l13 + 4; } } return le2; }; wzh = function(d2, b5, f2, fn2, u2, c2, ce2, co) { var fl2 = fn2.length, ex = f2.extra, col = co && co.length; var exl = exfl(ex); wbytes(d2, b5, ce2 != null ? 33639248 : 67324752), b5 += 4; if (ce2 != null) d2[b5++] = 20, d2[b5++] = f2.os; d2[b5] = 20, b5 += 2; d2[b5++] = f2.flag << 1 | (c2 < 0 && 8), d2[b5++] = u2 && 8; d2[b5++] = f2.compression & 255, d2[b5++] = f2.compression >> 8; var dt2 = new Date(f2.mtime == null ? Date.now() : f2.mtime), y2 = dt2.getFullYear() - 1980; if (y2 < 0 || y2 > 119) err(10); wbytes(d2, b5, y2 << 25 | dt2.getMonth() + 1 << 21 | dt2.getDate() << 16 | dt2.getHours() << 11 | dt2.getMinutes() << 5 | dt2.getSeconds() >> 1), b5 += 4; if (c2 != -1) { wbytes(d2, b5, f2.crc); wbytes(d2, b5 + 4, c2 < 0 ? -c2 - 2 : c2); wbytes(d2, b5 + 8, f2.size); } wbytes(d2, b5 + 12, fl2); wbytes(d2, b5 + 14, exl), b5 += 16; if (ce2 != null) { wbytes(d2, b5, col); wbytes(d2, b5 + 6, f2.attrs); wbytes(d2, b5 + 10, ce2), b5 += 14; } d2.set(fn2, b5); b5 += fl2; if (exl) { for (var k in ex) { var exf = ex[k], l13 = exf.length; wbytes(d2, b5, +k); wbytes(d2, b5 + 2, l13); d2.set(exf, b5 + 4), b5 += 4 + l13; } } if (col) d2.set(co, b5), b5 += col; return b5; }; wzf = function(o3, b5, c2, d2, e5) { wbytes(o3, b5, 101010256); wbytes(o3, b5 + 8, c2); wbytes(o3, b5 + 10, c2); wbytes(o3, b5 + 12, d2); wbytes(o3, b5 + 16, e5); }; ZipPassThrough = /* @__PURE__ */ (function() { function ZipPassThrough2(filename) { this.filename = filename; this.c = crc(); this.size = 0; this.compression = 0; } ZipPassThrough2.prototype.process = function(chunk, final) { this.ondata(null, chunk, final); }; ZipPassThrough2.prototype.push = function(chunk, final) { if (!this.ondata) err(5); this.c.p(chunk); this.size += chunk.length; if (final) this.crc = this.c.d(); this.process(chunk, final || false); }; return ZipPassThrough2; })(); ZipDeflate = /* @__PURE__ */ (function() { function ZipDeflate2(filename, opts) { var _this = this; if (!opts) opts = {}; ZipPassThrough.call(this, filename); this.d = new Deflate(opts, function(dat, final) { _this.ondata(null, dat, final); }); this.compression = 8; this.flag = dbf(opts.level); } ZipDeflate2.prototype.process = function(chunk, final) { try { this.d.push(chunk, final); } catch (e5) { this.ondata(e5, null, final); } }; ZipDeflate2.prototype.push = function(chunk, final) { ZipPassThrough.prototype.push.call(this, chunk, final); }; return ZipDeflate2; })(); AsyncZipDeflate = /* @__PURE__ */ (function() { function AsyncZipDeflate2(filename, opts) { var _this = this; if (!opts) opts = {}; ZipPassThrough.call(this, filename); this.d = new AsyncDeflate(opts, function(err2, dat, final) { _this.ondata(err2, dat, final); }); this.compression = 8; this.flag = dbf(opts.level); this.terminate = this.d.terminate; } AsyncZipDeflate2.prototype.process = function(chunk, final) { this.d.push(chunk, final); }; AsyncZipDeflate2.prototype.push = function(chunk, final) { ZipPassThrough.prototype.push.call(this, chunk, final); }; return AsyncZipDeflate2; })(); Zip = /* @__PURE__ */ (function() { function Zip2(cb) { this.ondata = cb; this.u = []; this.d = 1; } Zip2.prototype.add = function(file2) { var _this = this; if (!this.ondata) err(5); if (this.d & 2) this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false); else { var f2 = strToU8(file2.filename), fl_1 = f2.length; var com = file2.comment, o3 = com && strToU8(com); var u2 = fl_1 != file2.filename.length || o3 && com.length != o3.length; var hl_1 = fl_1 + exfl(file2.extra) + 30; if (fl_1 > 65535) this.ondata(err(11, 0, 1), null, false); var header = new u8(hl_1); wzh(header, 0, file2, f2, u2, -1); var chks_1 = [header]; var pAll_1 = function() { for (var _i2 = 0, chks_2 = chks_1; _i2 < chks_2.length; _i2++) { var chk = chks_2[_i2]; _this.ondata(null, chk, false); } chks_1 = []; }; var tr_1 = this.d; this.d = 0; var ind_1 = this.u.length; var uf_1 = mrg(file2, { f: f2, u: u2, o: o3, t: function() { if (file2.terminate) file2.terminate(); }, r: function() { pAll_1(); if (tr_1) { var nxt = _this.u[ind_1 + 1]; if (nxt) nxt.r(); else _this.d = 1; } tr_1 = 1; } }); var cl_1 = 0; file2.ondata = function(err2, dat, final) { if (err2) { _this.ondata(err2, dat, final); _this.terminate(); } else { cl_1 += dat.length; chks_1.push(dat); if (final) { var dd = new u8(16); wbytes(dd, 0, 134695760); wbytes(dd, 4, file2.crc); wbytes(dd, 8, cl_1); wbytes(dd, 12, file2.size); chks_1.push(dd); uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file2.crc, uf_1.size = file2.size; if (tr_1) uf_1.r(); tr_1 = 1; } else if (tr_1) pAll_1(); } }; this.u.push(uf_1); } }; Zip2.prototype.end = function() { var _this = this; if (this.d & 2) { this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true); return; } if (this.d) this.e(); else this.u.push({ r: function() { if (!(_this.d & 1)) return; _this.u.splice(-1, 1); _this.e(); }, t: function() { } }); this.d = 3; }; Zip2.prototype.e = function() { var bt2 = 0, l13 = 0, tl = 0; for (var _i2 = 0, _a25 = this.u; _i2 < _a25.length; _i2++) { var f2 = _a25[_i2]; tl += 46 + f2.f.length + exfl(f2.extra) + (f2.o ? f2.o.length : 0); } var out = new u8(tl + 22); for (var _b19 = 0, _c = this.u; _b19 < _c.length; _b19++) { var f2 = _c[_b19]; wzh(out, bt2, f2, f2.f, f2.u, -f2.c - 2, l13, f2.o); bt2 += 46 + f2.f.length + exfl(f2.extra) + (f2.o ? f2.o.length : 0), l13 += f2.b; } wzf(out, bt2, this.u.length, tl, l13); this.ondata(null, out, true); this.d = 2; }; Zip2.prototype.terminate = function() { for (var _i2 = 0, _a25 = this.u; _i2 < _a25.length; _i2++) { var f2 = _a25[_i2]; f2.t(); } this.d = 2; }; return Zip2; })(); UnzipPassThrough = /* @__PURE__ */ (function() { function UnzipPassThrough2() { } UnzipPassThrough2.prototype.push = function(chunk, final) { this.ondata(null, chunk, final); }; UnzipPassThrough2.compression = 0; return UnzipPassThrough2; })(); UnzipInflate = /* @__PURE__ */ (function() { function UnzipInflate2() { var _this = this; this.i = new Inflate(function(dat, final) { _this.ondata(null, dat, final); }); } UnzipInflate2.prototype.push = function(chunk, final) { try { this.i.push(chunk, final); } catch (e5) { this.ondata(e5, null, final); } }; UnzipInflate2.compression = 8; return UnzipInflate2; })(); AsyncUnzipInflate = /* @__PURE__ */ (function() { function AsyncUnzipInflate2(_2, sz) { var _this = this; if (sz < 32e4) { this.i = new Inflate(function(dat, final) { _this.ondata(null, dat, final); }); } else { this.i = new AsyncInflate(function(err2, dat, final) { _this.ondata(err2, dat, final); }); this.terminate = this.i.terminate; } } AsyncUnzipInflate2.prototype.push = function(chunk, final) { if (this.i.terminate) chunk = slc(chunk, 0); this.i.push(chunk, final); }; AsyncUnzipInflate2.compression = 8; return AsyncUnzipInflate2; })(); Unzip = /* @__PURE__ */ (function() { function Unzip2(cb) { this.onfile = cb; this.k = []; this.o = { 0: UnzipPassThrough }; this.p = et2; } Unzip2.prototype.push = function(chunk, final) { var _this = this; if (!this.onfile) err(5); if (!this.p) err(4); if (this.c > 0) { var len = Math.min(this.c, chunk.length); var toAdd = chunk.subarray(0, len); this.c -= len; if (this.d) this.d.push(toAdd, !this.c); else this.k[0].push(toAdd); chunk = chunk.subarray(len); if (chunk.length) return this.push(chunk, final); } else { var f2 = 0, i4 = 0, is2 = void 0, buf = void 0; if (!this.p.length) buf = chunk; else if (!chunk.length) buf = this.p; else { buf = new u8(this.p.length + chunk.length); buf.set(this.p), buf.set(chunk, this.p.length); } var l13 = buf.length, oc2 = this.c, add = oc2 && this.d; var _loop_2 = function() { var sig = b4(buf, i4); if (sig == 67324752) { f2 = 1, is2 = i4; this_1.d = null; this_1.c = 0; var bf = b2(buf, i4 + 6), cmp_1 = b2(buf, i4 + 8), u2 = bf & 2048, dd = bf & 8, fnl = b2(buf, i4 + 26), es2 = b2(buf, i4 + 28); if (l13 > i4 + 30 + fnl + es2) { var chks_3 = []; this_1.k.unshift(chks_3); f2 = 2; var lsc = b4(buf, i4 + 18), lsu = b4(buf, i4 + 22); var fn_1 = strFromU8(buf.subarray(i4 + 30, i4 += 30 + fnl), !u2); var _a25 = z64hs(buf, i4, es2, 2, lsc, lsu, 0), sc_1 = _a25[0], su_1 = _a25[1], z64 = _a25[3]; if (dd) sc_1 = -1 - z64; i4 += es2; this_1.c = sc_1; var d_1; var file_1 = { name: fn_1, compression: cmp_1, start: function() { if (!file_1.ondata) err(5); if (!sc_1) file_1.ondata(null, et2, true); else { var ctr = _this.o[cmp_1]; if (!ctr) file_1.ondata(err(14, "unknown compression type " + cmp_1, 1), null, false); d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1); d_1.ondata = function(err2, dat3, final2) { file_1.ondata(err2, dat3, final2); }; for (var _i2 = 0, chks_4 = chks_3; _i2 < chks_4.length; _i2++) { var dat2 = chks_4[_i2]; d_1.push(dat2, false); } if (_this.k[0] == chks_3 && _this.c) _this.d = d_1; else d_1.push(et2, true); } }, terminate: function() { if (d_1 && d_1.terminate) d_1.terminate(); } }; if (sc_1 >= 0) file_1.size = sc_1, file_1.originalSize = su_1; this_1.onfile(file_1); } return "break"; } else if (oc2) { if (sig == 134695760) { is2 = i4 += 12 + (oc2 == -2 && 8), f2 = 3, this_1.c = 0; return "break"; } else if (sig == 33639248) { is2 = i4 -= 4, f2 = 3, this_1.c = 0; return "break"; } } }; var this_1 = this; for (; i4 < l13 - 4; ++i4) { var state_1 = _loop_2(); if (state_1 === "break") break; } this.p = et2; if (oc2 < 0) { var dat = f2 ? buf.subarray(0, is2 - 12 - (oc2 == -2 && 8) - (b4(buf, is2 - 16) == 134695760 && 4)) : buf.subarray(0, i4); if (add) add.push(dat, !!f2); else this.k[+(f2 == 2)].push(dat); } if (f2 & 2) return this.push(buf.subarray(i4), final); this.p = buf.subarray(i4); } if (final) { if (this.c) err(13); this.p = null; } }; Unzip2.prototype.register = function(decoder) { this.o[decoder.compression] = decoder; }; return Unzip2; })(); mt2 = typeof queueMicrotask == "function" ? queueMicrotask : typeof setTimeout == "function" ? setTimeout : function(fn2) { fn2(); }; } }); // node_modules/ajv/dist/compile/codegen/code.js var require_code = __commonJS({ "node_modules/ajv/dist/compile/codegen/code.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; var _CodeOrName = class { }; exports._CodeOrName = _CodeOrName; exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; var Name = class extends _CodeOrName { constructor(s2) { super(); if (!exports.IDENTIFIER.test(s2)) throw new Error("CodeGen: name must be a valid identifier"); this.str = s2; } toString() { return this.str; } emptyStr() { return false; } get names() { return { [this.str]: 1 }; } }; exports.Name = Name; var _Code = class extends _CodeOrName { constructor(code) { super(); this._items = typeof code === "string" ? [code] : code; } toString() { return this.str; } emptyStr() { if (this._items.length > 1) return false; const item = this._items[0]; return item === "" || item === '""'; } get str() { var _a25; return (_a25 = this._str) !== null && _a25 !== void 0 ? _a25 : this._str = this._items.reduce((s2, c2) => `${s2}${c2}`, ""); } get names() { var _a25; return (_a25 = this._names) !== null && _a25 !== void 0 ? _a25 : this._names = this._items.reduce((names, c2) => { if (c2 instanceof Name) names[c2.str] = (names[c2.str] || 0) + 1; return names; }, {}); } }; exports._Code = _Code; exports.nil = new _Code(""); function _2(strs, ...args) { const code = [strs[0]]; let i4 = 0; while (i4 < args.length) { addCodeArg(code, args[i4]); code.push(strs[++i4]); } return new _Code(code); } exports._ = _2; var plus = new _Code("+"); function str(strs, ...args) { const expr = [safeStringify(strs[0])]; let i4 = 0; while (i4 < args.length) { expr.push(plus); addCodeArg(expr, args[i4]); expr.push(plus, safeStringify(strs[++i4])); } optimize(expr); return new _Code(expr); } exports.str = str; function addCodeArg(code, arg) { if (arg instanceof _Code) code.push(...arg._items); else if (arg instanceof Name) code.push(arg); else code.push(interpolate(arg)); } exports.addCodeArg = addCodeArg; function optimize(expr) { let i4 = 1; while (i4 < expr.length - 1) { if (expr[i4] === plus) { const res = mergeExprItems(expr[i4 - 1], expr[i4 + 1]); if (res !== void 0) { expr.splice(i4 - 1, 3, res); continue; } expr[i4++] = "+"; } i4++; } } function mergeExprItems(a3, b5) { if (b5 === '""') return a3; if (a3 === '""') return b5; if (typeof a3 == "string") { if (b5 instanceof Name || a3[a3.length - 1] !== '"') return; if (typeof b5 != "string") return `${a3.slice(0, -1)}${b5}"`; if (b5[0] === '"') return a3.slice(0, -1) + b5.slice(1); return; } if (typeof b5 == "string" && b5[0] === '"' && !(a3 instanceof Name)) return `"${a3}${b5.slice(1)}`; return; } function strConcat(c1, c2) { return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; } exports.strConcat = strConcat; function interpolate(x4) { return typeof x4 == "number" || typeof x4 == "boolean" || x4 === null ? x4 : safeStringify(Array.isArray(x4) ? x4.join(",") : x4); } function stringify(x4) { return new _Code(safeStringify(x4)); } exports.stringify = stringify; function safeStringify(x4) { return JSON.stringify(x4).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); } exports.safeStringify = safeStringify; function getProperty(key) { return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _2`[${key}]`; } exports.getProperty = getProperty; function getEsmExportName(key) { if (typeof key == "string" && exports.IDENTIFIER.test(key)) { return new _Code(`${key}`); } throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); } exports.getEsmExportName = getEsmExportName; function regexpCode(rx) { return new _Code(rx.toString()); } exports.regexpCode = regexpCode; } }); // node_modules/ajv/dist/compile/codegen/scope.js var require_scope = __commonJS({ "node_modules/ajv/dist/compile/codegen/scope.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; var code_1 = require_code(); var ValueError = class extends Error { constructor(name24) { super(`CodeGen: "code" for ${name24} not defined`); this.value = name24.value; } }; var UsedValueState; (function(UsedValueState2) { UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); exports.varKinds = { const: new code_1.Name("const"), let: new code_1.Name("let"), var: new code_1.Name("var") }; var Scope = class { constructor({ prefixes, parent } = {}) { this._names = {}; this._prefixes = prefixes; this._parent = parent; } toName(nameOrPrefix) { return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); } name(prefix) { return new code_1.Name(this._newName(prefix)); } _newName(prefix) { const ng = this._names[prefix] || this._nameGroup(prefix); return `${prefix}${ng.index++}`; } _nameGroup(prefix) { var _a25, _b19; if (((_b19 = (_a25 = this._parent) === null || _a25 === void 0 ? void 0 : _a25._prefixes) === null || _b19 === void 0 ? void 0 : _b19.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); } return this._names[prefix] = { prefix, index: 0 }; } }; exports.Scope = Scope; var ValueScopeName = class extends code_1.Name { constructor(prefix, nameStr) { super(nameStr); this.prefix = prefix; } setValue(value, { property, itemIndex }) { this.value = value; this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; } }; exports.ValueScopeName = ValueScopeName; var line2 = (0, code_1._)`\n`; var ValueScope = class extends Scope { constructor(opts) { super(opts); this._values = {}; this._scope = opts.scope; this.opts = { ...opts, _n: opts.lines ? line2 : code_1.nil }; } get() { return this._scope; } name(prefix) { return new ValueScopeName(prefix, this._newName(prefix)); } value(nameOrPrefix, value) { var _a25; if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); const name24 = this.toName(nameOrPrefix); const { prefix } = name24; const valueKey = (_a25 = value.key) !== null && _a25 !== void 0 ? _a25 : value.ref; let vs2 = this._values[prefix]; if (vs2) { const _name = vs2.get(valueKey); if (_name) return _name; } else { vs2 = this._values[prefix] = /* @__PURE__ */ new Map(); } vs2.set(valueKey, name24); const s2 = this._scope[prefix] || (this._scope[prefix] = []); const itemIndex = s2.length; s2[itemIndex] = value.ref; name24.setValue(value, { property: prefix, itemIndex }); return name24; } getValue(prefix, keyOrRef) { const vs2 = this._values[prefix]; if (!vs2) return; return vs2.get(keyOrRef); } scopeRefs(scopeName, values = this._values) { return this._reduceValues(values, (name24) => { if (name24.scopePath === void 0) throw new Error(`CodeGen: name "${name24}" has no value`); return (0, code_1._)`${scopeName}${name24.scopePath}`; }); } scopeCode(values = this._values, usedValues, getCode) { return this._reduceValues(values, (name24) => { if (name24.value === void 0) throw new Error(`CodeGen: name "${name24}" has no value`); return name24.value.code; }, usedValues, getCode); } _reduceValues(values, valueCode, usedValues = {}, getCode) { let code = code_1.nil; for (const prefix in values) { const vs2 = values[prefix]; if (!vs2) continue; const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); vs2.forEach((name24) => { if (nameSet.has(name24)) return; nameSet.set(name24, UsedValueState.Started); let c2 = valueCode(name24); if (c2) { const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; code = (0, code_1._)`${code}${def} ${name24} = ${c2};${this.opts._n}`; } else if (c2 = getCode === null || getCode === void 0 ? void 0 : getCode(name24)) { code = (0, code_1._)`${code}${c2}${this.opts._n}`; } else { throw new ValueError(name24); } nameSet.set(name24, UsedValueState.Completed); }); } return code; } }; exports.ValueScope = ValueScope; } }); // node_modules/ajv/dist/compile/codegen/index.js var require_codegen = __commonJS({ "node_modules/ajv/dist/compile/codegen/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; var code_1 = require_code(); var scope_1 = require_scope(); var code_2 = require_code(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return code_2._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return code_2.str; } }); Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { return code_2.strConcat; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return code_2.nil; } }); Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { return code_2.getProperty; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return code_2.stringify; } }); Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { return code_2.regexpCode; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return code_2.Name; } }); var scope_2 = require_scope(); Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { return scope_2.Scope; } }); Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { return scope_2.ValueScope; } }); Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { return scope_2.ValueScopeName; } }); Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { return scope_2.varKinds; } }); exports.operators = { GT: new code_1._Code(">"), GTE: new code_1._Code(">="), LT: new code_1._Code("<"), LTE: new code_1._Code("<="), EQ: new code_1._Code("==="), NEQ: new code_1._Code("!=="), NOT: new code_1._Code("!"), OR: new code_1._Code("||"), AND: new code_1._Code("&&"), ADD: new code_1._Code("+") }; var Node2 = class { optimizeNodes() { return this; } optimizeNames(_names, _constants) { return this; } }; var Def = class extends Node2 { constructor(varKind, name24, rhs) { super(); this.varKind = varKind; this.name = name24; this.rhs = rhs; } render({ es5, _n: _n3 }) { const varKind = es5 ? scope_1.varKinds.var : this.varKind; const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; return `${varKind} ${this.name}${rhs};` + _n3; } optimizeNames(names, constants) { if (!names[this.name.str]) return; if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; } }; var Assign = class extends Node2 { constructor(lhs, rhs, sideEffects) { super(); this.lhs = lhs; this.rhs = rhs; this.sideEffects = sideEffects; } render({ _n: _n3 }) { return `${this.lhs} = ${this.rhs};` + _n3; } optimizeNames(names, constants) { if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; return addExprNames(names, this.rhs); } }; var AssignOp = class extends Assign { constructor(lhs, op, rhs, sideEffects) { super(lhs, rhs, sideEffects); this.op = op; } render({ _n: _n3 }) { return `${this.lhs} ${this.op}= ${this.rhs};` + _n3; } }; var Label = class extends Node2 { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n: _n3 }) { return `${this.label}:` + _n3; } }; var Break = class extends Node2 { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n: _n3 }) { const label = this.label ? ` ${this.label}` : ""; return `break${label};` + _n3; } }; var Throw = class extends Node2 { constructor(error40) { super(); this.error = error40; } render({ _n: _n3 }) { return `throw ${this.error};` + _n3; } get names() { return this.error.names; } }; var AnyCode = class extends Node2 { constructor(code) { super(); this.code = code; } render({ _n: _n3 }) { return `${this.code};` + _n3; } optimizeNodes() { return `${this.code}` ? this : void 0; } optimizeNames(names, constants) { this.code = optimizeExpr(this.code, names, constants); return this; } get names() { return this.code instanceof code_1._CodeOrName ? this.code.names : {}; } }; var ParentNode = class extends Node2 { constructor(nodes = []) { super(); this.nodes = nodes; } render(opts) { return this.nodes.reduce((code, n5) => code + n5.render(opts), ""); } optimizeNodes() { const { nodes } = this; let i4 = nodes.length; while (i4--) { const n5 = nodes[i4].optimizeNodes(); if (Array.isArray(n5)) nodes.splice(i4, 1, ...n5); else if (n5) nodes[i4] = n5; else nodes.splice(i4, 1); } return nodes.length > 0 ? this : void 0; } optimizeNames(names, constants) { const { nodes } = this; let i4 = nodes.length; while (i4--) { const n5 = nodes[i4]; if (n5.optimizeNames(names, constants)) continue; subtractNames(names, n5.names); nodes.splice(i4, 1); } return nodes.length > 0 ? this : void 0; } get names() { return this.nodes.reduce((names, n5) => addNames(names, n5.names), {}); } }; var BlockNode = class extends ParentNode { render(opts) { return "{" + opts._n + super.render(opts) + "}" + opts._n; } }; var Root = class extends ParentNode { }; var Else = class extends BlockNode { }; Else.kind = "else"; var If = class _If extends BlockNode { constructor(condition, nodes) { super(nodes); this.condition = condition; } render(opts) { let code = `if(${this.condition})` + super.render(opts); if (this.else) code += "else " + this.else.render(opts); return code; } optimizeNodes() { super.optimizeNodes(); const cond = this.condition; if (cond === true) return this.nodes; let e5 = this.else; if (e5) { const ns2 = e5.optimizeNodes(); e5 = this.else = Array.isArray(ns2) ? new Else(ns2) : ns2; } if (e5) { if (cond === false) return e5 instanceof _If ? e5 : e5.nodes; if (this.nodes.length) return this; return new _If(not(cond), e5 instanceof _If ? [e5] : e5.nodes); } if (cond === false || !this.nodes.length) return void 0; return this; } optimizeNames(names, constants) { var _a25; this.else = (_a25 = this.else) === null || _a25 === void 0 ? void 0 : _a25.optimizeNames(names, constants); if (!(super.optimizeNames(names, constants) || this.else)) return; this.condition = optimizeExpr(this.condition, names, constants); return this; } get names() { const names = super.names; addExprNames(names, this.condition); if (this.else) addNames(names, this.else.names); return names; } }; If.kind = "if"; var For = class extends BlockNode { }; For.kind = "for"; var ForLoop = class extends For { constructor(iteration) { super(); this.iteration = iteration; } render(opts) { return `for(${this.iteration})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iteration = optimizeExpr(this.iteration, names, constants); return this; } get names() { return addNames(super.names, this.iteration.names); } }; var ForRange = class extends For { constructor(varKind, name24, from, to) { super(); this.varKind = varKind; this.name = name24; this.from = from; this.to = to; } render(opts) { const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; const { name: name24, from, to } = this; return `for(${varKind} ${name24}=${from}; ${name24}<${to}; ${name24}++)` + super.render(opts); } get names() { const names = addExprNames(super.names, this.from); return addExprNames(names, this.to); } }; var ForIter = class extends For { constructor(loop, varKind, name24, iterable) { super(); this.loop = loop; this.varKind = varKind; this.name = name24; this.iterable = iterable; } render(opts) { return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iterable = optimizeExpr(this.iterable, names, constants); return this; } get names() { return addNames(super.names, this.iterable.names); } }; var Func = class extends BlockNode { constructor(name24, args, async) { super(); this.name = name24; this.args = args; this.async = async; } render(opts) { const _async = this.async ? "async " : ""; return `${_async}function ${this.name}(${this.args})` + super.render(opts); } }; Func.kind = "func"; var Return = class extends ParentNode { render(opts) { return "return " + super.render(opts); } }; Return.kind = "return"; var Try = class extends BlockNode { render(opts) { let code = "try" + super.render(opts); if (this.catch) code += this.catch.render(opts); if (this.finally) code += this.finally.render(opts); return code; } optimizeNodes() { var _a25, _b19; super.optimizeNodes(); (_a25 = this.catch) === null || _a25 === void 0 ? void 0 : _a25.optimizeNodes(); (_b19 = this.finally) === null || _b19 === void 0 ? void 0 : _b19.optimizeNodes(); return this; } optimizeNames(names, constants) { var _a25, _b19; super.optimizeNames(names, constants); (_a25 = this.catch) === null || _a25 === void 0 ? void 0 : _a25.optimizeNames(names, constants); (_b19 = this.finally) === null || _b19 === void 0 ? void 0 : _b19.optimizeNames(names, constants); return this; } get names() { const names = super.names; if (this.catch) addNames(names, this.catch.names); if (this.finally) addNames(names, this.finally.names); return names; } }; var Catch = class extends BlockNode { constructor(error40) { super(); this.error = error40; } render(opts) { return `catch(${this.error})` + super.render(opts); } }; Catch.kind = "catch"; var Finally = class extends BlockNode { render(opts) { return "finally" + super.render(opts); } }; Finally.kind = "finally"; var CodeGen = class { constructor(extScope, opts = {}) { this._values = {}; this._blockStarts = []; this._constants = {}; this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; this._extScope = extScope; this._scope = new scope_1.Scope({ parent: extScope }); this._nodes = [new Root()]; } toString() { return this._root.render(this.opts); } // returns unique name in the internal scope name(prefix) { return this._scope.name(prefix); } // reserves unique name in the external scope scopeName(prefix) { return this._extScope.name(prefix); } // reserves unique name in the external scope and assigns value to it scopeValue(prefixOrName, value) { const name24 = this._extScope.value(prefixOrName, value); const vs2 = this._values[name24.prefix] || (this._values[name24.prefix] = /* @__PURE__ */ new Set()); vs2.add(name24); return name24; } getScopeValue(prefix, keyOrRef) { return this._extScope.getValue(prefix, keyOrRef); } // return code that assigns values in the external scope to the names that are used internally // (same names that were returned by gen.scopeName or gen.scopeValue) scopeRefs(scopeName) { return this._extScope.scopeRefs(scopeName, this._values); } scopeCode() { return this._extScope.scopeCode(this._values); } _def(varKind, nameOrPrefix, rhs, constant) { const name24 = this._scope.toName(nameOrPrefix); if (rhs !== void 0 && constant) this._constants[name24.str] = rhs; this._leafNode(new Def(varKind, name24, rhs)); return name24; } // `const` declaration (`var` in es5 mode) const(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); } // `let` declaration with optional assignment (`var` in es5 mode) let(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); } // `var` declaration with optional assignment var(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); } // assignment code assign(lhs, rhs, sideEffects) { return this._leafNode(new Assign(lhs, rhs, sideEffects)); } // `+=` code add(lhs, rhs) { return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); } // appends passed SafeExpr to code or executes Block code(c2) { if (typeof c2 == "function") c2(); else if (c2 !== code_1.nil) this._leafNode(new AnyCode(c2)); return this; } // returns code for object literal for the passed argument list of key-value pairs object(...keyValues) { const code = ["{"]; for (const [key, value] of keyValues) { if (code.length > 1) code.push(","); code.push(key); if (key !== value || this.opts.es5) { code.push(":"); (0, code_1.addCodeArg)(code, value); } } code.push("}"); return new code_1._Code(code); } // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) if(condition, thenBody, elseBody) { this._blockNode(new If(condition)); if (thenBody && elseBody) { this.code(thenBody).else().code(elseBody).endIf(); } else if (thenBody) { this.code(thenBody).endIf(); } else if (elseBody) { throw new Error('CodeGen: "else" body without "then" body'); } return this; } // `else if` clause - invalid without `if` or after `else` clauses elseIf(condition) { return this._elseNode(new If(condition)); } // `else` clause - only valid after `if` or `else if` clauses else() { return this._elseNode(new Else()); } // end `if` statement (needed if gen.if was used only with condition) endIf() { return this._endBlockNode(If, Else); } _for(node, forBody) { this._blockNode(node); if (forBody) this.code(forBody).endFor(); return this; } // a generic `for` clause (or statement if `forBody` is passed) for(iteration, forBody) { return this._for(new ForLoop(iteration), forBody); } // `for` statement for a range of values forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { const name24 = this._scope.toName(nameOrPrefix); return this._for(new ForRange(varKind, name24, from, to), () => forBody(name24)); } // `for-of` statement (in es5 mode replace with a normal for loop) forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { const name24 = this._scope.toName(nameOrPrefix); if (this.opts.es5) { const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i4) => { this.var(name24, (0, code_1._)`${arr}[${i4}]`); forBody(name24); }); } return this._for(new ForIter("of", varKind, name24, iterable), () => forBody(name24)); } // `for-in` statement. // With option `ownProperties` replaced with a `for-of` loop for object keys forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { if (this.opts.ownProperties) { return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); } const name24 = this._scope.toName(nameOrPrefix); return this._for(new ForIter("in", varKind, name24, obj), () => forBody(name24)); } // end `for` loop endFor() { return this._endBlockNode(For); } // `label` statement label(label) { return this._leafNode(new Label(label)); } // `break` statement break(label) { return this._leafNode(new Break(label)); } // `return` statement return(value) { const node = new Return(); this._blockNode(node); this.code(value); if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } // `try` statement try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); const node = new Try(); this._blockNode(node); this.code(tryBody); if (catchCode) { const error40 = this.name("e"); this._currNode = node.catch = new Catch(error40); catchCode(error40); } if (finallyCode) { this._currNode = node.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement throw(error40) { return this._leafNode(new Throw(error40)); } // start self-balancing block block(body, nodeCount) { this._blockStarts.push(this._nodes.length); if (body) this.code(body).endBlock(nodeCount); return this; } // end the current self-balancing block endBlock(nodeCount) { const len = this._blockStarts.pop(); if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); const toClose = this._nodes.length - len; if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); } this._nodes.length = len; return this; } // `function` heading (or definition if funcBody is passed) func(name24, args = code_1.nil, async, funcBody) { this._blockNode(new Func(name24, args, async)); if (funcBody) this.code(funcBody).endFunc(); return this; } // end function definition endFunc() { return this._endBlockNode(Func); } optimize(n5 = 1) { while (n5-- > 0) { this._root.optimizeNodes(); this._root.optimizeNames(this._root.names, this._constants); } } _leafNode(node) { this._currNode.nodes.push(node); return this; } _blockNode(node) { this._currNode.nodes.push(node); this._nodes.push(node); } _endBlockNode(N1, N22) { const n5 = this._currNode; if (n5 instanceof N1 || N22 && n5 instanceof N22) { this._nodes.pop(); return this; } throw new Error(`CodeGen: not in block "${N22 ? `${N1.kind}/${N22.kind}` : N1.kind}"`); } _elseNode(node) { const n5 = this._currNode; if (!(n5 instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } this._currNode = n5.else = node; return this; } get _root() { return this._nodes[0]; } get _currNode() { const ns2 = this._nodes; return ns2[ns2.length - 1]; } set _currNode(node) { const ns2 = this._nodes; ns2[ns2.length - 1] = node; } }; exports.CodeGen = CodeGen; function addNames(names, from) { for (const n5 in from) names[n5] = (names[n5] || 0) + (from[n5] || 0); return names; } function addExprNames(names, from) { return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; } function optimizeExpr(expr, names, constants) { if (expr instanceof code_1.Name) return replaceName(expr); if (!canOptimize(expr)) return expr; return new code_1._Code(expr._items.reduce((items, c2) => { if (c2 instanceof code_1.Name) c2 = replaceName(c2); if (c2 instanceof code_1._Code) items.push(...c2._items); else items.push(c2); return items; }, [])); function replaceName(n5) { const c2 = constants[n5.str]; if (c2 === void 0 || names[n5.str] !== 1) return n5; delete names[n5.str]; return c2; } function canOptimize(e5) { return e5 instanceof code_1._Code && e5._items.some((c2) => c2 instanceof code_1.Name && names[c2.str] === 1 && constants[c2.str] !== void 0); } } function subtractNames(names, from) { for (const n5 in from) names[n5] = (names[n5] || 0) - (from[n5] || 0); } function not(x4) { return typeof x4 == "boolean" || typeof x4 == "number" || x4 === null ? !x4 : (0, code_1._)`!${par(x4)}`; } exports.not = not; var andCode = mappend(exports.operators.AND); function and(...args) { return args.reduce(andCode); } exports.and = and; var orCode = mappend(exports.operators.OR); function or2(...args) { return args.reduce(orCode); } exports.or = or2; function mappend(op) { return (x4, y2) => x4 === code_1.nil ? y2 : y2 === code_1.nil ? x4 : (0, code_1._)`${par(x4)} ${op} ${par(y2)}`; } function par(x4) { return x4 instanceof code_1.Name ? x4 : (0, code_1._)`(${x4})`; } } }); // node_modules/ajv/dist/compile/util.js var require_util = __commonJS({ "node_modules/ajv/dist/compile/util.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; var codegen_1 = require_codegen(); var code_1 = require_code(); function toHash(arr) { const hash = {}; for (const item of arr) hash[item] = true; return hash; } exports.toHash = toHash; function alwaysValidSchema(it2, schema) { if (typeof schema == "boolean") return schema; if (Object.keys(schema).length === 0) return true; checkUnknownRules(it2, schema); return !schemaHasRules(schema, it2.self.RULES.all); } exports.alwaysValidSchema = alwaysValidSchema; function checkUnknownRules(it2, schema = it2.schema) { const { opts, self } = it2; if (!opts.strictSchema) return; if (typeof schema === "boolean") return; const rules = self.RULES.keywords; for (const key in schema) { if (!rules[key]) checkStrictMode(it2, `unknown keyword: "${key}"`); } } exports.checkUnknownRules = checkUnknownRules; function schemaHasRules(schema, rules) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (rules[key]) return true; return false; } exports.schemaHasRules = schemaHasRules; function schemaHasRulesButRef(schema, RULES) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; return false; } exports.schemaHasRulesButRef = schemaHasRulesButRef; function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { if (!$data) { if (typeof schema == "number" || typeof schema == "boolean") return schema; if (typeof schema == "string") return (0, codegen_1._)`${schema}`; } return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; } exports.schemaRefOrVal = schemaRefOrVal; function unescapeFragment(str) { return unescapeJsonPointer(decodeURIComponent(str)); } exports.unescapeFragment = unescapeFragment; function escapeFragment(str) { return encodeURIComponent(escapeJsonPointer(str)); } exports.escapeFragment = escapeFragment; function escapeJsonPointer(str) { if (typeof str == "number") return `${str}`; return str.replace(/~/g, "~0").replace(/\//g, "~1"); } exports.escapeJsonPointer = escapeJsonPointer; function unescapeJsonPointer(str) { return str.replace(/~1/g, "/").replace(/~0/g, "~"); } exports.unescapeJsonPointer = unescapeJsonPointer; function eachItem(xs2, f2) { if (Array.isArray(xs2)) { for (const x4 of xs2) f2(x4); } else { f2(xs2); } } exports.eachItem = eachItem; function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { return (gen, from, to, toName) => { const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to); return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; }; } exports.mergeEvaluated = { props: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); }), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { if (from === true) { gen.assign(to, true); } else { gen.assign(to, (0, codegen_1._)`${to} || {}`); setEvaluated(gen, to, from); } }), mergeValues: (from, to) => from === true ? true : { ...from, ...to }, resultToName: evaluatedPropsToName }), items: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), mergeValues: (from, to) => from === true ? true : Math.max(from, to), resultToName: (gen, items) => gen.var("items", items) }) }; function evaluatedPropsToName(gen, ps2) { if (ps2 === true) return gen.var("props", true); const props = gen.var("props", (0, codegen_1._)`{}`); if (ps2 !== void 0) setEvaluated(gen, props, ps2); return props; } exports.evaluatedPropsToName = evaluatedPropsToName; function setEvaluated(gen, props, ps2) { Object.keys(ps2).forEach((p2) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p2)}`, true)); } exports.setEvaluated = setEvaluated; var snippets = {}; function useFunc(gen, f2) { return gen.scopeValue("func", { ref: f2, code: snippets[f2.code] || (snippets[f2.code] = new code_1._Code(f2.code)) }); } exports.useFunc = useFunc; var Type; (function(Type2) { Type2[Type2["Num"] = 0] = "Num"; Type2[Type2["Str"] = 1] = "Str"; })(Type || (exports.Type = Type = {})); function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { if (dataProp instanceof codegen_1.Name) { const isNumber2 = dataPropType === Type.Num; return jsPropertySyntax ? isNumber2 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber2 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; } return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); } exports.getErrorPath = getErrorPath; function checkStrictMode(it2, msg, mode = it2.opts.strictSchema) { if (!mode) return; msg = `strict mode: ${msg}`; if (mode === true) throw new Error(msg); it2.self.logger.warn(msg); } exports.checkStrictMode = checkStrictMode; } }); // node_modules/ajv/dist/compile/names.js var require_names = __commonJS({ "node_modules/ajv/dist/compile/names.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var names = { // validation function arguments data: new codegen_1.Name("data"), // data passed to validation function // args passed from referencing schema valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below instancePath: new codegen_1.Name("instancePath"), parentData: new codegen_1.Name("parentData"), parentDataProperty: new codegen_1.Name("parentDataProperty"), rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef // function scoped variables vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors errors: new codegen_1.Name("errors"), // counter of validation errors this: new codegen_1.Name("this"), // "globals" self: new codegen_1.Name("self"), scope: new codegen_1.Name("scope"), // JTD serialize/parse name for JSON string and position json: new codegen_1.Name("json"), jsonPos: new codegen_1.Name("jsonPos"), jsonLen: new codegen_1.Name("jsonLen"), jsonPart: new codegen_1.Name("jsonPart") }; exports.default = names; } }); // node_modules/ajv/dist/compile/errors.js var require_errors = __commonJS({ "node_modules/ajv/dist/compile/errors.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var names_1 = require_names(); exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; function reportError(cxt, error40 = exports.keywordError, errorPaths, overrideAllErrors) { const { it: it2 } = cxt; const { gen, compositeRule, allErrors } = it2; const errObj = errorObjectCode(cxt, error40, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { returnErrors(it2, (0, codegen_1._)`[${errObj}]`); } } exports.reportError = reportError; function reportExtraError(cxt, error40 = exports.keywordError, errorPaths) { const { it: it2 } = cxt; const { gen, compositeRule, allErrors } = it2; const errObj = errorObjectCode(cxt, error40, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it2, names_1.default.vErrors); } } exports.reportExtraError = reportExtraError; function resetErrorsCount(gen, errsCount) { gen.assign(names_1.default.errors, errsCount); gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); } exports.resetErrorsCount = resetErrorsCount; function extendErrors({ gen, keyword, schemaValue, data, errsCount, it: it2 }) { if (errsCount === void 0) throw new Error("ajv implementation error"); const err2 = gen.name("err"); gen.forRange("i", errsCount, names_1.default.errors, (i4) => { gen.const(err2, (0, codegen_1._)`${names_1.default.vErrors}[${i4}]`); gen.if((0, codegen_1._)`${err2}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err2}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it2.errorPath))); gen.assign((0, codegen_1._)`${err2}.schemaPath`, (0, codegen_1.str)`${it2.errSchemaPath}/${keyword}`); if (it2.opts.verbose) { gen.assign((0, codegen_1._)`${err2}.schema`, schemaValue); gen.assign((0, codegen_1._)`${err2}.data`, data); } }); } exports.extendErrors = extendErrors; function addError(gen, errObj) { const err2 = gen.const("err", errObj); gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err2}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err2})`); gen.code((0, codegen_1._)`${names_1.default.errors}++`); } function returnErrors(it2, errs) { const { gen, validateName, schemaEnv } = it2; if (schemaEnv.$async) { gen.throw((0, codegen_1._)`new ${it2.ValidationError}(${errs})`); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, errs); gen.return(false); } } var E3 = { keyword: new codegen_1.Name("keyword"), schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors params: new codegen_1.Name("params"), propertyName: new codegen_1.Name("propertyName"), message: new codegen_1.Name("message"), schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; function errorObjectCode(cxt, error40, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; return errorObject(cxt, error40, errorPaths); } function errorObject(cxt, error40, errorPaths = {}) { const { gen, it: it2 } = cxt; const keyValues = [ errorInstancePath(it2, errorPaths), errorSchemaPath(cxt, errorPaths) ]; extraErrorProps(cxt, error40, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; } function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; if (schemaPath) { schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; } return [E3.schemaPath, schPath]; } function extraErrorProps(cxt, { params, message }, keyValues) { const { keyword, data, schemaValue, it: it2 } = cxt; const { opts, propertyName, topSchemaRef, schemaPath } = it2; keyValues.push([E3.keyword, keyword], [E3.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); if (opts.messages) { keyValues.push([E3.message, typeof message == "function" ? message(cxt) : message]); } if (opts.verbose) { keyValues.push([E3.schema, schemaValue], [E3.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); } if (propertyName) keyValues.push([E3.propertyName, propertyName]); } } }); // node_modules/ajv/dist/compile/validate/boolSchema.js var require_boolSchema = __commonJS({ "node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; var errors_1 = require_errors(); var codegen_1 = require_codegen(); var names_1 = require_names(); var boolError = { message: "boolean schema is false" }; function topBoolOrEmptySchema(it2) { const { gen, schema, validateName } = it2; if (schema === false) { falseSchemaError(it2, false); } else if (typeof schema == "object" && schema.$async === true) { gen.return(names_1.default.data); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, null); gen.return(true); } } exports.topBoolOrEmptySchema = topBoolOrEmptySchema; function boolOrEmptySchema(it2, valid) { const { gen, schema } = it2; if (schema === false) { gen.var(valid, false); falseSchemaError(it2); } else { gen.var(valid, true); } } exports.boolOrEmptySchema = boolOrEmptySchema; function falseSchemaError(it2, overrideAllErrors) { const { gen, data } = it2; const cxt = { gen, keyword: "false schema", data, schema: false, schemaCode: false, schemaValue: false, params: {}, it: it2 }; (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); } } }); // node_modules/ajv/dist/compile/rules.js var require_rules = __commonJS({ "node_modules/ajv/dist/compile/rules.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getRules = exports.isJSONType = void 0; var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; var jsonTypes = new Set(_jsonTypes); function isJSONType(x4) { return typeof x4 == "string" && jsonTypes.has(x4); } exports.isJSONType = isJSONType; function getRules() { const groups = { number: { type: "number", rules: [] }, string: { type: "string", rules: [] }, array: { type: "array", rules: [] }, object: { type: "object", rules: [] } }; return { types: { ...groups, integer: true, boolean: true, null: true }, rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], post: { rules: [] }, all: {}, keywords: {} }; } exports.getRules = getRules; } }); // node_modules/ajv/dist/compile/validate/applicability.js var require_applicability = __commonJS({ "node_modules/ajv/dist/compile/validate/applicability.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; function schemaHasRulesForType({ schema, self }, type) { const group = self.RULES.types[type]; return group && group !== true && shouldUseGroup(schema, group); } exports.schemaHasRulesForType = schemaHasRulesForType; function shouldUseGroup(schema, group) { return group.rules.some((rule) => shouldUseRule(schema, rule)); } exports.shouldUseGroup = shouldUseGroup; function shouldUseRule(schema, rule) { var _a25; return schema[rule.keyword] !== void 0 || ((_a25 = rule.definition.implements) === null || _a25 === void 0 ? void 0 : _a25.some((kwd) => schema[kwd] !== void 0)); } exports.shouldUseRule = shouldUseRule; } }); // node_modules/ajv/dist/compile/validate/dataType.js var require_dataType = __commonJS({ "node_modules/ajv/dist/compile/validate/dataType.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; var rules_1 = require_rules(); var applicability_1 = require_applicability(); var errors_1 = require_errors(); var codegen_1 = require_codegen(); var util_1 = require_util(); var DataType; (function(DataType2) { DataType2[DataType2["Correct"] = 0] = "Correct"; DataType2[DataType2["Wrong"] = 1] = "Wrong"; })(DataType || (exports.DataType = DataType = {})); function getSchemaTypes(schema) { const types = getJSONTypes(schema.type); const hasNull = types.includes("null"); if (hasNull) { if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); } else { if (!types.length && schema.nullable !== void 0) { throw new Error('"nullable" cannot be used without "type"'); } if (schema.nullable === true) types.push("null"); } return types; } exports.getSchemaTypes = getSchemaTypes; function getJSONTypes(ts2) { const types = Array.isArray(ts2) ? ts2 : ts2 ? [ts2] : []; if (types.every(rules_1.isJSONType)) return types; throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); } exports.getJSONTypes = getJSONTypes; function coerceAndCheckDataType(it2, types) { const { gen, data, opts } = it2; const coerceTo = coerceToTypes(types, opts.coerceTypes); const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it2, types[0])); if (checkTypes) { const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); gen.if(wrongType, () => { if (coerceTo.length) coerceData(it2, types, coerceTo); else reportTypeError(it2); }); } return checkTypes; } exports.coerceAndCheckDataType = coerceAndCheckDataType; var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); function coerceToTypes(types, coerceTypes) { return coerceTypes ? types.filter((t4) => COERCIBLE.has(t4) || coerceTypes === "array" && t4 === "array") : []; } function coerceData(it2, types, coerceTo) { const { gen, data, opts } = it2; const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); if (opts.coerceTypes === "array") { gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); } gen.if((0, codegen_1._)`${coerced} !== undefined`); for (const t4 of coerceTo) { if (COERCIBLE.has(t4) || t4 === "array" && opts.coerceTypes === "array") { coerceSpecificType(t4); } } gen.else(); reportTypeError(it2); gen.endIf(); gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { gen.assign(data, coerced); assignParentData(it2, coerced); }); function coerceSpecificType(t4) { switch (t4) { case "string": gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); return; case "number": gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "integer": gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "boolean": gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); return; case "null": gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); gen.assign(coerced, null); return; case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); } } } function assignParentData({ gen, parentData, parentDataProperty }, expr) { gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); } function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { const EQ2 = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; let cond; switch (dataType) { case "null": return (0, codegen_1._)`${data} ${EQ2} null`; case "array": cond = (0, codegen_1._)`Array.isArray(${data})`; break; case "object": cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; break; case "integer": cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); break; case "number": cond = numCond(); break; default: return (0, codegen_1._)`typeof ${data} ${EQ2} ${dataType}`; } return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); function numCond(_cond = codegen_1.nil) { return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); } } exports.checkDataType = checkDataType; function checkDataTypes(dataTypes, data, strictNums, correct) { if (dataTypes.length === 1) { return checkDataType(dataTypes[0], data, strictNums, correct); } let cond; const types = (0, util_1.toHash)(dataTypes); if (types.array && types.object) { const notObj = (0, codegen_1._)`typeof ${data} != "object"`; cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; delete types.null; delete types.array; delete types.object; } else { cond = codegen_1.nil; } if (types.number) delete types.integer; for (const t4 in types) cond = (0, codegen_1.and)(cond, checkDataType(t4, data, strictNums, correct)); return cond; } exports.checkDataTypes = checkDataTypes; var typeError = { message: ({ schema }) => `must be ${schema}`, params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` }; function reportTypeError(it2) { const cxt = getTypeErrorContext(it2); (0, errors_1.reportError)(cxt, typeError); } exports.reportTypeError = reportTypeError; function getTypeErrorContext(it2) { const { gen, data, schema } = it2; const schemaCode = (0, util_1.schemaRefOrVal)(it2, schema, "type"); return { gen, keyword: "type", data, schema: schema.type, schemaCode, schemaValue: schemaCode, parentSchema: schema, params: {}, it: it2 }; } } }); // node_modules/ajv/dist/compile/validate/defaults.js var require_defaults = __commonJS({ "node_modules/ajv/dist/compile/validate/defaults.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.assignDefaults = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); function assignDefaults(it2, ty) { const { properties, items } = it2.schema; if (ty === "object" && properties) { for (const key in properties) { assignDefault(it2, key, properties[key].default); } } else if (ty === "array" && Array.isArray(items)) { items.forEach((sch, i4) => assignDefault(it2, i4, sch.default)); } } exports.assignDefaults = assignDefaults; function assignDefault(it2, prop, defaultValue) { const { gen, compositeRule, data, opts } = it2; if (defaultValue === void 0) return; const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; if (compositeRule) { (0, util_1.checkStrictMode)(it2, `default is ignored for: ${childData}`); return; } let condition = (0, codegen_1._)`${childData} === undefined`; if (opts.useDefaults === "empty") { condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; } gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); } } }); // node_modules/ajv/dist/vocabularies/code.js var require_code2 = __commonJS({ "node_modules/ajv/dist/vocabularies/code.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var names_1 = require_names(); var util_2 = require_util(); function checkReportMissingProp(cxt, prop) { const { gen, data, it: it2 } = cxt; gen.if(noPropertyInData(gen, data, prop, it2.opts.ownProperties), () => { cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); cxt.error(); }); } exports.checkReportMissingProp = checkReportMissingProp; function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); } exports.checkMissingProp = checkMissingProp; function reportMissingProp(cxt, missing) { cxt.setParams({ missingProperty: missing }, true); cxt.error(); } exports.reportMissingProp = reportMissingProp; function hasPropFunc(gen) { return gen.scopeValue("func", { // eslint-disable-next-line @typescript-eslint/unbound-method ref: Object.prototype.hasOwnProperty, code: (0, codegen_1._)`Object.prototype.hasOwnProperty` }); } exports.hasPropFunc = hasPropFunc; function isOwnProperty(gen, data, property) { return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; } exports.isOwnProperty = isOwnProperty; function propertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; } exports.propertyInData = propertyInData; function noPropertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; } exports.noPropertyInData = noPropertyInData; function allSchemaProperties(schemaMap) { return schemaMap ? Object.keys(schemaMap).filter((p2) => p2 !== "__proto__") : []; } exports.allSchemaProperties = allSchemaProperties; function schemaProperties(it2, schemaMap) { return allSchemaProperties(schemaMap).filter((p2) => !(0, util_1.alwaysValidSchema)(it2, schemaMap[p2])); } exports.schemaProperties = schemaProperties; function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it: it2 }, func, context, passSchema) { const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; const valCxt = [ [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], [names_1.default.parentData, it2.parentData], [names_1.default.parentDataProperty, it2.parentDataProperty], [names_1.default.rootData, names_1.default.rootData] ]; if (it2.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; } exports.callValidateCode = callValidateCode; var newRegExp = (0, codegen_1._)`new RegExp`; function usePattern({ gen, it: { opts } }, pattern) { const u2 = opts.unicodeRegExp ? "u" : ""; const { regExp } = opts.code; const rx = regExp(pattern, u2); return gen.scopeValue("pattern", { key: rx.toString(), ref: rx, code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u2})` }); } exports.usePattern = usePattern; function validateArray(cxt) { const { gen, data, keyword, it: it2 } = cxt; const valid = gen.name("valid"); if (it2.allErrors) { const validArr = gen.let("valid", true); validateItems(() => gen.assign(validArr, false)); return validArr; } gen.var(valid, true); validateItems(() => gen.break()); return valid; function validateItems(notValid) { const len = gen.const("len", (0, codegen_1._)`${data}.length`); gen.forRange("i", 0, len, (i4) => { cxt.subschema({ keyword, dataProp: i4, dataPropType: util_1.Type.Num }, valid); gen.if((0, codegen_1.not)(valid), notValid); }); } } exports.validateArray = validateArray; function validateUnion(cxt) { const { gen, schema, keyword, it: it2 } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it2, sch)); if (alwaysValid && !it2.opts.unevaluated) return; const valid = gen.let("valid", false); const schValid = gen.name("_valid"); gen.block(() => schema.forEach((_sch, i4) => { const schCxt = cxt.subschema({ keyword, schemaProp: i4, compositeRule: true }, schValid); gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); const merged = cxt.mergeValidEvaluated(schCxt, schValid); if (!merged) gen.if((0, codegen_1.not)(valid)); })); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); } exports.validateUnion = validateUnion; } }); // node_modules/ajv/dist/compile/validate/keyword.js var require_keyword = __commonJS({ "node_modules/ajv/dist/compile/validate/keyword.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; var codegen_1 = require_codegen(); var names_1 = require_names(); var code_1 = require_code2(); var errors_1 = require_errors(); function macroKeywordCode(cxt, def) { const { gen, keyword, schema, parentSchema, it: it2 } = cxt; const macroSchema = def.macro.call(it2.self, schema, parentSchema, it2); const schemaRef = useKeyword(gen, keyword, macroSchema); if (it2.opts.validateSchema !== false) it2.self.validateSchema(macroSchema, true); const valid = gen.name("valid"); cxt.subschema({ schema: macroSchema, schemaPath: codegen_1.nil, errSchemaPath: `${it2.errSchemaPath}/${keyword}`, topSchemaRef: schemaRef, compositeRule: true }, valid); cxt.pass(valid, () => cxt.error(true)); } exports.macroKeywordCode = macroKeywordCode; function funcKeywordCode(cxt, def) { var _a25; const { gen, keyword, schema, parentSchema, $data, it: it2 } = cxt; checkAsyncKeyword(it2, def); const validate = !$data && def.compile ? def.compile.call(it2.self, schema, parentSchema, it2) : def.validate; const validateRef = useKeyword(gen, keyword, validate); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a25 = def.valid) !== null && _a25 !== void 0 ? _a25 : valid); function validateKeyword() { if (def.errors === false) { assignValid(); if (def.modifying) modifyData(cxt); reportErrs(() => cxt.error()); } else { const ruleErrs = def.async ? validateAsync() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } function validateAsync() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e5) => gen.assign(valid, false).if((0, codegen_1._)`${e5} instanceof ${it2.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e5}.errors`), () => gen.throw(e5))); return ruleErrs; } function validateSync() { const validateErrs = (0, codegen_1._)`${validateRef}.errors`; gen.assign(validateErrs, null); assignValid(codegen_1.nil); return validateErrs; } function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { const passCxt = it2.opts.passContext ? names_1.default.this : names_1.default.self; const passSchema = !("compile" in def && !$data || def.schema === false); gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); } function reportErrs(errors) { var _a26; gen.if((0, codegen_1.not)((_a26 = def.valid) !== null && _a26 !== void 0 ? _a26 : valid), errors); } } exports.funcKeywordCode = funcKeywordCode; function modifyData(cxt) { const { gen, data, it: it2 } = cxt; gen.if(it2.parentData, () => gen.assign(data, (0, codegen_1._)`${it2.parentData}[${it2.parentDataProperty}]`)); } function addErrs(cxt, errs) { const { gen } = cxt; gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); (0, errors_1.extendErrors)(cxt); }, () => cxt.error()); } function checkAsyncKeyword({ schemaEnv }, def) { if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); } function useKeyword(gen, keyword, result) { if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); } function validSchemaType(schema, schemaType, allowUndefined = false) { return !schemaType.length || schemaType.some((st2) => st2 === "array" ? Array.isArray(schema) : st2 === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st2 || allowUndefined && typeof schema == "undefined"); } exports.validSchemaType = validSchemaType; function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { throw new Error("ajv implementation error"); } const deps = def.dependencies; if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); } if (def.validateSchema) { const valid = def.validateSchema(schema[keyword]); if (!valid) { const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); if (opts.validateSchema === "log") self.logger.error(msg); else throw new Error(msg); } } } exports.validateKeywordUsage = validateKeywordUsage; } }); // node_modules/ajv/dist/compile/validate/subschema.js var require_subschema = __commonJS({ "node_modules/ajv/dist/compile/validate/subschema.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); function getSubschema(it2, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { if (keyword !== void 0 && schema !== void 0) { throw new Error('both "keyword" and "schema" passed, only one allowed'); } if (keyword !== void 0) { const sch = it2.schema[keyword]; return schemaProp === void 0 ? { schema: sch, schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, errSchemaPath: `${it2.errSchemaPath}/${keyword}` } : { schema: sch[schemaProp], schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, errSchemaPath: `${it2.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` }; } if (schema !== void 0) { if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); } return { schema, schemaPath, topSchemaRef, errSchemaPath }; } throw new Error('either "keyword" or "schema" must be passed'); } exports.getSubschema = getSubschema; function extendSubschemaData(subschema, it2, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { if (data !== void 0 && dataProp !== void 0) { throw new Error('both "data" and "dataProp" passed, only one allowed'); } const { gen } = it2; if (dataProp !== void 0) { const { errorPath, dataPathArr, opts } = it2; const nextData = gen.let("data", (0, codegen_1._)`${it2.data}${(0, codegen_1.getProperty)(dataProp)}`, true); dataContextProps(nextData); subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; } if (data !== void 0) { const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); dataContextProps(nextData); if (propertyName !== void 0) subschema.propertyName = propertyName; } if (dataTypes) subschema.dataTypes = dataTypes; function dataContextProps(_nextData) { subschema.data = _nextData; subschema.dataLevel = it2.dataLevel + 1; subschema.dataTypes = []; it2.definedProperties = /* @__PURE__ */ new Set(); subschema.parentData = it2.data; subschema.dataNames = [...it2.dataNames, _nextData]; } } exports.extendSubschemaData = extendSubschemaData; function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { if (compositeRule !== void 0) subschema.compositeRule = compositeRule; if (createErrors !== void 0) subschema.createErrors = createErrors; if (allErrors !== void 0) subschema.allErrors = allErrors; subschema.jtdDiscriminator = jtdDiscriminator; subschema.jtdMetadata = jtdMetadata; } exports.extendSubschemaMode = extendSubschemaMode; } }); // node_modules/fast-deep-equal/index.js var require_fast_deep_equal = __commonJS({ "node_modules/fast-deep-equal/index.js"(exports, module) { "use strict"; module.exports = function equal2(a3, b5) { if (a3 === b5) return true; if (a3 && b5 && typeof a3 == "object" && typeof b5 == "object") { if (a3.constructor !== b5.constructor) return false; var length, i4, keys; if (Array.isArray(a3)) { length = a3.length; if (length != b5.length) return false; for (i4 = length; i4-- !== 0; ) if (!equal2(a3[i4], b5[i4])) return false; return true; } if (a3.constructor === RegExp) return a3.source === b5.source && a3.flags === b5.flags; if (a3.valueOf !== Object.prototype.valueOf) return a3.valueOf() === b5.valueOf(); if (a3.toString !== Object.prototype.toString) return a3.toString() === b5.toString(); keys = Object.keys(a3); length = keys.length; if (length !== Object.keys(b5).length) return false; for (i4 = length; i4-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(b5, keys[i4])) return false; for (i4 = length; i4-- !== 0; ) { var key = keys[i4]; if (!equal2(a3[key], b5[key])) return false; } return true; } return a3 !== a3 && b5 !== b5; }; } }); // node_modules/json-schema-traverse/index.js var require_json_schema_traverse = __commonJS({ "node_modules/json-schema-traverse/index.js"(exports, module) { "use strict"; var traverse = module.exports = function(schema, opts, cb) { if (typeof opts == "function") { cb = opts; opts = {}; } cb = opts.cb || cb; var pre = typeof cb == "function" ? cb : cb.pre || function() { }; var post = cb.post || function() { }; _traverse(opts, pre, post, schema, "", schema); }; traverse.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true, if: true, then: true, else: true }; traverse.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true }; traverse.propsKeywords = { $defs: true, definitions: true, properties: true, patternProperties: true, dependencies: true }; traverse.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { if (schema && typeof schema == "object" && !Array.isArray(schema)) { pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); for (var key in schema) { var sch = schema[key]; if (Array.isArray(sch)) { if (key in traverse.arrayKeywords) { for (var i4 = 0; i4 < sch.length; i4++) _traverse(opts, pre, post, sch[i4], jsonPtr + "/" + key + "/" + i4, rootSchema, jsonPtr, key, schema, i4); } } else if (key in traverse.propsKeywords) { if (sch && typeof sch == "object") { for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); } } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); } } post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); } } function escapeJsonPtr(str) { return str.replace(/~/g, "~0").replace(/\//g, "~1"); } } }); // node_modules/ajv/dist/compile/resolve.js var require_resolve = __commonJS({ "node_modules/ajv/dist/compile/resolve.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; var util_1 = require_util(); var equal2 = require_fast_deep_equal(); var traverse = require_json_schema_traverse(); var SIMPLE_INLINED = /* @__PURE__ */ new Set([ "type", "format", "pattern", "maxLength", "minLength", "maxProperties", "minProperties", "maxItems", "minItems", "maximum", "minimum", "uniqueItems", "multipleOf", "required", "enum", "const" ]); function inlineRef(schema, limit = true) { if (typeof schema == "boolean") return true; if (limit === true) return !hasRef(schema); if (!limit) return false; return countKeys(schema) <= limit; } exports.inlineRef = inlineRef; var REF_KEYWORDS = /* @__PURE__ */ new Set([ "$ref", "$recursiveRef", "$recursiveAnchor", "$dynamicRef", "$dynamicAnchor" ]); function hasRef(schema) { for (const key in schema) { if (REF_KEYWORDS.has(key)) return true; const sch = schema[key]; if (Array.isArray(sch) && sch.some(hasRef)) return true; if (typeof sch == "object" && hasRef(sch)) return true; } return false; } function countKeys(schema) { let count = 0; for (const key in schema) { if (key === "$ref") return Infinity; count++; if (SIMPLE_INLINED.has(key)) continue; if (typeof schema[key] == "object") { (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); } if (count === Infinity) return Infinity; } return count; } function getFullPath(resolver, id = "", normalize) { if (normalize !== false) id = normalizeId(id); const p2 = resolver.parse(id); return _getFullPath(resolver, p2); } exports.getFullPath = getFullPath; function _getFullPath(resolver, p2) { const serialized = resolver.serialize(p2); return serialized.split("#")[0] + "#"; } exports._getFullPath = _getFullPath; var TRAILING_SLASH_HASH = /#\/?$/; function normalizeId(id) { return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; } exports.normalizeId = normalizeId; function resolveUrl(resolver, baseId, id) { id = normalizeId(id); return resolver.resolve(baseId, id); } exports.resolveUrl = resolveUrl; var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; function getSchemaRefs(schema, baseId) { if (typeof schema == "boolean") return {}; const { schemaId, uriResolver } = this.opts; const schId = normalizeId(schema[schemaId] || baseId); const baseIds = { "": schId }; const pathPrefix = getFullPath(uriResolver, schId, false); const localRefs = {}; const schemaRefs = /* @__PURE__ */ new Set(); traverse(schema, { allKeys: true }, (sch, jsonPtr, _2, parentJsonPtr) => { if (parentJsonPtr === void 0) return; const fullPath = pathPrefix + jsonPtr; let innerBaseId = baseIds[parentJsonPtr]; if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); addAnchor.call(this, sch.$anchor); addAnchor.call(this, sch.$dynamicAnchor); baseIds[jsonPtr] = innerBaseId; function addRef(ref) { const _resolve = this.opts.uriResolver.resolve; ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); if (schemaRefs.has(ref)) throw ambiguos(ref); schemaRefs.add(ref); let schOrRef = this.refs[ref]; if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; if (typeof schOrRef == "object") { checkAmbiguosRef(sch, schOrRef.schema, ref); } else if (ref !== normalizeId(fullPath)) { if (ref[0] === "#") { checkAmbiguosRef(sch, localRefs[ref], ref); localRefs[ref] = sch; } else { this.refs[ref] = fullPath; } } return ref; } function addAnchor(anchor) { if (typeof anchor == "string") { if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); addRef.call(this, `#${anchor}`); } } }); return localRefs; function checkAmbiguosRef(sch1, sch2, ref) { if (sch2 !== void 0 && !equal2(sch1, sch2)) throw ambiguos(ref); } function ambiguos(ref) { return new Error(`reference "${ref}" resolves to more than one schema`); } } exports.getSchemaRefs = getSchemaRefs; } }); // node_modules/ajv/dist/compile/validate/index.js var require_validate = __commonJS({ "node_modules/ajv/dist/compile/validate/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; var boolSchema_1 = require_boolSchema(); var dataType_1 = require_dataType(); var applicability_1 = require_applicability(); var dataType_2 = require_dataType(); var defaults_1 = require_defaults(); var keyword_1 = require_keyword(); var subschema_1 = require_subschema(); var codegen_1 = require_codegen(); var names_1 = require_names(); var resolve_1 = require_resolve(); var util_1 = require_util(); var errors_1 = require_errors(); function validateFunctionCode(it2) { if (isSchemaObj(it2)) { checkKeywords(it2); if (schemaCxtHasRules(it2)) { topSchemaObjCode(it2); return; } } validateFunction(it2, () => (0, boolSchema_1.topBoolOrEmptySchema)(it2)); } exports.validateFunctionCode = validateFunctionCode; function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { if (opts.code.es5) { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); destructureValCxtES5(gen, opts); gen.code(body); }); } else { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); } } function destructureValCxt(opts) { return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; } function destructureValCxtES5(gen, opts) { gen.if(names_1.default.valCxt, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); }, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); gen.var(names_1.default.rootData, names_1.default.data); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); }); } function topSchemaObjCode(it2) { const { schema, opts, gen } = it2; validateFunction(it2, () => { if (opts.$comment && schema.$comment) commentKeyword(it2); checkNoDefault(it2); gen.let(names_1.default.vErrors, null); gen.let(names_1.default.errors, 0); if (opts.unevaluated) resetEvaluated(it2); typeAndKeywords(it2); returnResults(it2); }); return; } function resetEvaluated(it2) { const { gen, validateName } = it2; it2.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); gen.if((0, codegen_1._)`${it2.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.props`, (0, codegen_1._)`undefined`)); gen.if((0, codegen_1._)`${it2.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.items`, (0, codegen_1._)`undefined`)); } function funcSourceUrl(schema, opts) { const schId = typeof schema == "object" && schema[opts.schemaId]; return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; } function subschemaCode(it2, valid) { if (isSchemaObj(it2)) { checkKeywords(it2); if (schemaCxtHasRules(it2)) { subSchemaObjCode(it2, valid); return; } } (0, boolSchema_1.boolOrEmptySchema)(it2, valid); } function schemaCxtHasRules({ schema, self }) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (self.RULES.all[key]) return true; return false; } function isSchemaObj(it2) { return typeof it2.schema != "boolean"; } function subSchemaObjCode(it2, valid) { const { schema, gen, opts } = it2; if (opts.$comment && schema.$comment) commentKeyword(it2); updateContext(it2); checkAsyncSchema(it2); const errsCount = gen.const("_errs", names_1.default.errors); typeAndKeywords(it2, errsCount); gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); } function checkKeywords(it2) { (0, util_1.checkUnknownRules)(it2); checkRefsAndKeywords(it2); } function typeAndKeywords(it2, errsCount) { if (it2.opts.jtd) return schemaKeywords(it2, [], false, errsCount); const types = (0, dataType_1.getSchemaTypes)(it2.schema); const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it2, types); schemaKeywords(it2, types, !checkedTypes, errsCount); } function checkRefsAndKeywords(it2) { const { schema, errSchemaPath, opts, self } = it2; if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); } } function checkNoDefault(it2) { const { schema, opts } = it2; if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { (0, util_1.checkStrictMode)(it2, "default is ignored in the schema root"); } } function updateContext(it2) { const schId = it2.schema[it2.opts.schemaId]; if (schId) it2.baseId = (0, resolve_1.resolveUrl)(it2.opts.uriResolver, it2.baseId, schId); } function checkAsyncSchema(it2) { if (it2.schema.$async && !it2.schemaEnv.$async) throw new Error("async schema in sync schema"); } function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { const msg = schema.$comment; if (opts.$comment === true) { gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); } else if (typeof opts.$comment == "function") { const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); } } function returnResults(it2) { const { gen, schemaEnv, validateName, ValidationError, opts } = it2; if (schemaEnv.$async) { gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); if (opts.unevaluated) assignEvaluated(it2); gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); } } function assignEvaluated({ gen, evaluated, props, items }) { if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); } function schemaKeywords(it2, types, typeErrors, errsCount) { const { gen, schema, data, allErrors, opts, self } = it2; const { RULES } = self; if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { gen.block(() => keywordCode(it2, "$ref", RULES.all.$ref.definition)); return; } if (!opts.jtd) checkStrictTypes(it2, types); gen.block(() => { for (const group of RULES.rules) groupKeywords(group); groupKeywords(RULES.post); }); function groupKeywords(group) { if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; if (group.type) { gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); iterateKeywords(it2, group); if (types.length === 1 && types[0] === group.type && typeErrors) { gen.else(); (0, dataType_2.reportTypeError)(it2); } gen.endIf(); } else { iterateKeywords(it2, group); } if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); } } function iterateKeywords(it2, group) { const { gen, schema, opts: { useDefaults } } = it2; if (useDefaults) (0, defaults_1.assignDefaults)(it2, group.type); gen.block(() => { for (const rule of group.rules) { if ((0, applicability_1.shouldUseRule)(schema, rule)) { keywordCode(it2, rule.keyword, rule.definition, group.type); } } }); } function checkStrictTypes(it2, types) { if (it2.schemaEnv.meta || !it2.opts.strictTypes) return; checkContextTypes(it2, types); if (!it2.opts.allowUnionTypes) checkMultipleTypes(it2, types); checkKeywordTypes(it2, it2.dataTypes); } function checkContextTypes(it2, types) { if (!types.length) return; if (!it2.dataTypes.length) { it2.dataTypes = types; return; } types.forEach((t4) => { if (!includesType(it2.dataTypes, t4)) { strictTypesError(it2, `type "${t4}" not allowed by context "${it2.dataTypes.join(",")}"`); } }); narrowSchemaTypes(it2, types); } function checkMultipleTypes(it2, ts2) { if (ts2.length > 1 && !(ts2.length === 2 && ts2.includes("null"))) { strictTypesError(it2, "use allowUnionTypes to allow union type keyword"); } } function checkKeywordTypes(it2, ts2) { const rules = it2.self.RULES.all; for (const keyword in rules) { const rule = rules[keyword]; if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it2.schema, rule)) { const { type } = rule.definition; if (type.length && !type.some((t4) => hasApplicableType(ts2, t4))) { strictTypesError(it2, `missing type "${type.join(",")}" for keyword "${keyword}"`); } } } } function hasApplicableType(schTs, kwdT) { return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); } function includesType(ts2, t4) { return ts2.includes(t4) || t4 === "integer" && ts2.includes("number"); } function narrowSchemaTypes(it2, withTypes) { const ts2 = []; for (const t4 of it2.dataTypes) { if (includesType(withTypes, t4)) ts2.push(t4); else if (withTypes.includes("integer") && t4 === "number") ts2.push("integer"); } it2.dataTypes = ts2; } function strictTypesError(it2, msg) { const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath; msg += ` at "${schemaPath}" (strictTypes)`; (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictTypes); } var KeywordCxt = class { constructor(it2, def, keyword) { (0, keyword_1.validateKeywordUsage)(it2, def, keyword); this.gen = it2.gen; this.allErrors = it2.allErrors; this.keyword = keyword; this.data = it2.data; this.schema = it2.schema[keyword]; this.$data = def.$data && it2.opts.$data && this.schema && this.schema.$data; this.schemaValue = (0, util_1.schemaRefOrVal)(it2, this.schema, keyword, this.$data); this.schemaType = def.schemaType; this.parentSchema = it2.schema; this.params = {}; this.it = it2; this.def = def; if (this.$data) { this.schemaCode = it2.gen.const("vSchema", getData(this.$data, it2)); } else { this.schemaCode = this.schemaValue; if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it2.gen.const("_errs", names_1.default.errors); } } result(condition, successAction, failAction) { this.failResult((0, codegen_1.not)(condition), successAction, failAction); } failResult(condition, successAction, failAction) { this.gen.if(condition); if (failAction) failAction(); else this.error(); if (successAction) { this.gen.else(); successAction(); if (this.allErrors) this.gen.endIf(); } else { if (this.allErrors) this.gen.endIf(); else this.gen.else(); } } pass(condition, failAction) { this.failResult((0, codegen_1.not)(condition), void 0, failAction); } fail(condition) { if (condition === void 0) { this.error(); if (!this.allErrors) this.gen.if(false); return; } this.gen.if(condition); this.error(); if (this.allErrors) this.gen.endIf(); else this.gen.else(); } fail$data(condition) { if (!this.$data) return this.fail(condition); const { schemaCode } = this; this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); } error(append, errorParams, errorPaths) { if (errorParams) { this.setParams(errorParams); this._error(append, errorPaths); this.setParams({}); return; } this._error(append, errorPaths); } _error(append, errorPaths) { ; (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); } $dataError() { (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); } reset() { if (this.errsCount === void 0) throw new Error('add "trackErrors" to keyword definition'); (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); } ok(cond) { if (!this.allErrors) this.gen.if(cond); } setParams(obj, assign) { if (assign) Object.assign(this.params, obj); else this.params = obj; } block$data(valid, codeBlock, $dataValid = codegen_1.nil) { this.gen.block(() => { this.check$data(valid, $dataValid); codeBlock(); }); } check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { if (!this.$data) return; const { gen, schemaCode, schemaType, def } = this; gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); if (valid !== codegen_1.nil) gen.assign(valid, true); if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()); this.$dataError(); if (valid !== codegen_1.nil) gen.assign(valid, false); } gen.else(); } invalid$data() { const { gen, schemaCode, schemaType, def, it: it2 } = this; return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); function wrong$DataType() { if (schemaType.length) { if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); const st2 = Array.isArray(schemaType) ? schemaType : [schemaType]; return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st2, schemaCode, it2.opts.strictNumbers, dataType_2.DataType.Wrong)}`; } return codegen_1.nil; } function invalid$DataSchema() { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; } return codegen_1.nil; } } subschema(appl, valid) { const subschema = (0, subschema_1.getSubschema)(this.it, appl); (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); (0, subschema_1.extendSubschemaMode)(subschema, appl); const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; subschemaCode(nextContext, valid); return nextContext; } mergeEvaluated(schemaCxt, toName) { const { it: it2, gen } = this; if (!it2.opts.unevaluated) return; if (it2.props !== true && schemaCxt.props !== void 0) { it2.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it2.props, toName); } if (it2.items !== true && schemaCxt.items !== void 0) { it2.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it2.items, toName); } } mergeValidEvaluated(schemaCxt, valid) { const { it: it2, gen } = this; if (it2.opts.unevaluated && (it2.props !== true || it2.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); return true; } } }; exports.KeywordCxt = KeywordCxt; function keywordCode(it2, keyword, def, ruleType) { const cxt = new KeywordCxt(it2, def, keyword); if ("code" in def) { def.code(cxt, ruleType); } else if (cxt.$data && def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } else if ("macro" in def) { (0, keyword_1.macroKeywordCode)(cxt, def); } else if (def.compile || def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } } var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; function getData($data, { dataLevel, dataNames, dataPathArr }) { let jsonPointer; let data; if ($data === "") return names_1.default.rootData; if ($data[0] === "/") { if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); jsonPointer = $data; data = names_1.default.rootData; } else { const matches = RELATIVE_JSON_POINTER.exec($data); if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); const up = +matches[1]; jsonPointer = matches[2]; if (jsonPointer === "#") { if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); return dataPathArr[dataLevel - up]; } if (up > dataLevel) throw new Error(errorMsg("data", up)); data = dataNames[dataLevel - up]; if (!jsonPointer) return data; } let expr = data; const segments = jsonPointer.split("/"); for (const segment2 of segments) { if (segment2) { data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment2))}`; expr = (0, codegen_1._)`${expr} && ${data}`; } } return expr; function errorMsg(pointerType, up) { return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; } } exports.getData = getData; } }); // node_modules/ajv/dist/runtime/validation_error.js var require_validation_error = __commonJS({ "node_modules/ajv/dist/runtime/validation_error.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ValidationError = class extends Error { constructor(errors) { super("validation failed"); this.errors = errors; this.ajv = this.validation = true; } }; exports.default = ValidationError; } }); // node_modules/ajv/dist/compile/ref_error.js var require_ref_error = __commonJS({ "node_modules/ajv/dist/compile/ref_error.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var resolve_1 = require_resolve(); var MissingRefError = class extends Error { constructor(resolver, baseId, ref, msg) { super(msg || `can't resolve reference ${ref} from id ${baseId}`); this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); } }; exports.default = MissingRefError; } }); // node_modules/ajv/dist/compile/index.js var require_compile = __commonJS({ "node_modules/ajv/dist/compile/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; var codegen_1 = require_codegen(); var validation_error_1 = require_validation_error(); var names_1 = require_names(); var resolve_1 = require_resolve(); var util_1 = require_util(); var validate_1 = require_validate(); var SchemaEnv = class { constructor(env) { var _a25; this.refs = {}; this.dynamicAnchors = {}; let schema; if (typeof env.schema == "object") schema = env.schema; this.schema = env.schema; this.schemaId = env.schemaId; this.root = env.root || this; this.baseId = (_a25 = env.baseId) !== null && _a25 !== void 0 ? _a25 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); this.schemaPath = env.schemaPath; this.localRefs = env.localRefs; this.meta = env.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } }; exports.SchemaEnv = SchemaEnv; function compileSchema(sch) { const _sch = getCompilingSchema.call(this, sch); if (_sch) return _sch; const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); let _ValidationError; if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: validation_error_1.default, code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` }); } const validateName = gen.scopeName("validate"); sch.validateName = validateName; const schemaCxt = { gen, allErrors: this.opts.allErrors, data: names_1.default.data, parentData: names_1.default.parentData, parentDataProperty: names_1.default.parentDataProperty, dataNames: [names_1.default.data], dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: /* @__PURE__ */ new Set(), topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: codegen_1.nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: (0, codegen_1._)`""`, opts: this.opts, self: this }; let sourceCode; try { this._compilations.add(sch); (0, validate_1.validateFunctionCode)(schemaCxt); gen.optimize(this.opts.code.optimize); const validateCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); const validate = makeValidate(this, this.scope.get()); this.scope.value(validateName, { ref: validate }); validate.errors = null; validate.schema = sch.schema; validate.schemaEnv = sch; if (sch.$async) validate.$async = true; if (this.opts.code.source === true) { validate.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; validate.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); } sch.validate = validate; return sch; } catch (e5) { delete sch.validate; delete sch.validateName; if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); throw e5; } finally { this._compilations.delete(sch); } } exports.compileSchema = compileSchema; function resolveRef(root, baseId, ref) { var _a25; ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); const schOrFunc = root.refs[ref]; if (schOrFunc) return schOrFunc; let _sch = resolve3.call(this, root, ref); if (_sch === void 0) { const schema = (_a25 = root.localRefs) === null || _a25 === void 0 ? void 0 : _a25[ref]; const { schemaId } = this.opts; if (schema) _sch = new SchemaEnv({ schema, schemaId, root, baseId }); } if (_sch === void 0) return; return root.refs[ref] = inlineOrCompile.call(this, _sch); } exports.resolveRef = resolveRef; function inlineOrCompile(sch) { if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; return sch.validate ? sch : compileSchema.call(this, sch); } function getCompilingSchema(schEnv) { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) return sch; } } exports.getCompilingSchema = getCompilingSchema; function sameSchemaEnv(s1, s2) { return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; } function resolve3(root, ref) { let sch; while (typeof (sch = this.refs[ref]) == "string") ref = sch; return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); } function resolveSchema(root, ref) { const p2 = this.opts.uriResolver.parse(ref); const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p2); let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); if (Object.keys(root.schema).length > 0 && refPath === baseId) { return getJsonPointer.call(this, p2, root); } const id = (0, resolve_1.normalizeId)(refPath); const schOrRef = this.refs[id] || this.schemas[id]; if (typeof schOrRef == "string") { const sch = resolveSchema.call(this, root, schOrRef); if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; return getJsonPointer.call(this, p2, sch); } if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; if (!schOrRef.validate) compileSchema.call(this, schOrRef); if (id === (0, resolve_1.normalizeId)(ref)) { const { schema } = schOrRef; const { schemaId } = this.opts; const schId = schema[schemaId]; if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); return new SchemaEnv({ schema, schemaId, root, baseId }); } return getJsonPointer.call(this, p2, schOrRef); } exports.resolveSchema = resolveSchema; var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ "properties", "patternProperties", "enum", "dependencies", "definitions" ]); function getJsonPointer(parsedRef, { baseId, schema, root }) { var _a25; if (((_a25 = parsedRef.fragment) === null || _a25 === void 0 ? void 0 : _a25[0]) !== "/") return; for (const part of parsedRef.fragment.slice(1).split("/")) { if (typeof schema === "boolean") return; const partSchema = schema[(0, util_1.unescapeFragment)(part)]; if (partSchema === void 0) return; schema = partSchema; const schId = typeof schema === "object" && schema[this.opts.schemaId]; if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } let env; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); env = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; env = env || new SchemaEnv({ schema, schemaId, root, baseId }); if (env.schema !== env.root.schema) return env; return void 0; } } }); // node_modules/ajv/dist/refs/data.json var require_data = __commonJS({ "node_modules/ajv/dist/refs/data.json"(exports, module) { module.exports = { $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", type: "object", required: ["$data"], properties: { $data: { type: "string", anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] } }, additionalProperties: false }; } }); // node_modules/fast-uri/lib/utils.js var require_utils = __commonJS({ "node_modules/fast-uri/lib/utils.js"(exports, module) { "use strict"; var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); var isIPv42 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu); var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu); var isPathCharacter = RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu); function stringArrayToHexStripped(input) { let acc = ""; let code = 0; let i4 = 0; for (i4 = 0; i4 < input.length; i4++) { code = input[i4].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } acc += input[i4]; break; } for (i4 += 1; i4 < input.length; i4++) { code = input[i4].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } acc += input[i4]; } return acc; } var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); function consumeIsZone(buffer) { buffer.length = 0; return true; } function consumeHextets(buffer, address, output) { if (buffer.length) { const hex = stringArrayToHexStripped(buffer); if (hex !== "") { address.push(hex); } else { output.error = true; return false; } buffer.length = 0; } return true; } function getIPV6(input) { let tokenCount = 0; const output = { error: false, address: "", zone: "" }; const address = []; const buffer = []; let endipv6Encountered = false; let endIpv6 = false; let consume = consumeHextets; for (let i4 = 0; i4 < input.length; i4++) { const cursor = input[i4]; if (cursor === "[" || cursor === "]") { continue; } if (cursor === ":") { if (endipv6Encountered === true) { endIpv6 = true; } if (!consume(buffer, address, output)) { break; } if (++tokenCount > 7) { output.error = true; break; } if (i4 > 0 && input[i4 - 1] === ":") { endipv6Encountered = true; } address.push(":"); continue; } else if (cursor === "%") { if (!consume(buffer, address, output)) { break; } consume = consumeIsZone; } else { buffer.push(cursor); continue; } } if (buffer.length) { if (consume === consumeIsZone) { output.zone = buffer.join(""); } else if (endIpv6) { address.push(buffer.join("")); } else { address.push(stringArrayToHexStripped(buffer)); } } output.address = address.join(""); return output; } function normalizeIPv6(host2) { if (findToken(host2, ":") < 2) { return { host: host2, isIPV6: false }; } const ipv63 = getIPV6(host2); if (!ipv63.error) { let newHost = ipv63.address; let escapedHost = ipv63.address; if (ipv63.zone) { newHost += "%" + ipv63.zone; escapedHost += "%25" + ipv63.zone; } return { host: newHost, isIPV6: true, escapedHost }; } else { return { host: host2, isIPV6: false }; } } function findToken(str, token2) { let ind = 0; for (let i4 = 0; i4 < str.length; i4++) { if (str[i4] === token2) ind++; } return ind; } function removeDotSegments(path) { let input = path; const output = []; let nextSlash = -1; let len = 0; while (len = input.length) { if (len === 1) { if (input === ".") { break; } else if (input === "/") { output.push("/"); break; } else { output.push(input); break; } } else if (len === 2) { if (input[0] === ".") { if (input[1] === ".") { break; } else if (input[1] === "/") { input = input.slice(2); continue; } } else if (input[0] === "/") { if (input[1] === "." || input[1] === "/") { output.push("/"); break; } } } else if (len === 3) { if (input === "/..") { if (output.length !== 0) { output.pop(); } output.push("/"); break; } } if (input[0] === ".") { if (input[1] === ".") { if (input[2] === "/") { input = input.slice(3); continue; } } else if (input[1] === "/") { input = input.slice(2); continue; } } else if (input[0] === "/") { if (input[1] === ".") { if (input[2] === "/") { input = input.slice(2); continue; } else if (input[2] === ".") { if (input[3] === "/") { input = input.slice(3); if (output.length !== 0) { output.pop(); } continue; } } } } if ((nextSlash = input.indexOf("/", 1)) === -1) { output.push(input); break; } else { output.push(input.slice(0, nextSlash)); input = input.slice(nextSlash); } } return output.join(""); } var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; var HOST_DELIM_RE = /[@/?#:]/g; var HOST_DELIM_NO_COLON_RE = /[@/?#]/g; function reescapeHostDelimiters(host2, isIP) { const re2 = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE; re2.lastIndex = 0; return host2.replace(re2, (ch2) => HOST_DELIMS[ch2]); } function normalizePercentEncoding(input, decodeUnreserved = false) { if (input.indexOf("%") === -1) { return input; } let output = ""; for (let i4 = 0; i4 < input.length; i4++) { if (input[i4] === "%" && i4 + 2 < input.length) { const hex = input.slice(i4 + 1, i4 + 3); if (isHexPair(hex)) { const normalizedHex = hex.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decodeUnreserved && isUnreserved(decoded)) { output += decoded; } else { output += "%" + normalizedHex; } i4 += 2; continue; } } output += input[i4]; } return output; } function normalizePathEncoding(input) { let output = ""; for (let i4 = 0; i4 < input.length; i4++) { if (input[i4] === "%" && i4 + 2 < input.length) { const hex = input.slice(i4 + 1, i4 + 3); if (isHexPair(hex)) { const normalizedHex = hex.toUpperCase(); const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); if (decoded !== "." && isUnreserved(decoded)) { output += decoded; } else { output += "%" + normalizedHex; } i4 += 2; continue; } } if (isPathCharacter(input[i4])) { output += input[i4]; } else { output += escape(input[i4]); } } return output; } function escapePreservingEscapes(input) { let output = ""; for (let i4 = 0; i4 < input.length; i4++) { if (input[i4] === "%" && i4 + 2 < input.length) { const hex = input.slice(i4 + 1, i4 + 3); if (isHexPair(hex)) { output += "%" + hex.toUpperCase(); i4 += 2; continue; } } output += escape(input[i4]); } return output; } function recomposeAuthority(component) { const uriTokens = []; if (component.userinfo !== void 0) { uriTokens.push(component.userinfo); uriTokens.push("@"); } if (component.host !== void 0) { let host2 = unescape(component.host); if (!isIPv42(host2)) { const ipV6res = normalizeIPv6(host2); if (ipV6res.isIPV6 === true) { host2 = `[${ipV6res.escapedHost}]`; } else { host2 = reescapeHostDelimiters(host2, false); } } uriTokens.push(host2); } if (typeof component.port === "number" || typeof component.port === "string") { uriTokens.push(":"); uriTokens.push(String(component.port)); } return uriTokens.length ? uriTokens.join("") : void 0; } module.exports = { nonSimpleDomain, recomposeAuthority, reescapeHostDelimiters, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, removeDotSegments, isIPv4: isIPv42, isUUID, normalizeIPv6, stringArrayToHexStripped }; } }); // node_modules/fast-uri/lib/schemes.js var require_schemes = __commonJS({ "node_modules/fast-uri/lib/schemes.js"(exports, module) { "use strict"; var { isUUID } = require_utils(); var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; var supportedSchemeNames = ( /** @type {const} */ [ "http", "https", "ws", "wss", "urn", "urn:uuid" ] ); function isValidSchemeName(name24) { return supportedSchemeNames.indexOf( /** @type {*} */ name24 ) !== -1; } function wsIsSecure(wsComponent) { if (wsComponent.secure === true) { return true; } else if (wsComponent.secure === false) { return false; } else if (wsComponent.scheme) { return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); } else { return false; } } function httpParse(component) { if (!component.host) { component.error = component.error || "HTTP URIs must have a host."; } return component; } function httpSerialize(component) { const secure = String(component.scheme).toLowerCase() === "https"; if (component.port === (secure ? 443 : 80) || component.port === "") { component.port = void 0; } if (!component.path) { component.path = "/"; } return component; } function wsParse(wsComponent) { wsComponent.secure = wsIsSecure(wsComponent); wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); wsComponent.path = void 0; wsComponent.query = void 0; return wsComponent; } function wsSerialize(wsComponent) { if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { wsComponent.port = void 0; } if (typeof wsComponent.secure === "boolean") { wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; wsComponent.secure = void 0; } if (wsComponent.resourceName) { const [path, query] = wsComponent.resourceName.split("?"); wsComponent.path = path && path !== "/" ? path : void 0; wsComponent.query = query; wsComponent.resourceName = void 0; } wsComponent.fragment = void 0; return wsComponent; } function urnParse(urnComponent, options) { if (!urnComponent.path) { urnComponent.error = "URN can not be parsed"; return urnComponent; } const matches = urnComponent.path.match(URN_REG); if (matches) { const scheme = options.scheme || urnComponent.scheme || "urn"; urnComponent.nid = matches[1].toLowerCase(); urnComponent.nss = matches[2]; const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; const schemeHandler = getSchemeHandler(urnScheme); urnComponent.path = void 0; if (schemeHandler) { urnComponent = schemeHandler.parse(urnComponent, options); } } else { urnComponent.error = urnComponent.error || "URN can not be parsed."; } return urnComponent; } function urnSerialize(urnComponent, options) { if (urnComponent.nid === void 0) { throw new Error("URN without nid cannot be serialized"); } const scheme = options.scheme || urnComponent.scheme || "urn"; const nid = urnComponent.nid.toLowerCase(); const urnScheme = `${scheme}:${options.nid || nid}`; const schemeHandler = getSchemeHandler(urnScheme); if (schemeHandler) { urnComponent = schemeHandler.serialize(urnComponent, options); } const uriComponent = urnComponent; const nss = urnComponent.nss; uriComponent.path = `${nid || options.nid}:${nss}`; options.skipEscape = true; return uriComponent; } function urnuuidParse(urnComponent, options) { const uuidComponent = urnComponent; uuidComponent.uuid = uuidComponent.nss; uuidComponent.nss = void 0; if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { uuidComponent.error = uuidComponent.error || "UUID is not valid."; } return uuidComponent; } function urnuuidSerialize(uuidComponent) { const urnComponent = uuidComponent; urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); return urnComponent; } var http = ( /** @type {SchemeHandler} */ { scheme: "http", domainHost: true, parse: httpParse, serialize: httpSerialize } ); var https = ( /** @type {SchemeHandler} */ { scheme: "https", domainHost: http.domainHost, parse: httpParse, serialize: httpSerialize } ); var ws2 = ( /** @type {SchemeHandler} */ { scheme: "ws", domainHost: true, parse: wsParse, serialize: wsSerialize } ); var wss = ( /** @type {SchemeHandler} */ { scheme: "wss", domainHost: ws2.domainHost, parse: ws2.parse, serialize: ws2.serialize } ); var urn = ( /** @type {SchemeHandler} */ { scheme: "urn", parse: urnParse, serialize: urnSerialize, skipNormalize: true } ); var urnuuid = ( /** @type {SchemeHandler} */ { scheme: "urn:uuid", parse: urnuuidParse, serialize: urnuuidSerialize, skipNormalize: true } ); var SCHEMES = ( /** @type {Record} */ { http, https, ws: ws2, wss, urn, "urn:uuid": urnuuid } ); Object.setPrototypeOf(SCHEMES, null); function getSchemeHandler(scheme) { return scheme && (SCHEMES[ /** @type {SchemeName} */ scheme ] || SCHEMES[ /** @type {SchemeName} */ scheme.toLowerCase() ]) || void 0; } module.exports = { wsIsSecure, SCHEMES, isValidSchemeName, getSchemeHandler }; } }); // node_modules/fast-uri/index.js var require_fast_uri = __commonJS({ "node_modules/fast-uri/index.js"(exports, module) { "use strict"; var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4: isIPv42, nonSimpleDomain } = require_utils(); var { SCHEMES, getSchemeHandler } = require_schemes(); function normalize(uri, options) { if (typeof uri === "string") { uri = /** @type {T} */ normalizeString(uri, options); } else if (typeof uri === "object") { uri = /** @type {T} */ parse3(serialize(uri, options), options); } return uri; } function resolve3(baseURI, relativeURI, options) { const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; const { parsed: baseParsed, malformedAuthorityOrPort: baseMalformed } = parseWithStatus(baseURI, schemelessOptions); const { parsed: relativeParsed, malformedAuthorityOrPort: relativeMalformed } = parseWithStatus(relativeURI, schemelessOptions); if (baseMalformed || relativeMalformed) { throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed."); } const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true); schemelessOptions.skipEscape = true; return serialize(resolved, schemelessOptions); } function resolveComponent(base, relative, options, skipNormalization) { const target = {}; if (!skipNormalization) { base = parse3(serialize(base, options), options); relative = parse3(serialize(relative, options), options); } options = options || {}; if (!options.tolerant && relative.scheme) { target.scheme = relative.scheme; target.userinfo = relative.userinfo; target.host = relative.host; target.port = relative.port; target.path = removeDotSegments(relative.path || ""); target.query = relative.query; } else { if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { target.userinfo = relative.userinfo; target.host = relative.host; target.port = relative.port; target.path = removeDotSegments(relative.path || ""); target.query = relative.query; } else { if (!relative.path) { target.path = base.path; if (relative.query !== void 0) { target.query = relative.query; } else { target.query = base.query; } } else { if (relative.path[0] === "/") { target.path = removeDotSegments(relative.path); } else { if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { target.path = "/" + relative.path; } else if (!base.path) { target.path = relative.path; } else { target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; } target.path = removeDotSegments(target.path); } target.query = relative.query; } target.userinfo = base.userinfo; target.host = base.host; target.port = base.port; } target.scheme = base.scheme; } target.fragment = relative.fragment; return target; } function equal2(uriA, uriB, options) { const normalizedA = normalizeComparableURI(uriA, options); const normalizedB = normalizeComparableURI(uriB, options); return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA.toLowerCase() === normalizedB.toLowerCase(); } function serialize(cmpts, opts) { const component = { host: cmpts.host, scheme: cmpts.scheme, userinfo: cmpts.userinfo, port: cmpts.port, path: cmpts.path, query: cmpts.query, nid: cmpts.nid, nss: cmpts.nss, uuid: cmpts.uuid, fragment: cmpts.fragment, reference: cmpts.reference, resourceName: cmpts.resourceName, secure: cmpts.secure, error: "" }; const options = Object.assign({}, opts); const uriTokens = []; const schemeHandler = getSchemeHandler(options.scheme || component.scheme); if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); if (component.path !== void 0) { if (!options.skipEscape) { component.path = escapePreservingEscapes(component.path); if (component.scheme !== void 0) { component.path = component.path.split("%3A").join(":"); } } else { component.path = normalizePercentEncoding(component.path); } } if (options.reference !== "suffix" && component.scheme) { uriTokens.push(component.scheme, ":"); } const authority = recomposeAuthority(component); if (authority !== void 0) { if (options.reference !== "suffix") { uriTokens.push("//"); } uriTokens.push(authority); if (component.path && component.path[0] !== "/") { uriTokens.push("/"); } } if (component.path !== void 0) { let s2 = component.path; if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { s2 = removeDotSegments(s2); } if (authority === void 0 && s2[0] === "/" && s2[1] === "/") { s2 = "/%2F" + s2.slice(2); } uriTokens.push(s2); } if (component.query !== void 0) { uriTokens.push("?", component.query); } if (component.fragment !== void 0) { uriTokens.push("#", component.fragment); } return uriTokens.join(""); } var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/; var AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/; function getParseError(parsed, matches) { if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") { return 'URI path must start with "/" when authority is present.'; } if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) { return "URI port is malformed."; } return void 0; } function parseWithStatus(uri, opts) { const options = Object.assign({}, opts); const parsed = { scheme: void 0, userinfo: void 0, host: "", port: void 0, path: "", query: void 0, fragment: void 0 }; let malformedAuthorityOrPort = false; let isIP = false; if (options.reference === "suffix") { if (options.scheme) { uri = options.scheme + ":" + uri; } else { uri = "//" + uri; } } const authorityMatch = uri.match(AUTHORITY_PREFIX); if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) { parsed.error = "URI authority must not contain a literal backslash."; malformedAuthorityOrPort = true; } const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION); if (introducerMatch !== null) { const region = introducerMatch[1]; const normalizedRegion = region.replace(/[\t\n\r]/g, ""); if (normalizedRegion.length >= 2) { if (normalizedRegion.slice(0, 2) !== "//") { parsed.error = parsed.error || "URI authority must not contain a literal backslash."; malformedAuthorityOrPort = true; } else if (region.length !== normalizedRegion.length) { parsed.error = parsed.error || "URI authority introducer must not contain whitespace."; malformedAuthorityOrPort = true; } } } const matches = uri.match(URI_PARSE); if (matches) { parsed.scheme = matches[1]; parsed.userinfo = matches[3]; parsed.host = matches[4]; parsed.port = parseInt(matches[5], 10); parsed.path = matches[6] || ""; parsed.query = matches[7]; parsed.fragment = matches[8]; if (isNaN(parsed.port)) { parsed.port = matches[5]; } const parseError = getParseError(parsed, matches); if (parseError !== void 0) { parsed.error = parsed.error || parseError; malformedAuthorityOrPort = true; } if (parsed.host) { const ipv4result = isIPv42(parsed.host); if (ipv4result === false) { const ipv6result = normalizeIPv6(parsed.host); parsed.host = ipv6result.host.toLowerCase(); isIP = ipv6result.isIPV6; } else { isIP = true; } } if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { parsed.reference = "same-document"; } else if (parsed.scheme === void 0) { parsed.reference = "relative"; } else if (parsed.fragment === void 0) { parsed.reference = "absolute"; } else { parsed.reference = "uri"; } if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; } const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) { try { parsed.host = new URL("http://" + parsed.host).hostname; } catch (e5) { parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e5; } } } if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { if (uri.indexOf("%") !== -1) { if (parsed.scheme !== void 0) { parsed.scheme = unescape(parsed.scheme); } if (parsed.host !== void 0) { parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP); } } if (parsed.path) { parsed.path = normalizePathEncoding(parsed.path); } if (parsed.fragment) { try { parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); } catch { parsed.error = parsed.error || "URI malformed"; } } } if (schemeHandler && schemeHandler.parse) { schemeHandler.parse(parsed, options); } } else { parsed.error = parsed.error || "URI can not be parsed."; } return { parsed, malformedAuthorityOrPort }; } function parse3(uri, opts) { return parseWithStatus(uri, opts).parsed; } function normalizeString(uri, opts) { return normalizeStringWithStatus(uri, opts).normalized; } function normalizeStringWithStatus(uri, opts) { const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts); return { normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts), malformedAuthorityOrPort }; } function normalizeComparableURI(uri, opts) { if (typeof uri === "string") { const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts); return malformedAuthorityOrPort ? void 0 : normalized; } if (typeof uri === "object") { return serialize(uri, opts); } } var fastUri = { SCHEMES, normalize, resolve: resolve3, resolveComponent, equal: equal2, serialize, parse: parse3 }; module.exports = fastUri; module.exports.default = fastUri; module.exports.fastUri = fastUri; } }); // node_modules/ajv/dist/runtime/uri.js var require_uri = __commonJS({ "node_modules/ajv/dist/runtime/uri.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var uri = require_fast_uri(); uri.code = 'require("ajv/dist/runtime/uri").default'; exports.default = uri; } }); // node_modules/ajv/dist/core.js var require_core = __commonJS({ "node_modules/ajv/dist/core.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; var validate_1 = require_validate(); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error(); var ref_error_1 = require_ref_error(); var rules_1 = require_rules(); var compile_1 = require_compile(); var codegen_2 = require_codegen(); var resolve_1 = require_resolve(); var dataType_1 = require_dataType(); var util_1 = require_util(); var $dataRefSchema = require_data(); var uri_1 = require_uri(); var defaultRegExp = (str, flags) => new RegExp(str, flags); defaultRegExp.code = "new RegExp"; var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ "validate", "serialize", "parse", "wrapper", "root", "schema", "keyword", "pattern", "formats", "validate$data", "func", "obj", "Error" ]); var removedOptions = { errorDataPath: "", format: "`validateFormats: false` can be used instead.", nullable: '"nullable" keyword is supported by default.', jsonPointers: "Deprecated jsPropertySyntax can be used instead.", extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", sourceCode: "Use option `code: {source: true}`", strictDefaults: "It is default now, see option `strict`.", strictKeywords: "It is default now, see option `strict`.", uniqueItems: '"uniqueItems" keyword is always validated.', unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", cache: "Map is used as cache, schema object as key.", serialize: "Map is used as cache, schema object as key.", ajvErrors: "It is default now." }; var deprecatedOptions = { ignoreKeywordsWithRef: "", jsPropertySyntax: "", unicode: '"minLength"/"maxLength" account for unicode characters by default.' }; var MAX_EXPRESSION = 200; function requiredOptions(o3) { var _a25, _b19, _c, _d, _e2, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r2, _s2, _t2, _u, _v, _w, _x, _y, _z, _0; const s2 = o3.strict; const _optz = (_a25 = o3.code) === null || _a25 === void 0 ? void 0 : _a25.optimize; const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; const regExp = (_c = (_b19 = o3.code) === null || _b19 === void 0 ? void 0 : _b19.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; const uriResolver = (_d = o3.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; return { strictSchema: (_f = (_e2 = o3.strictSchema) !== null && _e2 !== void 0 ? _e2 : s2) !== null && _f !== void 0 ? _f : true, strictNumbers: (_h = (_g = o3.strictNumbers) !== null && _g !== void 0 ? _g : s2) !== null && _h !== void 0 ? _h : true, strictTypes: (_k = (_j = o3.strictTypes) !== null && _j !== void 0 ? _j : s2) !== null && _k !== void 0 ? _k : "log", strictTuples: (_m = (_l = o3.strictTuples) !== null && _l !== void 0 ? _l : s2) !== null && _m !== void 0 ? _m : "log", strictRequired: (_p = (_o = o3.strictRequired) !== null && _o !== void 0 ? _o : s2) !== null && _p !== void 0 ? _p : false, code: o3.code ? { ...o3.code, optimize, regExp } : { optimize, regExp }, loopRequired: (_q = o3.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, loopEnum: (_r2 = o3.loopEnum) !== null && _r2 !== void 0 ? _r2 : MAX_EXPRESSION, meta: (_s2 = o3.meta) !== null && _s2 !== void 0 ? _s2 : true, messages: (_t2 = o3.messages) !== null && _t2 !== void 0 ? _t2 : true, inlineRefs: (_u = o3.inlineRefs) !== null && _u !== void 0 ? _u : true, schemaId: (_v = o3.schemaId) !== null && _v !== void 0 ? _v : "$id", addUsedSchema: (_w = o3.addUsedSchema) !== null && _w !== void 0 ? _w : true, validateSchema: (_x = o3.validateSchema) !== null && _x !== void 0 ? _x : true, validateFormats: (_y = o3.validateFormats) !== null && _y !== void 0 ? _y : true, unicodeRegExp: (_z = o3.unicodeRegExp) !== null && _z !== void 0 ? _z : true, int32range: (_0 = o3.int32range) !== null && _0 !== void 0 ? _0 : true, uriResolver }; } var Ajv2 = class { constructor(opts = {}) { this.schemas = {}; this.refs = {}; this.formats = /* @__PURE__ */ Object.create(null); this._compilations = /* @__PURE__ */ new Set(); this._loading = {}; this._cache = /* @__PURE__ */ new Map(); opts = this.opts = { ...opts, ...requiredOptions(opts) }; const { es5, lines } = this.opts.code; this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); this.logger = getLogger(opts.logger); const formatOpt = opts.validateFormats; opts.validateFormats = false; this.RULES = (0, rules_1.getRules)(); checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); this._metaOpts = getMetaSchemaOptions.call(this); if (opts.formats) addInitialFormats.call(this); this._addVocabularies(); this._addDefaultMetaSchema(); if (opts.keywords) addInitialKeywords.call(this, opts.keywords); if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); addInitialSchemas.call(this); opts.validateFormats = formatOpt; } _addVocabularies() { this.addKeyword("$async"); } _addDefaultMetaSchema() { const { $data, meta, schemaId } = this.opts; let _dataRefSchema = $dataRefSchema; if (schemaId === "id") { _dataRefSchema = { ...$dataRefSchema }; _dataRefSchema.id = _dataRefSchema.$id; delete _dataRefSchema.$id; } if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); } defaultMeta() { const { meta, schemaId } = this.opts; return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; } validate(schemaKeyRef, data) { let v2; if (typeof schemaKeyRef == "string") { v2 = this.getSchema(schemaKeyRef); if (!v2) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); } else { v2 = this.compile(schemaKeyRef); } const valid = v2(data); if (!("$async" in v2)) this.errors = v2.errors; return valid; } compile(schema, _meta) { const sch = this._addSchema(schema, _meta); return sch.validate || this._compileSchemaEnv(sch); } compileAsync(schema, meta) { if (typeof this.opts.loadSchema != "function") { throw new Error("options.loadSchema should be a function"); } const { loadSchema } = this.opts; return runCompileAsync.call(this, schema, meta); async function runCompileAsync(_schema, _meta) { await loadMetaSchema.call(this, _schema.$schema); const sch = this._addSchema(_schema, _meta); return sch.validate || _compileAsync.call(this, sch); } async function loadMetaSchema($ref) { if ($ref && !this.getSchema($ref)) { await runCompileAsync.call(this, { $ref }, true); } } async function _compileAsync(sch) { try { return this._compileSchemaEnv(sch); } catch (e5) { if (!(e5 instanceof ref_error_1.default)) throw e5; checkLoaded.call(this, e5); await loadMissingSchema.call(this, e5.missingSchema); return _compileAsync.call(this, sch); } } function checkLoaded({ missingSchema: ref, missingRef }) { if (this.refs[ref]) { throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); } } async function loadMissingSchema(ref) { const _schema = await _loadSchema.call(this, ref); if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); if (!this.refs[ref]) this.addSchema(_schema, ref, meta); } async function _loadSchema(ref) { const p2 = this._loading[ref]; if (p2) return p2; try { return await (this._loading[ref] = loadSchema(ref)); } finally { delete this._loading[ref]; } } } // Adds schema to the instance addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { if (Array.isArray(schema)) { for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); return this; } let id; if (typeof schema === "object") { const { schemaId } = this.opts; id = schema[schemaId]; if (id !== void 0 && typeof id != "string") { throw new Error(`schema ${schemaId} must be string`); } } key = (0, resolve_1.normalizeId)(key || id); this._checkUnique(key); this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); return this; } // Add schema that will be used to validate other schemas // options in META_IGNORE_OPTIONS are alway set to false addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { this.addSchema(schema, key, true, _validateSchema); return this; } // Validate schema against its meta-schema validateSchema(schema, throwOrLogError) { if (typeof schema == "boolean") return true; let $schema; $schema = schema.$schema; if ($schema !== void 0 && typeof $schema != "string") { throw new Error("$schema must be a string"); } $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); if (!$schema) { this.logger.warn("meta-schema not available"); this.errors = null; return true; } const valid = this.validate($schema, schema); if (!valid && throwOrLogError) { const message = "schema is invalid: " + this.errorsText(); if (this.opts.validateSchema === "log") this.logger.error(message); else throw new Error(message); } return valid; } // Get compiled schema by `key` or `ref`. // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) getSchema(keyRef) { let sch; while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; if (sch === void 0) { const { schemaId } = this.opts; const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); sch = compile_1.resolveSchema.call(this, root, keyRef); if (!sch) return; this.refs[keyRef] = sch; } return sch.validate || this._compileSchemaEnv(sch); } // Remove cached schema(s). // If no parameter is passed all schemas but meta-schemas are removed. // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. removeSchema(schemaKeyRef) { if (schemaKeyRef instanceof RegExp) { this._removeAllSchemas(this.schemas, schemaKeyRef); this._removeAllSchemas(this.refs, schemaKeyRef); return this; } switch (typeof schemaKeyRef) { case "undefined": this._removeAllSchemas(this.schemas); this._removeAllSchemas(this.refs); this._cache.clear(); return this; case "string": { const sch = getSchEnv.call(this, schemaKeyRef); if (typeof sch == "object") this._cache.delete(sch.schema); delete this.schemas[schemaKeyRef]; delete this.refs[schemaKeyRef]; return this; } case "object": { const cacheKey = schemaKeyRef; this._cache.delete(cacheKey); let id = schemaKeyRef[this.opts.schemaId]; if (id) { id = (0, resolve_1.normalizeId)(id); delete this.schemas[id]; delete this.refs[id]; } return this; } default: throw new Error("ajv.removeSchema: invalid parameter"); } } // add "vocabulary" - a collection of keywords addVocabulary(definitions) { for (const def of definitions) this.addKeyword(def); return this; } addKeyword(kwdOrDef, def) { let keyword; if (typeof kwdOrDef == "string") { keyword = kwdOrDef; if (typeof def == "object") { this.logger.warn("these parameters are deprecated, see docs for addKeyword"); def.keyword = keyword; } } else if (typeof kwdOrDef == "object" && def === void 0) { def = kwdOrDef; keyword = def.keyword; if (Array.isArray(keyword) && !keyword.length) { throw new Error("addKeywords: keyword must be string or non-empty array"); } } else { throw new Error("invalid addKeywords parameters"); } checkKeyword.call(this, keyword, def); if (!def) { (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); return this; } keywordMetaschema.call(this, def); const definition = { ...def, type: (0, dataType_1.getJSONTypes)(def.type), schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) }; (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t4) => addRule.call(this, k, definition, t4))); return this; } getKeyword(keyword) { const rule = this.RULES.all[keyword]; return typeof rule == "object" ? rule.definition : !!rule; } // Remove keyword removeKeyword(keyword) { const { RULES } = this; delete RULES.keywords[keyword]; delete RULES.all[keyword]; for (const group of RULES.rules) { const i4 = group.rules.findIndex((rule) => rule.keyword === keyword); if (i4 >= 0) group.rules.splice(i4, 1); } return this; } // Add format addFormat(name24, format) { if (typeof format == "string") format = new RegExp(format); this.formats[name24] = format; return this; } errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { if (!errors || errors.length === 0) return "No errors"; return errors.map((e5) => `${dataVar}${e5.instancePath} ${e5.message}`).reduce((text2, msg) => text2 + separator + msg); } $dataMetaSchema(metaSchema, keywordsJsonPointers) { const rules = this.RULES.all; metaSchema = JSON.parse(JSON.stringify(metaSchema)); for (const jsonPointer of keywordsJsonPointers) { const segments = jsonPointer.split("/").slice(1); let keywords = metaSchema; for (const seg of segments) keywords = keywords[seg]; for (const key in rules) { const rule = rules[key]; if (typeof rule != "object") continue; const { $data } = rule.definition; const schema = keywords[key]; if ($data && schema) keywords[key] = schemaOrData(schema); } } return metaSchema; } _removeAllSchemas(schemas, regex) { for (const keyRef in schemas) { const sch = schemas[keyRef]; if (!regex || regex.test(keyRef)) { if (typeof sch == "string") { delete schemas[keyRef]; } else if (sch && !sch.meta) { this._cache.delete(sch.schema); delete schemas[keyRef]; } } } } _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { let id; const { schemaId } = this.opts; if (typeof schema == "object") { id = schema[schemaId]; } else { if (this.opts.jtd) throw new Error("schema must be object"); else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); } let sch = this._cache.get(schema); if (sch !== void 0) return sch; baseId = (0, resolve_1.normalizeId)(id || baseId); const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); this._cache.set(sch.schema, sch); if (addSchema && !baseId.startsWith("#")) { if (baseId) this._checkUnique(baseId); this.refs[baseId] = sch; } if (validateSchema) this.validateSchema(schema, true); return sch; } _checkUnique(id) { if (this.schemas[id] || this.refs[id]) { throw new Error(`schema with key or id "${id}" already exists`); } } _compileSchemaEnv(sch) { if (sch.meta) this._compileMetaSchema(sch); else compile_1.compileSchema.call(this, sch); if (!sch.validate) throw new Error("ajv implementation error"); return sch.validate; } _compileMetaSchema(sch) { const currentOpts = this.opts; this.opts = this._metaOpts; try { compile_1.compileSchema.call(this, sch); } finally { this.opts = currentOpts; } } }; Ajv2.ValidationError = validation_error_1.default; Ajv2.MissingRefError = ref_error_1.default; exports.default = Ajv2; function checkOptions(checkOpts, options, msg, log = "error") { for (const key in checkOpts) { const opt = key; if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); } } function getSchEnv(keyRef) { keyRef = (0, resolve_1.normalizeId)(keyRef); return this.schemas[keyRef] || this.refs[keyRef]; } function addInitialSchemas() { const optsSchemas = this.opts.schemas; if (!optsSchemas) return; if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); } function addInitialFormats() { for (const name24 in this.opts.formats) { const format = this.opts.formats[name24]; if (format) this.addFormat(name24, format); } } function addInitialKeywords(defs) { if (Array.isArray(defs)) { this.addVocabulary(defs); return; } this.logger.warn("keywords option as map is deprecated, pass array"); for (const keyword in defs) { const def = defs[keyword]; if (!def.keyword) def.keyword = keyword; this.addKeyword(def); } } function getMetaSchemaOptions() { const metaOpts = { ...this.opts }; for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; return metaOpts; } var noLogs = { log() { }, warn() { }, error() { } }; function getLogger(logger) { if (logger === false) return noLogs; if (logger === void 0) return console; if (logger.log && logger.warn && logger.error) return logger; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; function checkKeyword(keyword, def) { const { RULES } = this; (0, util_1.eachItem)(keyword, (kwd) => { if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); }); if (!def) return; if (def.$data && !("code" in def || "validate" in def)) { throw new Error('$data keyword must have "code" or "validate" function'); } } function addRule(keyword, definition, dataType) { var _a25; const post = definition === null || definition === void 0 ? void 0 : definition.post; if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"'); const { RULES } = this; let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t4 }) => t4 === dataType); if (!ruleGroup) { ruleGroup = { type: dataType, rules: [] }; RULES.rules.push(ruleGroup); } RULES.keywords[keyword] = true; if (!definition) return; const rule = { keyword, definition: { ...definition, type: (0, dataType_1.getJSONTypes)(definition.type), schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) } }; if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); else ruleGroup.rules.push(rule); RULES.all[keyword] = rule; (_a25 = definition.implements) === null || _a25 === void 0 ? void 0 : _a25.forEach((kwd) => this.addKeyword(kwd)); } function addBeforeRule(ruleGroup, rule, before) { const i4 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); if (i4 >= 0) { ruleGroup.rules.splice(i4, 0, rule); } else { ruleGroup.rules.push(rule); this.logger.warn(`rule ${before} is not defined`); } } function keywordMetaschema(def) { let { metaSchema } = def; if (metaSchema === void 0) return; if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); def.validateSchema = this.compile(metaSchema, true); } var $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; function schemaOrData(schema) { return { anyOf: [schema, $dataRef] }; } } }); // node_modules/ajv/dist/vocabularies/core/id.js var require_id = __commonJS({ "node_modules/ajv/dist/vocabularies/core/id.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var def = { keyword: "id", code() { throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/core/ref.js var require_ref = __commonJS({ "node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.callRef = exports.getValidate = void 0; var ref_error_1 = require_ref_error(); var code_1 = require_code2(); var codegen_1 = require_codegen(); var names_1 = require_names(); var compile_1 = require_compile(); var util_1 = require_util(); var def = { keyword: "$ref", schemaType: "string", code(cxt) { const { gen, schema: $ref, it: it2 } = cxt; const { baseId, schemaEnv: env, validateName, opts, self } = it2; const { root } = env; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); if (schOrEnv === void 0) throw new ref_error_1.default(it2.opts.uriResolver, baseId, $ref); if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { if (env === root) return callRef(cxt, validateName, env, env.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } function callValidate(sch) { const v2 = getValidate(cxt, sch); callRef(cxt, v2, sch, sch.$async); } function inlineRefSchema(sch) { const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); const valid = gen.name("valid"); const schCxt = cxt.subschema({ schema: sch, dataTypes: [], schemaPath: codegen_1.nil, topSchemaRef: schName, errSchemaPath: $ref }, valid); cxt.mergeEvaluated(schCxt); cxt.ok(valid); } } }; function getValidate(cxt, sch) { const { gen } = cxt; return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; } exports.getValidate = getValidate; function callRef(cxt, v2, sch, $async) { const { gen, it: it2 } = cxt; const { allErrors, schemaEnv: env, opts } = it2; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { if (!env.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v2, passCxt)}`); addEvaluatedFrom(v2); if (!allErrors) gen.assign(valid, true); }, (e5) => { gen.if((0, codegen_1._)`!(${e5} instanceof ${it2.ValidationError})`, () => gen.throw(e5)); addErrorsFrom(e5); if (!allErrors) gen.assign(valid, false); }); cxt.ok(valid); } function callSyncRef() { cxt.result((0, code_1.callValidateCode)(cxt, v2, passCxt), () => addEvaluatedFrom(v2), () => addErrorsFrom(v2)); } function addErrorsFrom(source) { const errs = (0, codegen_1._)`${source}.errors`; gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); } function addEvaluatedFrom(source) { var _a25; if (!it2.opts.unevaluated) return; const schEvaluated = (_a25 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a25 === void 0 ? void 0 : _a25.evaluated; if (it2.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== void 0) { it2.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it2.props); } } else { const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); it2.props = util_1.mergeEvaluated.props(gen, props, it2.props, codegen_1.Name); } } if (it2.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== void 0) { it2.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it2.items); } } else { const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); it2.items = util_1.mergeEvaluated.items(gen, items, it2.items, codegen_1.Name); } } } } exports.callRef = callRef; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/core/index.js var require_core2 = __commonJS({ "node_modules/ajv/dist/vocabularies/core/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var id_1 = require_id(); var ref_1 = require_ref(); var core = [ "$schema", "$id", "$defs", "$vocabulary", { keyword: "$comment" }, "definitions", id_1.default, ref_1.default ]; exports.default = core; } }); // node_modules/ajv/dist/vocabularies/validation/limitNumber.js var require_limitNumber = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var ops = codegen_1.operators; var KWDs = { maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error40 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; var def = { keyword: Object.keys(KWDs), type: "number", schemaType: "number", $data: true, error: error40, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/multipleOf.js var require_multipleOf = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error40 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; var def = { keyword: "multipleOf", type: "number", schemaType: "number", $data: true, error: error40, code(cxt) { const { gen, data, schemaCode, it: it2 } = cxt; const prec = it2.opts.multipleOfPrecision; const res = gen.let("res"); const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); } }; exports.default = def; } }); // node_modules/ajv/dist/runtime/ucs2length.js var require_ucs2length = __commonJS({ "node_modules/ajv/dist/runtime/ucs2length.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function ucs2length(str) { const len = str.length; let length = 0; let pos = 0; let value; while (pos < len) { length++; value = str.charCodeAt(pos++); if (value >= 55296 && value <= 56319 && pos < len) { value = str.charCodeAt(pos); if ((value & 64512) === 56320) pos++; } } return length; } exports.default = ucs2length; ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; } }); // node_modules/ajv/dist/vocabularies/validation/limitLength.js var require_limitLength = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var ucs2length_1 = require_ucs2length(); var error40 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxLength", "minLength"], type: "string", schemaType: "number", $data: true, error: error40, code(cxt) { const { keyword, data, schemaCode, it: it2 } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; const len = it2.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/pattern.js var require_pattern = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code2(); var util_1 = require_util(); var codegen_1 = require_codegen(); var error40 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; var def = { keyword: "pattern", type: "string", schemaType: "string", $data: true, error: error40, code(cxt) { const { gen, data, $data, schema, schemaCode, it: it2 } = cxt; const u2 = it2.opts.unicodeRegExp ? "u" : ""; if ($data) { const { regExp } = it2.opts.code; const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); const valid = gen.let("valid"); gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u2}).test(${data})`), () => gen.assign(valid, false)); cxt.fail$data((0, codegen_1._)`!${valid}`); } else { const regExp = (0, code_1.usePattern)(cxt, schema); cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); } } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/limitProperties.js var require_limitProperties = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error40 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxProperties", "minProperties"], type: "object", schemaType: "number", $data: true, error: error40, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/required.js var require_required = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); var error40 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; var def = { keyword: "required", type: "object", schemaType: "array", $data: true, error: error40, code(cxt) { const { gen, schema, schemaCode, data, $data, it: it2 } = cxt; const { opts } = it2; if (!$data && schema.length === 0) return; const useLoop = schema.length >= opts.loopRequired; if (it2.allErrors) allErrorsMode(); else exitOnErrorMode(); if (opts.strictRequired) { const props = cxt.parentSchema.properties; const { definedProperties } = cxt.it; for (const requiredKey of schema) { if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath; const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictRequired); } } } function allErrorsMode() { if (useLoop || $data) { cxt.block$data(codegen_1.nil, loopAllRequired); } else { for (const prop of schema) { (0, code_1.checkReportMissingProp)(cxt, prop); } } } function exitOnErrorMode() { const missing = gen.let("missing"); if (useLoop || $data) { const valid = gen.let("valid", true); cxt.block$data(valid, () => loopUntilMissing(missing, valid)); cxt.ok(valid); } else { gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } function loopAllRequired() { gen.forOf("prop", schemaCode, (prop) => { cxt.setParams({ missingProperty: prop }); gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); }); } function loopUntilMissing(missing, valid) { cxt.setParams({ missingProperty: missing }); gen.forOf(missing, schemaCode, () => { gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); gen.if((0, codegen_1.not)(valid), () => { cxt.error(); gen.break(); }); }, codegen_1.nil); } } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/limitItems.js var require_limitItems = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error40 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxItems", "minItems"], type: "array", schemaType: "number", $data: true, error: error40, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); } }; exports.default = def; } }); // node_modules/ajv/dist/runtime/equal.js var require_equal = __commonJS({ "node_modules/ajv/dist/runtime/equal.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var equal2 = require_fast_deep_equal(); equal2.code = 'require("ajv/dist/runtime/equal").default'; exports.default = equal2; } }); // node_modules/ajv/dist/vocabularies/validation/uniqueItems.js var require_uniqueItems = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var dataType_1 = require_dataType(); var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); var error40 = { message: ({ params: { i: i4, j: j2 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j2} and ${i4} are identical)`, params: ({ params: { i: i4, j: j2 } }) => (0, codegen_1._)`{i: ${i4}, j: ${j2}}` }; var def = { keyword: "uniqueItems", type: "array", schemaType: "boolean", $data: true, error: error40, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it: it2 } = cxt; if (!$data && !schema) return; const valid = gen.let("valid"); const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); cxt.ok(valid); function validateUniqueItems() { const i4 = gen.let("i", (0, codegen_1._)`${data}.length`); const j2 = gen.let("j"); cxt.setParams({ i: i4, j: j2 }); gen.assign(valid, true); gen.if((0, codegen_1._)`${i4} > 1`, () => (canOptimize() ? loopN : loopN2)(i4, j2)); } function canOptimize() { return itemTypes.length > 0 && !itemTypes.some((t4) => t4 === "object" || t4 === "array"); } function loopN(i4, j2) { const item = gen.name("item"); const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it2.opts.strictNumbers, dataType_1.DataType.Wrong); const indices = gen.const("indices", (0, codegen_1._)`{}`); gen.for((0, codegen_1._)`;${i4}--;`, () => { gen.let(item, (0, codegen_1._)`${data}[${i4}]`); gen.if(wrongType, (0, codegen_1._)`continue`); if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { gen.assign(j2, (0, codegen_1._)`${indices}[${item}]`); cxt.error(); gen.assign(valid, false).break(); }).code((0, codegen_1._)`${indices}[${item}] = ${i4}`); }); } function loopN2(i4, j2) { const eql = (0, util_1.useFunc)(gen, equal_1.default); const outer = gen.name("outer"); gen.label(outer).for((0, codegen_1._)`;${i4}--;`, () => gen.for((0, codegen_1._)`${j2} = ${i4}; ${j2}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i4}], ${data}[${j2}])`, () => { cxt.error(); gen.assign(valid, false).break(outer); }))); } } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/const.js var require_const = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); var error40 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, error: error40, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); } else { cxt.fail((0, codegen_1._)`${schema} !== ${data}`); } } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/enum.js var require_enum = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var equal_1 = require_equal(); var error40 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", $data: true, error: error40, code(cxt) { const { gen, data, $data, schema, schemaCode, it: it2 } = cxt; if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); const useLoop = schema.length >= it2.opts.loopEnum; let eql; const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); let valid; if (useLoop || $data) { valid = gen.let("valid"); cxt.block$data(valid, loopEnum); } else { if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const vSchema = gen.const("vSchema", schemaCode); valid = (0, codegen_1.or)(...schema.map((_x, i4) => equalCode(vSchema, i4))); } cxt.pass(valid); function loopEnum() { gen.assign(valid, false); gen.forOf("v", schemaCode, (v2) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v2})`, () => gen.assign(valid, true).break())); } function equalCode(vSchema, i4) { const sch = schema[i4]; return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i4}])` : (0, codegen_1._)`${data} === ${sch}`; } } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/validation/index.js var require_validation = __commonJS({ "node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var limitNumber_1 = require_limitNumber(); var multipleOf_1 = require_multipleOf(); var limitLength_1 = require_limitLength(); var pattern_1 = require_pattern(); var limitProperties_1 = require_limitProperties(); var required_1 = require_required(); var limitItems_1 = require_limitItems(); var uniqueItems_1 = require_uniqueItems(); var const_1 = require_const(); var enum_1 = require_enum(); var validation = [ // number limitNumber_1.default, multipleOf_1.default, // string limitLength_1.default, pattern_1.default, // object limitProperties_1.default, required_1.default, // array limitItems_1.default, uniqueItems_1.default, // any { keyword: "type", schemaType: ["string", "array"] }, { keyword: "nullable", schemaType: "boolean" }, const_1.default, enum_1.default ]; exports.default = validation; } }); // node_modules/ajv/dist/vocabularies/applicator/additionalItems.js var require_additionalItems = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var error40 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "additionalItems", type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", error: error40, code(cxt) { const { parentSchema, it: it2 } = cxt; const { items } = parentSchema; if (!Array.isArray(items)) { (0, util_1.checkStrictMode)(it2, '"additionalItems" is ignored when "items" is not an array of schemas'); return; } validateAdditionalItems(cxt, items); } }; function validateAdditionalItems(cxt, items) { const { gen, schema, data, keyword, it: it2 } = cxt; it2.items = true; const len = gen.const("len", (0, codegen_1._)`${data}.length`); if (schema === false) { cxt.setParams({ len: items.length }); cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it2, schema)) { const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); cxt.ok(valid); } function validateItems(valid) { gen.forRange("i", items.length, len, (i4) => { cxt.subschema({ keyword, dataProp: i4, dataPropType: util_1.Type.Num }, valid); if (!it2.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); }); } } exports.validateAdditionalItems = validateAdditionalItems; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/items.js var require_items = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateTuple = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var code_1 = require_code2(); var def = { keyword: "items", type: "array", schemaType: ["object", "array", "boolean"], before: "uniqueItems", code(cxt) { const { schema, it: it2 } = cxt; if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); it2.items = true; if ((0, util_1.alwaysValidSchema)(it2, schema)) return; cxt.ok((0, code_1.validateArray)(cxt)); } }; function validateTuple(cxt, extraItems, schArr = cxt.schema) { const { gen, parentSchema, data, keyword, it: it2 } = cxt; checkStrictTuple(parentSchema); if (it2.opts.unevaluated && schArr.length && it2.items !== true) { it2.items = util_1.mergeEvaluated.items(gen, schArr.length, it2.items); } const valid = gen.name("valid"); const len = gen.const("len", (0, codegen_1._)`${data}.length`); schArr.forEach((sch, i4) => { if ((0, util_1.alwaysValidSchema)(it2, sch)) return; gen.if((0, codegen_1._)`${len} > ${i4}`, () => cxt.subschema({ keyword, schemaProp: i4, dataProp: i4 }, valid)); cxt.ok(valid); }); function checkStrictTuple(sch) { const { opts, errSchemaPath } = it2; const l13 = schArr.length; const fullTuple = l13 === sch.minItems && (l13 === sch.maxItems || sch[extraItems] === false); if (opts.strictTuples && !fullTuple) { const msg = `"${keyword}" is ${l13}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; (0, util_1.checkStrictMode)(it2, msg, opts.strictTuples); } } } exports.validateTuple = validateTuple; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/prefixItems.js var require_prefixItems = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var items_1 = require_items(); var def = { keyword: "prefixItems", type: "array", schemaType: ["array"], before: "uniqueItems", code: (cxt) => (0, items_1.validateTuple)(cxt, "items") }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/items2020.js var require_items2020 = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); var error40 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "items", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", error: error40, code(cxt) { const { schema, parentSchema, it: it2 } = cxt; const { prefixItems } = parentSchema; it2.items = true; if ((0, util_1.alwaysValidSchema)(it2, schema)) return; if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); else cxt.ok((0, code_1.validateArray)(cxt)); } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/contains.js var require_contains = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var error40 = { message: ({ params: { min, max: max2 } }) => max2 === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max2} valid item(s)`, params: ({ params: { min, max: max2 } }) => max2 === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max2}}` }; var def = { keyword: "contains", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, error: error40, code(cxt) { const { gen, schema, parentSchema, data, it: it2 } = cxt; let min; let max2; const { minContains, maxContains } = parentSchema; if (it2.opts.next) { min = minContains === void 0 ? 1 : minContains; max2 = maxContains; } else { min = 1; } const len = gen.const("len", (0, codegen_1._)`${data}.length`); cxt.setParams({ min, max: max2 }); if (max2 === void 0 && min === 0) { (0, util_1.checkStrictMode)(it2, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); return; } if (max2 !== void 0 && min > max2) { (0, util_1.checkStrictMode)(it2, `"minContains" > "maxContains" is always invalid`); cxt.fail(); return; } if ((0, util_1.alwaysValidSchema)(it2, schema)) { let cond = (0, codegen_1._)`${len} >= ${min}`; if (max2 !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max2}`; cxt.pass(cond); return; } it2.items = true; const valid = gen.name("valid"); if (max2 === void 0 && min === 1) { validateItems(valid, () => gen.if(valid, () => gen.break())); } else if (min === 0) { gen.let(valid, true); if (max2 !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); } else { gen.let(valid, false); validateItemsWithCount(); } cxt.result(valid, () => cxt.reset()); function validateItemsWithCount() { const schValid = gen.name("_valid"); const count = gen.let("count", 0); validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); } function validateItems(_valid, block) { gen.forRange("i", 0, len, (i4) => { cxt.subschema({ keyword: "contains", dataProp: i4, dataPropType: util_1.Type.Num, compositeRule: true }, _valid); block(); }); } function checkLimits(count) { gen.code((0, codegen_1._)`${count}++`); if (max2 === void 0) { gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); } else { gen.if((0, codegen_1._)`${count} > ${max2}`, () => gen.assign(valid, false).break()); if (min === 1) gen.assign(valid, true); else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); } } } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/dependencies.js var require_dependencies = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; var codegen_1 = require_codegen(); var util_1 = require_util(); var code_1 = require_code2(); exports.error = { message: ({ params: { property, depsCount, deps } }) => { const property_ies = depsCount === 1 ? "property" : "properties"; return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; }, params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, missingProperty: ${missingProperty}, depsCount: ${depsCount}, deps: ${deps}}` // TODO change to reference }; var def = { keyword: "dependencies", type: "object", schemaType: "object", error: exports.error, code(cxt) { const [propDeps, schDeps] = splitDependencies(cxt); validatePropertyDeps(cxt, propDeps); validateSchemaDeps(cxt, schDeps); } }; function splitDependencies({ schema }) { const propertyDeps = {}; const schemaDeps = {}; for (const key in schema) { if (key === "__proto__") continue; const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; deps[key] = schema[key]; } return [propertyDeps, schemaDeps]; } function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { const { gen, data, it: it2 } = cxt; if (Object.keys(propertyDeps).length === 0) return; const missing = gen.let("missing"); for (const prop in propertyDeps) { const deps = propertyDeps[prop]; if (deps.length === 0) continue; const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it2.opts.ownProperties); cxt.setParams({ property: prop, depsCount: deps.length, deps: deps.join(", ") }); if (it2.allErrors) { gen.if(hasProperty, () => { for (const depProp of deps) { (0, code_1.checkReportMissingProp)(cxt, depProp); } }); } else { gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } } exports.validatePropertyDeps = validatePropertyDeps; function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { const { gen, data, keyword, it: it2 } = cxt; const valid = gen.name("valid"); for (const prop in schemaDeps) { if ((0, util_1.alwaysValidSchema)(it2, schemaDeps[prop])) continue; gen.if( (0, code_1.propertyInData)(gen, data, prop, it2.opts.ownProperties), () => { const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); cxt.mergeValidEvaluated(schCxt, valid); }, () => gen.var(valid, true) // TODO var ); cxt.ok(valid); } } exports.validateSchemaDeps = validateSchemaDeps; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/propertyNames.js var require_propertyNames = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var error40 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; var def = { keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], error: error40, code(cxt) { const { gen, schema, data, it: it2 } = cxt; if ((0, util_1.alwaysValidSchema)(it2, schema)) return; const valid = gen.name("valid"); gen.forIn("key", data, (key) => { cxt.setParams({ propertyName: key }); cxt.subschema({ keyword: "propertyNames", data: key, dataTypes: ["string"], propertyName: key, compositeRule: true }, valid); gen.if((0, codegen_1.not)(valid), () => { cxt.error(true); if (!it2.allErrors) gen.break(); }); }); cxt.ok(valid); } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js var require_additionalProperties = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util(); var error40 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; var def = { keyword: "additionalProperties", type: ["object"], schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, error: error40, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it: it2 } = cxt; if (!errsCount) throw new Error("ajv implementation error"); const { allErrors, opts } = it2; it2.props = true; if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it2, schema)) return; const props = (0, code_1.allSchemaProperties)(parentSchema.properties); const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); checkAdditionalProperties(); cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); function checkAdditionalProperties() { gen.forIn("key", data, (key) => { if (!props.length && !patProps.length) additionalPropertyCode(key); else gen.if(isAdditional(key), () => additionalPropertyCode(key)); }); } function isAdditional(key) { let definedProp; if (props.length > 8) { const propsSchema = (0, util_1.schemaRefOrVal)(it2, parentSchema.properties, "properties"); definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); } else if (props.length) { definedProp = (0, codegen_1.or)(...props.map((p2) => (0, codegen_1._)`${key} === ${p2}`)); } else { definedProp = codegen_1.nil; } if (patProps.length) { definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p2) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p2)}.test(${key})`)); } return (0, codegen_1.not)(definedProp); } function deleteAdditional(key) { gen.code((0, codegen_1._)`delete ${data}[${key}]`); } function additionalPropertyCode(key) { if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { deleteAdditional(key); return; } if (schema === false) { cxt.setParams({ additionalProperty: key }); cxt.error(); if (!allErrors) gen.break(); return; } if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it2, schema)) { const valid = gen.name("valid"); if (opts.removeAdditional === "failing") { applyAdditionalSchema(key, valid, false); gen.if((0, codegen_1.not)(valid), () => { cxt.reset(); deleteAdditional(key); }); } else { applyAdditionalSchema(key, valid); if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); } } } function applyAdditionalSchema(key, valid, errors) { const subschema = { keyword: "additionalProperties", dataProp: key, dataPropType: util_1.Type.Str }; if (errors === false) { Object.assign(subschema, { compositeRule: true, createErrors: false, allErrors: false }); } cxt.subschema(subschema, valid); } } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/properties.js var require_properties = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var validate_1 = require_validate(); var code_1 = require_code2(); var util_1 = require_util(); var additionalProperties_1 = require_additionalProperties(); var def = { keyword: "properties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, parentSchema, data, it: it2 } = cxt; if (it2.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { additionalProperties_1.default.code(new validate_1.KeywordCxt(it2, additionalProperties_1.default, "additionalProperties")); } const allProps = (0, code_1.allSchemaProperties)(schema); for (const prop of allProps) { it2.definedProperties.add(prop); } if (it2.opts.unevaluated && allProps.length && it2.props !== true) { it2.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it2.props); } const properties = allProps.filter((p2) => !(0, util_1.alwaysValidSchema)(it2, schema[p2])); if (properties.length === 0) return; const valid = gen.name("valid"); for (const prop of properties) { if (hasDefault(prop)) { applyPropertySchema(prop); } else { gen.if((0, code_1.propertyInData)(gen, data, prop, it2.opts.ownProperties)); applyPropertySchema(prop); if (!it2.allErrors) gen.else().var(valid, true); gen.endIf(); } cxt.it.definedProperties.add(prop); cxt.ok(valid); } function hasDefault(prop) { return it2.opts.useDefaults && !it2.compositeRule && schema[prop].default !== void 0; } function applyPropertySchema(prop) { cxt.subschema({ keyword: "properties", schemaProp: prop, dataProp: prop }, valid); } } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/patternProperties.js var require_patternProperties = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util(); var util_2 = require_util(); var def = { keyword: "patternProperties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, data, parentSchema, it: it2 } = cxt; const { opts } = it2; const patterns = (0, code_1.allSchemaProperties)(schema); const alwaysValidPatterns = patterns.filter((p2) => (0, util_1.alwaysValidSchema)(it2, schema[p2])); if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it2.opts.unevaluated || it2.props === true)) { return; } const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; const valid = gen.name("valid"); if (it2.props !== true && !(it2.props instanceof codegen_1.Name)) { it2.props = (0, util_2.evaluatedPropsToName)(gen, it2.props); } const { props } = it2; validatePatternProperties(); function validatePatternProperties() { for (const pat of patterns) { if (checkProperties) checkMatchingProperties(pat); if (it2.allErrors) { validateProperties(pat); } else { gen.var(valid, true); validateProperties(pat); gen.if(valid); } } } function checkMatchingProperties(pat) { for (const prop in checkProperties) { if (new RegExp(pat).test(prop)) { (0, util_1.checkStrictMode)(it2, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); } } } function validateProperties(pat) { gen.forIn("key", data, (key) => { gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { const alwaysValid = alwaysValidPatterns.includes(pat); if (!alwaysValid) { cxt.subschema({ keyword: "patternProperties", schemaProp: pat, dataProp: key, dataPropType: util_2.Type.Str }, valid); } if (it2.opts.unevaluated && props !== true) { gen.assign((0, codegen_1._)`${props}[${key}]`, true); } else if (!alwaysValid && !it2.allErrors) { gen.if((0, codegen_1.not)(valid), () => gen.break()); } }); }); } } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/not.js var require_not = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util(); var def = { keyword: "not", schemaType: ["object", "boolean"], trackErrors: true, code(cxt) { const { gen, schema, it: it2 } = cxt; if ((0, util_1.alwaysValidSchema)(it2, schema)) { cxt.fail(); return; } const valid = gen.name("valid"); cxt.subschema({ keyword: "not", compositeRule: true, createErrors: false, allErrors: false }, valid); cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); }, error: { message: "must NOT be valid" } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/anyOf.js var require_anyOf = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require_code2(); var def = { keyword: "anyOf", schemaType: "array", trackErrors: true, code: code_1.validateUnion, error: { message: "must match a schema in anyOf" } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/oneOf.js var require_oneOf = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var error40 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; var def = { keyword: "oneOf", schemaType: "array", trackErrors: true, error: error40, code(cxt) { const { gen, schema, parentSchema, it: it2 } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); if (it2.opts.discriminator && parentSchema.discriminator) return; const schArr = schema; const valid = gen.let("valid", false); const passing = gen.let("passing", null); const schValid = gen.name("_valid"); cxt.setParams({ passing }); gen.block(validateOneOf); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); function validateOneOf() { schArr.forEach((sch, i4) => { let schCxt; if ((0, util_1.alwaysValidSchema)(it2, sch)) { gen.var(schValid, true); } else { schCxt = cxt.subschema({ keyword: "oneOf", schemaProp: i4, compositeRule: true }, schValid); } if (i4 > 0) { gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i4}]`).else(); } gen.if(schValid, () => { gen.assign(valid, true); gen.assign(passing, i4); if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); }); }); } } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/allOf.js var require_allOf = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util(); var def = { keyword: "allOf", schemaType: "array", code(cxt) { const { gen, schema, it: it2 } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const valid = gen.name("valid"); schema.forEach((sch, i4) => { if ((0, util_1.alwaysValidSchema)(it2, sch)) return; const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i4 }, valid); cxt.ok(valid); cxt.mergeEvaluated(schCxt); }); } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/if.js var require_if = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util(); var error40 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; var def = { keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, error: error40, code(cxt) { const { gen, parentSchema, it: it2 } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { (0, util_1.checkStrictMode)(it2, '"if" without "then" and "else" is ignored'); } const hasThen = hasSchema(it2, "then"); const hasElse = hasSchema(it2, "else"); if (!hasThen && !hasElse) return; const valid = gen.let("valid", true); const schValid = gen.name("_valid"); validateIf(); cxt.reset(); if (hasThen && hasElse) { const ifClause = gen.let("ifClause"); cxt.setParams({ ifClause }); gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); } else if (hasThen) { gen.if(schValid, validateClause("then")); } else { gen.if((0, codegen_1.not)(schValid), validateClause("else")); } cxt.pass(valid, () => cxt.error(true)); function validateIf() { const schCxt = cxt.subschema({ keyword: "if", compositeRule: true, createErrors: false, allErrors: false }, schValid); cxt.mergeEvaluated(schCxt); } function validateClause(keyword, ifClause) { return () => { const schCxt = cxt.subschema({ keyword }, schValid); gen.assign(valid, schValid); cxt.mergeValidEvaluated(schCxt, valid); if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); else cxt.setParams({ ifClause: keyword }); }; } } }; function hasSchema(it2, keyword) { const schema = it2.schema[keyword]; return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it2, schema); } exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/thenElse.js var require_thenElse = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util(); var def = { keyword: ["then", "else"], schemaType: ["object", "boolean"], code({ keyword, parentSchema, it: it2 }) { if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it2, `"${keyword}" without "if" is ignored`); } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/applicator/index.js var require_applicator = __commonJS({ "node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var additionalItems_1 = require_additionalItems(); var prefixItems_1 = require_prefixItems(); var items_1 = require_items(); var items2020_1 = require_items2020(); var contains_1 = require_contains(); var dependencies_1 = require_dependencies(); var propertyNames_1 = require_propertyNames(); var additionalProperties_1 = require_additionalProperties(); var properties_1 = require_properties(); var patternProperties_1 = require_patternProperties(); var not_1 = require_not(); var anyOf_1 = require_anyOf(); var oneOf_1 = require_oneOf(); var allOf_1 = require_allOf(); var if_1 = require_if(); var thenElse_1 = require_thenElse(); function getApplicator(draft2020 = false) { const applicator = [ // any not_1.default, anyOf_1.default, oneOf_1.default, allOf_1.default, if_1.default, thenElse_1.default, // object propertyNames_1.default, additionalProperties_1.default, dependencies_1.default, properties_1.default, patternProperties_1.default ]; if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); else applicator.push(additionalItems_1.default, items_1.default); applicator.push(contains_1.default); return applicator; } exports.default = getApplicator; } }); // node_modules/ajv/dist/vocabularies/format/format.js var require_format = __commonJS({ "node_modules/ajv/dist/vocabularies/format/format.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error40 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; var def = { keyword: "format", type: ["number", "string"], schemaType: "string", $data: true, error: error40, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it: it2 } = cxt; const { opts, errSchemaPath, schemaEnv, self } = it2; if (!opts.validateFormats) return; if ($data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats }); const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); const fType = gen.let("fType"); const format = gen.let("format"); gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); function unknownFmt() { if (opts.strictSchema === false) return codegen_1.nil; return (0, codegen_1._)`${schemaCode} && !${format}`; } function invalidFmt() { const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; } } function validateFormat() { const formatDef = self.formats[schema]; if (!formatDef) { unknownFormat(); return; } if (formatDef === true) return; const [fmtType, format, fmtRef] = getFormat(formatDef); if (fmtType === ruleType) cxt.pass(validCondition()); function unknownFormat() { if (opts.strictSchema === false) { self.logger.warn(unknownMsg()); return; } throw new Error(unknownMsg()); function unknownMsg() { return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; } } function getFormat(fmtDef) { const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; const fmt2 = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt2}.validate`]; } return ["string", fmtDef, fmt2]; } function validCondition() { if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { if (!schemaEnv.$async) throw new Error("async format in sync schema"); return (0, codegen_1._)`await ${fmtRef}(${data})`; } return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; } } } }; exports.default = def; } }); // node_modules/ajv/dist/vocabularies/format/index.js var require_format2 = __commonJS({ "node_modules/ajv/dist/vocabularies/format/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var format_1 = require_format(); var format = [format_1.default]; exports.default = format; } }); // node_modules/ajv/dist/vocabularies/metadata.js var require_metadata = __commonJS({ "node_modules/ajv/dist/vocabularies/metadata.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.contentVocabulary = exports.metadataVocabulary = void 0; exports.metadataVocabulary = [ "title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples" ]; exports.contentVocabulary = [ "contentMediaType", "contentEncoding", "contentSchema" ]; } }); // node_modules/ajv/dist/vocabularies/draft7.js var require_draft7 = __commonJS({ "node_modules/ajv/dist/vocabularies/draft7.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require_core2(); var validation_1 = require_validation(); var applicator_1 = require_applicator(); var format_1 = require_format2(); var metadata_1 = require_metadata(); var draft7Vocabularies = [ core_1.default, validation_1.default, (0, applicator_1.default)(), format_1.default, metadata_1.metadataVocabulary, metadata_1.contentVocabulary ]; exports.default = draft7Vocabularies; } }); // node_modules/ajv/dist/vocabularies/discriminator/types.js var require_types = __commonJS({ "node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DiscrError = void 0; var DiscrError; (function(DiscrError2) { DiscrError2["Tag"] = "tag"; DiscrError2["Mapping"] = "mapping"; })(DiscrError || (exports.DiscrError = DiscrError = {})); } }); // node_modules/ajv/dist/vocabularies/discriminator/index.js var require_discriminator = __commonJS({ "node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var types_1 = require_types(); var compile_1 = require_compile(); var ref_error_1 = require_ref_error(); var util_1 = require_util(); var error40 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` }; var def = { keyword: "discriminator", type: "object", schemaType: "object", error: error40, code(cxt) { const { gen, data, schema, parentSchema, it: it2 } = cxt; const { oneOf } = parentSchema; if (!it2.opts.discriminator) { throw new Error("discriminator: requires discriminator option"); } const tagName = schema.propertyName; if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); if (schema.mapping) throw new Error("discriminator: mapping is not supported"); if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); const valid = gen.let("valid", false); const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); cxt.ok(valid); function validateMapping() { const mapping = getMapping(); gen.if(false); for (const tagValue in mapping) { gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); gen.assign(valid, applyTagSchema(mapping[tagValue])); } gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); gen.endIf(); } function applyTagSchema(schemaProp) { const _valid = gen.name("valid"); const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); cxt.mergeEvaluated(schCxt, codegen_1.Name); return _valid; } function getMapping() { var _a25; const oneOfMapping = {}; const topRequired = hasRequired(parentSchema); let tagRequired = true; for (let i4 = 0; i4 < oneOf.length; i4++) { let sch = oneOf[i4]; if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it2.self.RULES)) { const ref = sch.$ref; sch = compile_1.resolveRef.call(it2.self, it2.schemaEnv.root, it2.baseId, ref); if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; if (sch === void 0) throw new ref_error_1.default(it2.opts.uriResolver, it2.baseId, ref); } const propSch = (_a25 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a25 === void 0 ? void 0 : _a25[tagName]; if (typeof propSch != "object") { throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); } tagRequired = tagRequired && (topRequired || hasRequired(sch)); addMappings(propSch, i4); } if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); return oneOfMapping; function hasRequired({ required: required2 }) { return Array.isArray(required2) && required2.includes(tagName); } function addMappings(sch, i4) { if (sch.const) { addMapping(sch.const, i4); } else if (sch.enum) { for (const tagValue of sch.enum) { addMapping(tagValue, i4); } } else { throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); } } function addMapping(tagValue, i4) { if (typeof tagValue != "string" || tagValue in oneOfMapping) { throw new Error(`discriminator: "${tagName}" values must be unique strings`); } oneOfMapping[tagValue] = i4; } } } }; exports.default = def; } }); // node_modules/ajv/dist/refs/json-schema-draft-07.json var require_json_schema_draft_07 = __commonJS({ "node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) { module.exports = { $schema: "http://json-schema.org/draft-07/schema#", $id: "http://json-schema.org/draft-07/schema#", title: "Core schema meta-schema", definitions: { schemaArray: { type: "array", minItems: 1, items: { $ref: "#" } }, nonNegativeInteger: { type: "integer", minimum: 0 }, nonNegativeIntegerDefault0: { allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] }, simpleTypes: { enum: ["array", "boolean", "integer", "null", "number", "object", "string"] }, stringArray: { type: "array", items: { type: "string" }, uniqueItems: true, default: [] } }, type: ["object", "boolean"], properties: { $id: { type: "string", format: "uri-reference" }, $schema: { type: "string", format: "uri" }, $ref: { type: "string", format: "uri-reference" }, $comment: { type: "string" }, title: { type: "string" }, description: { type: "string" }, default: true, readOnly: { type: "boolean", default: false }, examples: { type: "array", items: true }, multipleOf: { type: "number", exclusiveMinimum: 0 }, maximum: { type: "number" }, exclusiveMaximum: { type: "number" }, minimum: { type: "number" }, exclusiveMinimum: { type: "number" }, maxLength: { $ref: "#/definitions/nonNegativeInteger" }, minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, pattern: { type: "string", format: "regex" }, additionalItems: { $ref: "#" }, items: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], default: true }, maxItems: { $ref: "#/definitions/nonNegativeInteger" }, minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, uniqueItems: { type: "boolean", default: false }, contains: { $ref: "#" }, maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, required: { $ref: "#/definitions/stringArray" }, additionalProperties: { $ref: "#" }, definitions: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, properties: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, patternProperties: { type: "object", additionalProperties: { $ref: "#" }, propertyNames: { format: "regex" }, default: {} }, dependencies: { type: "object", additionalProperties: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] } }, propertyNames: { $ref: "#" }, const: true, enum: { type: "array", items: true, minItems: 1, uniqueItems: true }, type: { anyOf: [ { $ref: "#/definitions/simpleTypes" }, { type: "array", items: { $ref: "#/definitions/simpleTypes" }, minItems: 1, uniqueItems: true } ] }, format: { type: "string" }, contentMediaType: { type: "string" }, contentEncoding: { type: "string" }, if: { $ref: "#" }, then: { $ref: "#" }, else: { $ref: "#" }, allOf: { $ref: "#/definitions/schemaArray" }, anyOf: { $ref: "#/definitions/schemaArray" }, oneOf: { $ref: "#/definitions/schemaArray" }, not: { $ref: "#" } }, default: true }; } }); // node_modules/ajv/dist/ajv.js var require_ajv = __commonJS({ "node_modules/ajv/dist/ajv.js"(exports, module) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; var core_1 = require_core(); var draft7_1 = require_draft7(); var discriminator_1 = require_discriminator(); var draft7MetaSchema = require_json_schema_draft_07(); var META_SUPPORT_DATA = ["/properties"]; var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; var Ajv2 = class extends core_1.default { _addVocabularies() { super._addVocabularies(); draft7_1.default.forEach((v2) => this.addVocabulary(v2)); if (this.opts.discriminator) this.addKeyword(discriminator_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); if (!this.opts.meta) return; const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; } defaultMeta() { return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); } }; exports.Ajv = Ajv2; module.exports = exports = Ajv2; module.exports.Ajv = Ajv2; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Ajv2; var validate_1 = require_validate(); Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen(); Object.defineProperty(exports, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error(); Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { return validation_error_1.default; } }); var ref_error_1 = require_ref_error(); Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { return ref_error_1.default; } }); } }); // node_modules/ajv-formats/dist/formats.js var require_formats = __commonJS({ "node_modules/ajv-formats/dist/formats.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; function fmtDef(validate, compare) { return { validate, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 date: fmtDef(date5, compareDate), // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 time: fmtDef(getTime(true), compareTime), "date-time": fmtDef(getDateTime(true), compareDateTime), "iso-time": fmtDef(getTime(), compareIsoTime), "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), // duration: https://tools.ietf.org/html/rfc3339#appendix-A duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, uri, "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, // uri-template: https://tools.ietf.org/html/rfc6570 "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, // For the source: https://gist.github.com/dperini/729294 // For test cases: https://mathiasbynens.be/demo/url-regex url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, regex, // uuid: http://tools.ietf.org/html/rfc4122 uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, // JSON-pointer: https://tools.ietf.org/html/rfc6901 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types // byte: https://github.com/miguelmota/is-base64 byte, // signed 32 bit integer int32: { type: "number", validate: validateInt32 }, // signed 64 bit integer int64: { type: "number", validate: validateInt64 }, // C-type float float: { type: "number", validate: validateNumber }, // C-type double double: { type: "number", validate: validateNumber }, // hint to the UI to hide input strings password: true, // unchecked string payload binary: true }; exports.fastFormats = { ...exports.fullFormats, date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, // email (sources from jsen validator): // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i }; exports.formatNames = Object.keys(exports.fullFormats); function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function date5(str) { const matches = DATE.exec(str); if (!matches) return false; const year = +matches[1]; const month = +matches[2]; const day = +matches[3]; return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); } function compareDate(d1, d2) { if (!(d1 && d2)) return void 0; if (d1 > d2) return 1; if (d1 < d2) return -1; return 0; } var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; function getTime(strictTimeZone) { return function time3(str) { const matches = TIME.exec(str); if (!matches) return false; const hr2 = +matches[1]; const min = +matches[2]; const sec = +matches[3]; const tz = matches[4]; const tzSign = matches[5] === "-" ? -1 : 1; const tzH = +(matches[6] || 0); const tzM = +(matches[7] || 0); if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; if (hr2 <= 23 && min <= 59 && sec < 60) return true; const utcMin = min - tzM * tzSign; const utcHr = hr2 - tzH * tzSign - (utcMin < 0 ? 1 : 0); return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; }; } function compareTime(s1, s2) { if (!(s1 && s2)) return void 0; const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); const t22 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); if (!(t1 && t22)) return void 0; return t1 - t22; } function compareIsoTime(t1, t22) { if (!(t1 && t22)) return void 0; const a1 = TIME.exec(t1); const a22 = TIME.exec(t22); if (!(a1 && a22)) return void 0; t1 = a1[1] + a1[2] + a1[3]; t22 = a22[1] + a22[2] + a22[3]; if (t1 > t22) return 1; if (t1 < t22) return -1; return 0; } var DATE_TIME_SEPARATOR = /t|\s/i; function getDateTime(strictTimeZone) { const time3 = getTime(strictTimeZone); return function date_time(str) { const dateTime = str.split(DATE_TIME_SEPARATOR); return dateTime.length === 2 && date5(dateTime[0]) && time3(dateTime[1]); }; } function compareDateTime(dt1, dt2) { if (!(dt1 && dt2)) return void 0; const d1 = new Date(dt1).valueOf(); const d2 = new Date(dt2).valueOf(); if (!(d1 && d2)) return void 0; return d1 - d2; } function compareIsoDateTime(dt1, dt2) { if (!(dt1 && dt2)) return void 0; const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); const [d2, t22] = dt2.split(DATE_TIME_SEPARATOR); const res = compareDate(d1, d2); if (res === void 0) return void 0; return res || compareTime(t1, t22); } var NOT_URI_FRAGMENT = /\/|:/; var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; function uri(str) { return NOT_URI_FRAGMENT.test(str) && URI.test(str); } var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; function byte(str) { BYTE.lastIndex = 0; return BYTE.test(str); } var MIN_INT32 = -(2 ** 31); var MAX_INT32 = 2 ** 31 - 1; function validateInt32(value) { return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; } function validateInt64(value) { return Number.isInteger(value); } function validateNumber() { return true; } var Z_ANCHOR = /[^\\]\\Z/; function regex(str) { if (Z_ANCHOR.test(str)) return false; try { new RegExp(str); return true; } catch (e5) { return false; } } } }); // node_modules/ajv-formats/dist/limit.js var require_limit = __commonJS({ "node_modules/ajv-formats/dist/limit.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatLimitDefinition = void 0; var ajv_1 = require_ajv(); var codegen_1 = require_codegen(); var ops = codegen_1.operators; var KWDs = { formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error40 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; exports.formatLimitDefinition = { keyword: Object.keys(KWDs), type: "string", schemaType: "string", $data: true, error: error40, code(cxt) { const { gen, data, schemaCode, keyword, it: it2 } = cxt; const { opts, self } = it2; if (!opts.validateFormats) return; const fCxt = new ajv_1.KeywordCxt(it2, self.RULES.all.format.definition, "format"); if (fCxt.$data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats }); const fmt2 = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt2} != "object"`, (0, codegen_1._)`${fmt2} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt2}.compare != "function"`, compareCode(fmt2))); } function validateFormat() { const format = fCxt.schema; const fmtDef = self.formats[format]; if (!fmtDef || fmtDef === true) return; if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); } const fmt2 = gen.scopeValue("formats", { key: format, ref: fmtDef, code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 }); cxt.fail$data(compareCode(fmt2)); } function compareCode(fmt2) { return (0, codegen_1._)`${fmt2}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; } }, dependencies: ["format"] }; var formatLimitPlugin = (ajv) => { ajv.addKeyword(exports.formatLimitDefinition); return ajv; }; exports.default = formatLimitPlugin; } }); // node_modules/ajv-formats/dist/index.js var require_dist2 = __commonJS({ "node_modules/ajv-formats/dist/index.js"(exports, module) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var formats_1 = require_formats(); var limit_1 = require_limit(); var codegen_1 = require_codegen(); var fullName = new codegen_1.Name("fullFormats"); var fastName = new codegen_1.Name("fastFormats"); var formatsPlugin = (ajv, opts = { keywords: true }) => { if (Array.isArray(opts)) { addFormats(ajv, opts, formats_1.fullFormats, fullName); return ajv; } const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; const list = opts.formats || formats_1.formatNames; addFormats(ajv, list, formats, exportName); if (opts.keywords) (0, limit_1.default)(ajv); return ajv; }; formatsPlugin.get = (name24, mode = "full") => { const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; const f2 = formats[name24]; if (!f2) throw new Error(`Unknown format "${name24}"`); return f2; }; function addFormats(ajv, list, fs2, exportName) { var _a25; var _b19; (_a25 = (_b19 = ajv.opts.code).formats) !== null && _a25 !== void 0 ? _a25 : _b19.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; for (const f2 of list) ajv.addFormat(f2, fs2[f2]); } module.exports = exports = formatsPlugin; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = formatsPlugin; } }); // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js import process2 from "node:process"; // node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, ZodArray: () => ZodArray, ZodBase64: () => ZodBase64, ZodBase64URL: () => ZodBase64URL, ZodBigInt: () => ZodBigInt, ZodBigIntFormat: () => ZodBigIntFormat, ZodBoolean: () => ZodBoolean, ZodCIDRv4: () => ZodCIDRv4, ZodCIDRv6: () => ZodCIDRv6, ZodCUID: () => ZodCUID, ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, ZodDefault: () => ZodDefault, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, ZodE164: () => ZodE164, ZodEmail: () => ZodEmail, ZodEmoji: () => ZodEmoji, ZodEnum: () => ZodEnum, ZodError: () => ZodError, ZodFile: () => ZodFile, ZodGUID: () => ZodGUID, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, ZodLazy: () => ZodLazy, ZodLiteral: () => ZodLiteral, 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, ZodRealError: () => ZodRealError, 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, _ZodString: () => _ZodString, _default: () => _default2, any: () => any, array: () => array, base64: () => base642, base64url: () => base64url2, bigint: () => bigint2, boolean: () => boolean2, catch: () => _catch2, check: () => check, cidrv4: () => cidrv42, cidrv6: () => cidrv62, clone: () => clone, coerce: () => coerce_exports, config: () => config, core: () => core_exports2, cuid: () => cuid3, cuid2: () => cuid22, custom: () => custom, date: () => date3, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, email: () => email2, emoji: () => emoji2, endsWith: () => _endsWith, enum: () => _enum2, file: () => file, flattenError: () => flattenError, float32: () => float32, float64: () => float64, formatError: () => formatError, function: () => _function, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, gte: () => _gte, guid: () => guid2, includes: () => _includes, instanceof: () => _instanceof, int: () => int, int32: () => int32, int64: () => int64, intersection: () => intersection, ipv4: () => ipv42, ipv6: () => ipv62, iso: () => iso_exports, json: () => json, jwt: () => jwt, keyof: () => keyof, ksuid: () => ksuid2, lazy: () => lazy, length: () => _length, literal: () => literal, locales: () => locales_exports, looseObject: () => looseObject, lowercase: () => _lowercase, lt: () => _lt, lte: () => _lte, map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, mime: () => _mime, minLength: () => _minLength, minSize: () => _minSize, multipleOf: () => _multipleOf, nan: () => nan, nanoid: () => nanoid2, nativeEnum: () => nativeEnum, negative: () => _negative, never: () => never, nonnegative: () => _nonnegative, nonoptional: () => nonoptional, nonpositive: () => _nonpositive, normalize: () => _normalize, null: () => _null3, nullable: () => nullable, nullish: () => nullish2, number: () => number2, object: () => object, optional: () => optional, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, partialRecord: () => partialRecord, pipe: () => pipe, positive: () => _positive, prefault: () => prefault, preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, property: () => _property, readonly: () => readonly, record: () => record, refine: () => refine, regex: () => _regex, regexes: () => regexes_exports, registry: () => registry, safeParse: () => safeParse2, safeParseAsync: () => safeParseAsync2, set: () => set, setErrorMap: () => setErrorMap, size: () => _size, startsWith: () => _startsWith, strictObject: () => strictObject, string: () => string2, stringFormat: () => stringFormat, stringbool: () => stringbool, success: () => success, superRefine: () => superRefine, symbol: () => symbol, templateLiteral: () => templateLiteral, toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, tuple: () => tuple, uint32: () => uint32, uint64: () => uint64, ulid: () => ulid2, undefined: () => _undefined3, union: () => union, unknown: () => unknown, uppercase: () => _uppercase, url: () => url, uuid: () => uuid2, uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, void: () => _void2, xid: () => xid2 }); // node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, $ZodArray: () => $ZodArray, $ZodAsyncError: () => $ZodAsyncError, $ZodBase64: () => $ZodBase64, $ZodBase64URL: () => $ZodBase64URL, $ZodBigInt: () => $ZodBigInt, $ZodBigIntFormat: () => $ZodBigIntFormat, $ZodBoolean: () => $ZodBoolean, $ZodCIDRv4: () => $ZodCIDRv4, $ZodCIDRv6: () => $ZodCIDRv6, $ZodCUID: () => $ZodCUID, $ZodCUID2: () => $ZodCUID2, $ZodCatch: () => $ZodCatch, $ZodCheck: () => $ZodCheck, $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, $ZodCheckEndsWith: () => $ZodCheckEndsWith, $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, $ZodCheckIncludes: () => $ZodCheckIncludes, $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, $ZodCheckLessThan: () => $ZodCheckLessThan, $ZodCheckLowerCase: () => $ZodCheckLowerCase, $ZodCheckMaxLength: () => $ZodCheckMaxLength, $ZodCheckMaxSize: () => $ZodCheckMaxSize, $ZodCheckMimeType: () => $ZodCheckMimeType, $ZodCheckMinLength: () => $ZodCheckMinLength, $ZodCheckMinSize: () => $ZodCheckMinSize, $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, $ZodCheckStartsWith: () => $ZodCheckStartsWith, $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, $ZodE164: () => $ZodE164, $ZodEmail: () => $ZodEmail, $ZodEmoji: () => $ZodEmoji, $ZodEnum: () => $ZodEnum, $ZodError: () => $ZodError, $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, $ZodISODateTime: () => $ZodISODateTime, $ZodISODuration: () => $ZodISODuration, $ZodISOTime: () => $ZodISOTime, $ZodIntersection: () => $ZodIntersection, $ZodJWT: () => $ZodJWT, $ZodKSUID: () => $ZodKSUID, $ZodLazy: () => $ZodLazy, $ZodLiteral: () => $ZodLiteral, $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, $ZodRealError: () => $ZodRealError, $ZodRecord: () => $ZodRecord, $ZodRegistry: () => $ZodRegistry, $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, $brand: () => $brand, $constructor: () => $constructor, $input: () => $input, $output: () => $output, Doc: () => Doc, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, _any: () => _any, _array: () => _array, _base64: () => _base64, _base64url: () => _base64url, _bigint: () => _bigint, _boolean: () => _boolean, _catch: () => _catch, _cidrv4: () => _cidrv4, _cidrv6: () => _cidrv6, _coercedBigint: () => _coercedBigint, _coercedBoolean: () => _coercedBoolean, _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, _date: () => _date, _default: () => _default, _discriminatedUnion: () => _discriminatedUnion, _e164: () => _e164, _email: () => _email, _emoji: () => _emoji2, _endsWith: () => _endsWith, _enum: () => _enum, _file: () => _file, _float32: () => _float32, _float64: () => _float64, _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, _includes: () => _includes, _int: () => _int, _int32: () => _int32, _int64: () => _int64, _intersection: () => _intersection, _ipv4: () => _ipv4, _ipv6: () => _ipv6, _isoDate: () => _isoDate, _isoDateTime: () => _isoDateTime, _isoDuration: () => _isoDuration, _isoTime: () => _isoTime, _jwt: () => _jwt, _ksuid: () => _ksuid, _lazy: () => _lazy, _length: () => _length, _literal: () => _literal, _lowercase: () => _lowercase, _lt: () => _lt, _lte: () => _lte, _map: () => _map, _max: () => _lte, _maxLength: () => _maxLength, _maxSize: () => _maxSize, _mime: () => _mime, _min: () => _gte, _minLength: () => _minLength, _minSize: () => _minSize, _multipleOf: () => _multipleOf, _nan: () => _nan, _nanoid: () => _nanoid, _nativeEnum: () => _nativeEnum, _negative: () => _negative, _never: () => _never, _nonnegative: () => _nonnegative, _nonoptional: () => _nonoptional, _nonpositive: () => _nonpositive, _normalize: () => _normalize, _null: () => _null2, _nullable: () => _nullable, _number: () => _number, _optional: () => _optional, _overwrite: () => _overwrite, _parse: () => _parse, _parseAsync: () => _parseAsync, _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, _property: () => _property, _readonly: () => _readonly, _record: () => _record, _refine: () => _refine, _regex: () => _regex, _safeParse: () => _safeParse, _safeParseAsync: () => _safeParseAsync, _set: () => _set, _size: () => _size, _startsWith: () => _startsWith, _string: () => _string, _stringFormat: () => _stringFormat, _stringbool: () => _stringbool, _success: () => _success, _symbol: () => _symbol, _templateLiteral: () => _templateLiteral, _toLowerCase: () => _toLowerCase, _toUpperCase: () => _toUpperCase, _transform: () => _transform, _trim: () => _trim, _tuple: () => _tuple, _uint32: () => _uint32, _uint64: () => _uint64, _ulid: () => _ulid, _undefined: () => _undefined2, _union: () => _union, _unknown: () => _unknown, _uppercase: () => _uppercase, _url: () => _url, _uuid: () => _uuid, _uuidv4: () => _uuidv4, _uuidv6: () => _uuidv6, _uuidv7: () => _uuidv7, _void: () => _void, _xid: () => _xid, clone: () => clone, config: () => config, flattenError: () => flattenError, formatError: () => formatError, function: () => _function, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, isValidJWT: () => isValidJWT, locales: () => locales_exports, parse: () => parse, parseAsync: () => parseAsync, prettifyError: () => prettifyError, regexes: () => regexes_exports, registry: () => registry, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, treeifyError: () => treeifyError, util: () => util_exports, version: () => version }); // node_modules/zod/v4/core/core.js var NEVER = Object.freeze({ status: "aborted" }); // @__NO_SIDE_EFFECTS__ function $constructor(name24, initializer3, params) { function init(inst, def) { var _a25; Object.defineProperty(inst, "_zod", { value: inst._zod ?? {}, enumerable: false }); (_a25 = inst._zod).traits ?? (_a25.traits = /* @__PURE__ */ new Set()); inst._zod.traits.add(name24); initializer3(inst, def); for (const k in _2.prototype) { if (!(k in inst)) Object.defineProperty(inst, k, { value: _2.prototype[k].bind(inst) }); } inst._zod.constr = _2; inst._zod.def = def; } const Parent = params?.Parent ?? Object; class Definition extends Parent { } Object.defineProperty(Definition, "name", { value: name24 }); function _2(def) { var _a25; const inst = params?.Parent ? new Definition() : this; init(inst, def); (_a25 = inst._zod).deferred ?? (_a25.deferred = []); for (const fn2 of inst._zod.deferred) { fn2(); } return inst; } Object.defineProperty(_2, "init", { value: init }); Object.defineProperty(_2, Symbol.hasInstance, { value: (inst) => { if (params?.Parent && inst instanceof params.Parent) return true; return inst?._zod?.traits?.has(name24); } }); Object.defineProperty(_2, "name", { value: name24 }); return _2; } var $brand = /* @__PURE__ */ Symbol("zod_brand"); var $ZodAsyncError = class extends Error { constructor() { super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); } }; var globalConfig = {}; function config(newConfig) { if (newConfig) Object.assign(globalConfig, newConfig); return globalConfig; } // node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, allowsEval: () => allowsEval, assert: () => assert, assertEqual: () => assertEqual, assertIs: () => assertIs, assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, cached: () => cached, captureStackTrace: () => captureStackTrace, cleanEnum: () => cleanEnum, cleanRegex: () => cleanRegex, clone: () => clone, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, esc: () => esc, escapeRegex: () => escapeRegex, extend: () => extend, finalizeIssue: () => finalizeIssue, floatSafeRemainder: () => floatSafeRemainder, getElementAtPath: () => getElementAtPath, getEnumValues: () => getEnumValues, getLengthableOrigin: () => getLengthableOrigin, getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, isObject: () => isObject, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, merge: () => merge, normalizeParams: () => normalizeParams, nullish: () => nullish, numKeys: () => numKeys, omit: () => omit, optionalKeys: () => optionalKeys, partial: () => partial, pick: () => pick, prefixIssues: () => prefixIssues, primitiveTypes: () => primitiveTypes, promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, required: () => required, stringifyPrimitive: () => stringifyPrimitive, unwrapMessage: () => unwrapMessage }); function assertEqual(val) { return val; } function assertNotEqual(val) { return val; } function assertIs(_arg) { } function assertNever(_x) { throw new Error(); } function assert(_2) { } function getEnumValues(entries) { const numericValues = Object.values(entries).filter((v2) => typeof v2 === "number"); const values = Object.entries(entries).filter(([k, _2]) => numericValues.indexOf(+k) === -1).map(([_2, v2]) => v2); return values; } function joinValues(array3, separator = "|") { return array3.map((val) => stringifyPrimitive(val)).join(separator); } function jsonStringifyReplacer(_2, value) { if (typeof value === "bigint") return value.toString(); return value; } function cached(getter) { const set2 = false; return { get value() { if (!set2) { const value = getter(); Object.defineProperty(this, "value", { value }); return value; } throw new Error("cached value already set"); } }; } function nullish(input) { return input === null || input === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; return source.slice(start, end); } function floatSafeRemainder(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; } function defineLazy(object4, key, getter) { const set2 = false; Object.defineProperty(object4, key, { get() { if (!set2) { const value = getter(); object4[key] = value; return value; } throw new Error("cached value already set"); }, set(v2) { Object.defineProperty(object4, key, { value: v2 // configurable: true, }); }, configurable: true }); } function assignProp(target, prop, value) { Object.defineProperty(target, prop, { value, writable: true, enumerable: true, configurable: true }); } function getElementAtPath(obj, path) { if (!path) return obj; return path.reduce((acc, key) => acc?.[key], obj); } function promiseAllObject(promisesObj) { const keys = Object.keys(promisesObj); const promises = keys.map((key) => promisesObj[key]); return Promise.all(promises).then((results) => { const resolvedObj = {}; for (let i4 = 0; i4 < keys.length; i4++) { resolvedObj[keys[i4]] = results[i4]; } return resolvedObj; }); } function randomString(length = 10) { const chars = "abcdefghijklmnopqrstuvwxyz"; let str = ""; for (let i4 = 0; i4 < length; i4++) { str += chars[Math.floor(Math.random() * chars.length)]; } return str; } function esc(str) { return JSON.stringify(str); } var captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => { }; function isObject(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } var allowsEval = cached(() => { if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { return false; } try { const F2 = Function; new F2(""); return true; } catch (_2) { return false; } }); function isPlainObject(o3) { if (isObject(o3) === false) return false; const ctor = o3.constructor; if (ctor === void 0) return true; const prot = ctor.prototype; if (isObject(prot) === false) return false; if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; } return true; } function numKeys(data) { let keyCount = 0; for (const key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { keyCount++; } } return keyCount; } var getParsedType = (data) => { const t4 = typeof data; switch (t4) { case "undefined": return "undefined"; case "string": return "string"; case "number": return Number.isNaN(data) ? "nan" : "number"; case "boolean": return "boolean"; case "function": return "function"; case "bigint": return "bigint"; case "symbol": return "symbol"; case "object": if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return "promise"; } if (typeof Map !== "undefined" && data instanceof Map) { return "map"; } if (typeof Set !== "undefined" && data instanceof Set) { return "set"; } if (typeof Date !== "undefined" && data instanceof Date) { return "date"; } if (typeof File !== "undefined" && data instanceof File) { return "file"; } return "object"; default: throw new Error(`Unknown data type: ${t4}`); } }; var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); var primitiveTypes = /* @__PURE__ */ 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 (typeof params === "string") return { error: () => params }; if (params?.message !== void 0) { if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params"); params.error = params.message; } delete params.message; if (typeof params.error === "string") return { ...params, error: () => params.error }; return params; } function createTransparentProxy(getter) { let target; return new Proxy({}, { get(_2, prop, receiver) { target ?? (target = getter()); return Reflect.get(target, prop, receiver); }, set(_2, prop, value, receiver) { target ?? (target = getter()); return Reflect.set(target, prop, value, receiver); }, has(_2, prop) { target ?? (target = getter()); return Reflect.has(target, prop); }, deleteProperty(_2, prop) { target ?? (target = getter()); return Reflect.deleteProperty(target, prop); }, ownKeys(_2) { target ?? (target = getter()); return Reflect.ownKeys(target); }, getOwnPropertyDescriptor(_2, prop) { target ?? (target = getter()); return Reflect.getOwnPropertyDescriptor(target, prop); }, defineProperty(_2, prop, descriptor) { target ?? (target = getter()); return Reflect.defineProperty(target, prop, descriptor); } }); } function stringifyPrimitive(value) { if (typeof value === "bigint") return value.toString() + "n"; if (typeof value === "string") return `"${value}"`; return `${value}`; } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; }); } var NUMBER_FORMAT_RANGES = { safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] }; var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] }; function pick(schema, mask) { const newShape = {}; const currDef = schema._zod.def; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; newShape[key] = currDef.shape[key]; } return clone(schema, { ...schema._zod.def, shape: newShape, checks: [] }); } function omit(schema, mask) { const newShape = { ...schema._zod.def.shape }; const currDef = schema._zod.def; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; delete newShape[key]; } return clone(schema, { ...schema._zod.def, shape: newShape, checks: [] }); } function extend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to extend: expected a plain object"); } const def = { ...schema._zod.def, get shape() { const _shape = { ...schema._zod.def.shape, ...shape }; assignProp(this, "shape", _shape); return _shape; }, checks: [] // delete existing checks }; return clone(schema, def); } function merge(a3, b5) { return clone(a3, { ...a3._zod.def, get shape() { const _shape = { ...a3._zod.def.shape, ...b5._zod.def.shape }; assignProp(this, "shape", _shape); return _shape; }, catchall: b5._zod.def.catchall, checks: [] // delete existing checks }); } function partial(Class2, schema, mask) { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in oldShape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; shape[key] = Class2 ? new Class2({ type: "optional", innerType: oldShape[key] }) : oldShape[key]; } } else { for (const key in oldShape) { shape[key] = Class2 ? new Class2({ type: "optional", innerType: oldShape[key] }) : oldShape[key]; } } return clone(schema, { ...schema._zod.def, shape, checks: [] }); } function required(Class2, schema, mask) { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; shape[key] = new Class2({ type: "nonoptional", innerType: oldShape[key] }); } } else { for (const key in oldShape) { shape[key] = new Class2({ type: "nonoptional", innerType: oldShape[key] }); } } return clone(schema, { ...schema._zod.def, shape, // optional: [], checks: [] }); } function aborted(x4, startIndex = 0) { for (let i4 = startIndex; i4 < x4.issues.length; i4++) { if (x4.issues[i4]?.continue !== true) return true; } return false; } function prefixIssues(path, issues) { return issues.map((iss) => { var _a25; (_a25 = iss).path ?? (_a25.path = []); iss.path.unshift(path); return iss; }); } function unwrapMessage(message) { return typeof message === "string" ? message : message?.message; } function finalizeIssue(iss, ctx, config2) { const full = { ...iss, path: iss.path ?? [] }; if (!iss.message) { const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.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 (typeof input === "string") return "string"; return "unknown"; } function issue(...args) { const [iss, input, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", input, inst }; } return { ...iss }; } function cleanEnum(obj) { return Object.entries(obj).filter(([k, _2]) => { return Number.isNaN(Number.parseInt(k, 10)); }).map((el) => el[1]); } var Class = class { constructor(..._args) { } }; // node_modules/zod/v4/core/errors.js var initializer = (inst, def) => { inst.name = "$ZodError"; Object.defineProperty(inst, "_zod", { value: inst._zod, enumerable: false }); Object.defineProperty(inst, "issues", { value: def, enumerable: false }); Object.defineProperty(inst, "message", { get() { return JSON.stringify(def, jsonStringifyReplacer, 2); }, enumerable: true // configurable: false, }); Object.defineProperty(inst, "toString", { value: () => inst.message, enumerable: false }); }; var $ZodError = $constructor("$ZodError", initializer); var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); function flattenError(error40, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; for (const sub of error40.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(error40, _mapper) { const mapper = _mapper || function(issue2) { return issue2.message; }; const fieldErrors = { _errors: [] }; const processError = (error41) => { for (const issue2 of error41.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues })); } else if (issue2.code === "invalid_key") { processError({ issues: issue2.issues }); } else if (issue2.code === "invalid_element") { processError({ issues: issue2.issues }); } else if (issue2.path.length === 0) { fieldErrors._errors.push(mapper(issue2)); } else { let curr = fieldErrors; let i4 = 0; while (i4 < issue2.path.length) { const el = issue2.path[i4]; const terminal = i4 === issue2.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue2)); } curr = curr[el]; i4++; } } } }; processError(error40); return fieldErrors; } function treeifyError(error40, _mapper) { const mapper = _mapper || function(issue2) { return issue2.message; }; const result = { errors: [] }; const processError = (error41, path = []) => { var _a25, _b19; for (const issue2 of error41.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, issue2.path)); } else if (issue2.code === "invalid_key") { processError({ issues: issue2.issues }, issue2.path); } else if (issue2.code === "invalid_element") { processError({ issues: issue2.issues }, issue2.path); } else { const fullpath = [...path, ...issue2.path]; if (fullpath.length === 0) { result.errors.push(mapper(issue2)); continue; } let curr = result; let i4 = 0; while (i4 < fullpath.length) { const el = fullpath[i4]; const terminal = i4 === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); (_a25 = curr.properties)[el] ?? (_a25[el] = { errors: [] }); curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); (_b19 = curr.items)[el] ?? (_b19[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { curr.errors.push(mapper(issue2)); } i4++; } } } }; processError(error40); return result; } function toDotPath(path) { const segs = []; for (const seg of path) { if (typeof seg === "number") segs.push(`[${seg}]`); else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`); else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`); else { if (segs.length) segs.push("."); segs.push(seg); } } return segs.join(""); } function prettifyError(error40) { const lines = []; const issues = [...error40.issues].sort((a3, b5) => a3.path.length - b5.path.length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) lines.push(` \u2192 at ${toDotPath(issue2.path)}`); } return lines.join("\n"); } // node_modules/zod/v4/core/parse.js var _parse = (_Err) => (schema, value, _ctx, _params) => { const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } if (result.issues.length) { const e5 = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e5, _params?.callee); throw e5; } return result.value; }; var parse = /* @__PURE__ */ _parse($ZodRealError); var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; if (result.issues.length) { const e5 = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e5, params?.callee); throw e5; } return result.value; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } return result.issues.length ? { success: false, error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) } : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; return result.issues.length ? { success: false, error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) } : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); // node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { _emoji: () => _emoji, base64: () => base64, base64url: () => base64url, bigint: () => bigint, boolean: () => boolean, browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, cuid: () => cuid, cuid2: () => cuid2, date: () => date, datetime: () => datetime, domain: () => domain, duration: () => duration, e164: () => e164, email: () => email, emoji: () => emoji, extendedDuration: () => extendedDuration, guid: () => guid, hostname: () => hostname, html5Email: () => html5Email, integer: () => integer, ipv4: () => ipv4, ipv6: () => ipv6, ksuid: () => ksuid, lowercase: () => lowercase, nanoid: () => nanoid, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, string: () => string, time: () => time, ulid: () => ulid, undefined: () => _undefined, unicodeEmail: () => unicodeEmail, uppercase: () => uppercase, uuid: () => uuid, uuid4: () => uuid4, uuid6: () => uuid6, uuid7: () => uuid7, xid: () => xid }); var cuid = /^[cC][^\s-]{8,}$/; var cuid2 = /^[0-9a-z]+$/; var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var 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)?)??$/; var 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})$/; var uuid = (version2) => { if (!version2) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); }; var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var 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])?)*$/; var 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,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var 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])?)*$/; var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; function emoji() { return new RegExp(_emoji, "u"); } var 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])$/; var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/; var 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])$/; var 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])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; var base64url = /^[A-Za-z0-9_-]*$/; var hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; var e164 = /^\+(?:[0-9]){6,14}[0-9]$/; var 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])))`; var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { const time3 = timeSource({ precision: args.precision }); const opts = ["Z"]; if (args.local) opts.push(""); if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); const timeRegex2 = `${time3}(?:${opts.join("|")})`; return new RegExp(`^${dateSource}T(?:${timeRegex2})$`); } var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); }; var bigint = /^\d+n?$/; var integer = /^\d+$/; var number = /^-?\d+(?:\.\d+)?/i; var boolean = /true|false/i; var _null = /null/i; var _undefined = /undefined/i; var lowercase = /^[^A-Z]*$/; var uppercase = /^[^a-z]*$/; // node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a25; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a25 = inst._zod).onattach ?? (_a25.onattach = []); }); var numericOriginMap = { number: "number", bigint: "bigint", object: "date" }; var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; if (def.value < curr) { if (def.inclusive) bag.maximum = def.value; else bag.exclusiveMaximum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ origin, code: "too_big", maximum: def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; if (def.value > curr) { if (def.inclusive) bag.minimum = def.value; else bag.exclusiveMinimum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ origin, code: "too_small", minimum: def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.onattach.push((inst2) => { var _a25; (_a25 = inst2._zod.bag).multipleOf ?? (_a25.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 = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ origin: typeof payload.value, code: "not_multiple_of", divisor: def.value, input: payload.value, inst, continue: !def.abort }); }; }); var $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((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; if (isInt) bag.pattern = integer; }); inst._zod.check = (payload) => { const input = payload.value; if (isInt) { if (!Number.isInteger(input)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", input, inst }); return; } if (!Number.isSafeInteger(input)) { if (input > 0) { payload.issues.push({ input, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, continue: !def.abort }); } else { payload.issues.push({ input, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, continue: !def.abort }); } return; } } if (input < minimum) { payload.issues.push({ origin: "number", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "number", input, code: "too_big", maximum, inst }); } }; }); var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst2) => { const bag = inst2._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, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "bigint", input, code: "too_big", maximum, inst }); } }; }); var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a25; $ZodCheck.init(inst, def); (_a25 = inst._zod.def).when ?? (_a25.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._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, input, inst, continue: !def.abort }); }; }); var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a25; $ZodCheck.init(inst, def); (_a25 = inst._zod.def).when ?? (_a25.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._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, input, inst, continue: !def.abort }); }; }); var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a25; $ZodCheck.init(inst, def); (_a25 = inst._zod.def).when ?? (_a25.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const bag = inst2._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 }); }; }); var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a25; $ZodCheck.init(inst, def); (_a25 = inst._zod.def).when ?? (_a25.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._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 }); }; }); var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a25; $ZodCheck.init(inst, def); (_a25 = inst._zod.def).when ?? (_a25.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._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 }); }; }); var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a25; $ZodCheck.init(inst, def); (_a25 = inst._zod.def).when ?? (_a25.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const bag = inst2._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 }); }; }); var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a25, _b19; $ZodCheck.init(inst, def); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; if (def.pattern) { bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(def.pattern); } }); if (def.pattern) (_a25 = inst._zod).check ?? (_a25.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 (_b19 = inst._zod).check ?? (_b19.check = () => { }); }); var $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 }); }; }); var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { def.pattern ?? (def.pattern = lowercase); $ZodCheckStringFormat.init(inst, def); }); var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { def.pattern ?? (def.pattern = uppercase); $ZodCheckStringFormat.init(inst, def); }); var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); def.pattern = pattern; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "includes", includes: def.includes, input: payload.value, inst, continue: !def.abort }); }; }); var $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((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "starts_with", prefix: def.prefix, input: payload.value, inst, continue: !def.abort }); }; }); var $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((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "ends_with", suffix: def.suffix, input: payload.value, inst, continue: !def.abort }); }; }); function handleCheckPropertyResult(result, payload, property) { if (result.issues.length) { payload.issues.push(...prefixIssues(property, result.issues)); } } var $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((result2) => handleCheckPropertyResult(result2, payload, def.property)); } handleCheckPropertyResult(result, payload, def.property); return; }; }); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); inst._zod.onattach.push((inst2) => { inst2._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 }); }; }); var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.check = (payload) => { payload.value = def.tx(payload.value); }; }); // node_modules/zod/v4/core/doc.js var Doc = class { constructor(args = []) { this.content = []; this.indent = 0; if (this) this.args = args; } indented(fn2) { this.indent += 1; fn2(this); this.indent -= 1; } write(arg) { if (typeof arg === "function") { arg(this, { execution: "sync" }); arg(this, { execution: "async" }); return; } const content = arg; const lines = content.split("\n").filter((x4) => x4); const minIndent = Math.min(...lines.map((x4) => x4.length - x4.trimStart().length)); const dedented = lines.map((x4) => x4.slice(minIndent)).map((x4) => " ".repeat(this.indent * 2) + x4); for (const line2 of dedented) { this.content.push(line2); } } compile() { const F2 = Function; const args = this?.args; const content = this?.content ?? [``]; const lines = [...content.map((x4) => ` ${x4}`)]; return new F2(...args, lines.join("\n")); } }; // node_modules/zod/v4/core/versions.js var version = { major: 4, minor: 0, patch: 0 }; // node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a25; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; const checks = [...inst._zod.def.checks ?? []]; if (inst._zod.traits.has("$ZodCheck")) { checks.unshift(inst); } for (const ch2 of checks) { for (const fn2 of ch2._zod.onattach) { fn2(inst); } } if (checks.length === 0) { (_a25 = inst._zod).deferred ?? (_a25.deferred = []); inst._zod.deferred?.push(() => { inst._zod.run = inst._zod.parse; }); } else { const runChecks = (payload, checks2, ctx) => { let isAborted2 = aborted(payload); let asyncResult; for (const ch2 of checks2) { if (ch2._zod.def.when) { const shouldRun = ch2._zod.def.when(payload); if (!shouldRun) continue; } else if (isAborted2) { continue; } const currLen = payload.issues.length; const _2 = ch2._zod.check(payload); if (_2 instanceof Promise && ctx?.async === false) { throw new $ZodAsyncError(); } if (asyncResult || _2 instanceof Promise) { asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { await _2; const nextLen = payload.issues.length; if (nextLen === currLen) return; if (!isAborted2) isAborted2 = aborted(payload, currLen); }); } else { const nextLen = payload.issues.length; if (nextLen === currLen) continue; if (!isAborted2) isAborted2 = aborted(payload, currLen); } } if (asyncResult) { return asyncResult.then(() => { return payload; }); } return payload; }; inst._zod.run = (payload, ctx) => { const result = inst._zod.parse(payload, ctx); if (result instanceof Promise) { if (ctx.async === false) throw new $ZodAsyncError(); return result.then((result2) => runChecks(result2, checks, ctx)); } return runChecks(result, checks, ctx); }; } inst["~standard"] = { validate: (value) => { try { const r4 = safeParse(inst, value); return r4.success ? { value: r4.data } : { issues: r4.error?.issues }; } catch (_2) { return safeParseAsync(inst, value).then((r4) => r4.success ? { value: r4.data } : { issues: r4.error?.issues }); } }, vendor: "zod", version: 1 }; }); var $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, _2) => { if (def.coerce) try { payload.value = String(payload.value); } catch (_3) { } if (typeof payload.value === "string") return payload; payload.issues.push({ expected: "string", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { $ZodCheckStringFormat.init(inst, def); $ZodString.init(inst, def); }); var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { def.pattern ?? (def.pattern = guid); $ZodStringFormat.init(inst, def); }); var $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 v2 = versionMap[def.version]; if (v2 === void 0) throw new Error(`Invalid UUID version: "${def.version}"`); def.pattern ?? (def.pattern = uuid(v2)); } else def.pattern ?? (def.pattern = uuid()); $ZodStringFormat.init(inst, def); }); var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const orig = payload.value; const url2 = new URL(orig); const href = url2.href; if (def.hostname) { def.hostname.lastIndex = 0; if (!def.hostname.test(url2.hostname)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid hostname", pattern: hostname.source, input: payload.value, inst, continue: !def.abort }); } } if (def.protocol) { def.protocol.lastIndex = 0; if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid protocol", pattern: def.protocol.source, input: payload.value, inst, continue: !def.abort }); } } if (!orig.endsWith("/") && href.endsWith("/")) { payload.value = href.slice(0, -1); } else { payload.value = href; } return; } catch (_2) { payload.issues.push({ code: "invalid_format", format: "url", input: payload.value, inst, continue: !def.abort }); } }; }); var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { def.pattern ?? (def.pattern = emoji()); $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { def.pattern ?? (def.pattern = nanoid); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { def.pattern ?? (def.pattern = cuid); $ZodStringFormat.init(inst, def); }); var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { def.pattern ?? (def.pattern = cuid2); $ZodStringFormat.init(inst, def); }); var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { def.pattern ?? (def.pattern = ulid); $ZodStringFormat.init(inst, def); }); var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { def.pattern ?? (def.pattern = xid); $ZodStringFormat.init(inst, def); }); var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { def.pattern ?? (def.pattern = ksuid); $ZodStringFormat.init(inst, def); }); var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { def.pattern ?? (def.pattern = datetime(def)); $ZodStringFormat.init(inst, def); }); var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { def.pattern ?? (def.pattern = date); $ZodStringFormat.init(inst, def); }); var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { def.pattern ?? (def.pattern = time(def)); $ZodStringFormat.init(inst, def); }); var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { def.pattern ?? (def.pattern = duration); $ZodStringFormat.init(inst, def); }); var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = `ipv4`; }); }); var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = `ipv6`; }); inst._zod.check = (payload) => { try { new URL(`http://[${payload.value}]`); } catch { payload.issues.push({ code: "invalid_format", format: "ipv6", input: payload.value, inst, continue: !def.abort }); } }; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { const [address, prefix] = payload.value.split("/"); try { if (!prefix) throw new Error(); const prefixNum = Number(prefix); if (`${prefixNum}` !== prefix) throw new Error(); if (prefixNum < 0 || prefixNum > 128) throw new Error(); new URL(`http://[${address}]`); } catch { payload.issues.push({ code: "invalid_format", format: "cidrv6", input: payload.value, inst, continue: !def.abort }); } }; }); function isValidBase64(data) { if (data === "") return true; if (data.length % 4 !== 0) return false; try { atob(data); return true; } catch { return false; } } var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { def.pattern ?? (def.pattern = base64); $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst2) => { inst2._zod.bag.contentEncoding = "base64"; }); inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64", input: payload.value, inst, continue: !def.abort }); }; }); function isValidBase64URL(data) { if (!base64url.test(data)) return false; const base643 = data.replace(/[-_]/g, (c2) => c2 === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { def.pattern ?? (def.pattern = base64url); $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst2) => { inst2._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 }); }; }); var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); function isValidJWT(token2, algorithm = null) { try { const tokensParts = token2.split("."); if (tokensParts.length !== 3) return false; const [header] = tokensParts; if (!header) return false; const parsedHeader = JSON.parse(atob(header)); if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false; if (!parsedHeader.alg) return false; if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; return true; } catch { return false; } } var $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 }); }; }); var $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 }); }; }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = inst._zod.bag.pattern ?? number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_2) { } const input = payload.value; if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { return payload; } const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", input, inst, ...received ? { received } : {} }); return payload; }; }); var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodCheckNumberFormat.init(inst, def); $ZodNumber.init(inst, def); }); var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = boolean; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Boolean(payload.value); } catch (_2) { } const input = payload.value; if (typeof input === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", input, inst }); return payload; }; }); var $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 (_2) { } if (typeof payload.value === "bigint") return payload; payload.issues.push({ expected: "bigint", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { $ZodCheckBigIntFormat.init(inst, def); $ZodBigInt.init(inst, def); }); var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", input, inst }); return payload; }; }); var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.optin = "optional"; inst._zod.optout = "optional"; inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", input, inst }); return payload; }; }); var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", input, inst }); return payload; }; }); var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); var $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; }; }); var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", input, inst }); return payload; }; }); var $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; } var $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 i4 = 0; i4 < input.length; i4++) { const item = input[i4]; const result = def.element._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleArrayResult(result2, payload, i4))); } else { handleArrayResult(result, payload, i4); } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; }; }); function handleObjectResult(result, final, key) { if (result.issues.length) { final.issues.push(...prefixIssues(key, result.issues)); } final.value[key] = result.value; } function handleOptionalObjectResult(result, final, key, input) { if (result.issues.length) { if (input[key] === void 0) { if (key in input) { final.value[key] = void 0; } else { final.value[key] = result.value; } } else { final.issues.push(...prefixIssues(key, result.issues)); } } else if (result.value === void 0) { if (key in input) final.value[key] = void 0; } else { final.value[key] = result.value; } } var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const _normalized = cached(() => { const keys = Object.keys(def.shape); for (const k of keys) { if (!(def.shape[k] instanceof $ZodType)) { throw new Error(`Invalid element at key "${k}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { shape: def.shape, keys, keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; }); defineLazy(inst._zod, "propValues", () => { const shape = def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); for (const v2 of field.values) propValues[key].add(v2); } } return propValues; }); const generateFastpass = (shape) => { const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; const parseStr = (key) => { const k = esc(key); return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; }; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; for (const key of normalized.keys) { ids[key] = `key_${counter++}`; } doc.write(`const newResult = {}`); for (const key of normalized.keys) { if (normalized.optionalKeys.has(key)) { const id = ids[key]; doc.write(`const ${id} = ${parseStr(key)};`); const k = esc(key); doc.write(` if (${id}.issues.length) { if (input[${k}] === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { payload.issues = payload.issues.concat( ${id}.issues.map((iss) => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}], })) ); } } else if (${id}.value === undefined) { if (${k} in input) newResult[${k}] = undefined; } else { newResult[${k}] = ${id}.value; } `); } else { const id = ids[key]; doc.write(`const ${id} = ${parseStr(key)};`); doc.write(` if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ ...iss, path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}] })));`); doc.write(`newResult[${esc(key)}] = ${id}.value`); } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); const fn2 = doc.compile(); return (payload, ctx) => fn2(shape, payload, ctx); }; let fastpass; const isObject2 = isObject; const jit = !globalConfig.jitless; const allowsEval2 = allowsEval; const fastEnabled = jit && allowsEval2.value; const catchall = def.catchall; let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); const input = payload.value; if (!isObject2(input)) { payload.issues.push({ expected: "object", code: "invalid_type", input, inst }); return payload; } const proms = []; if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { if (!fastpass) fastpass = generateFastpass(def.shape); payload = fastpass(payload, ctx); } else { payload.value = {}; const shape = value.shape; for (const key of value.keys) { const el = shape[key]; const r4 = el._zod.run({ value: input[key], issues: [] }, ctx); const isOptional2 = el._zod.optin === "optional" && el._zod.optout === "optional"; if (r4 instanceof Promise) { proms.push(r4.then((r5) => isOptional2 ? handleOptionalObjectResult(r5, payload, key, input) : handleObjectResult(r5, payload, key))); } else if (isOptional2) { handleOptionalObjectResult(r4, payload, key, input); } else { handleObjectResult(r4, payload, key); } } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } const unrecognized = []; const keySet = value.keySet; const _catchall = catchall._zod; const t4 = _catchall.def.type; for (const key of Object.keys(input)) { if (keySet.has(key)) continue; if (t4 === "never") { unrecognized.push(key); continue; } const r4 = _catchall.run({ value: input[key], issues: [] }, ctx); if (r4 instanceof Promise) { proms.push(r4.then((r5) => handleObjectResult(r5, payload, key))); } else { handleObjectResult(r4, payload, key); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, input, inst }); } if (!proms.length) return payload; return Promise.all(proms).then(() => { return payload; }); }; }); function handleUnionResults(results, final, inst, ctx) { for (const result of results) { if (result.issues.length === 0) { final.value = result.value; return final; } } final.issues.push({ code: "invalid_union", input: final.value, inst, errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) }); return final; } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.options.some((o3) => o3._zod.optin === "optional") ? "optional" : void 0); defineLazy(inst._zod, "optout", () => def.options.some((o3) => o3._zod.optout === "optional") ? "optional" : void 0); defineLazy(inst._zod, "values", () => { if (def.options.every((o3) => o3._zod.values)) { return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); defineLazy(inst._zod, "pattern", () => { if (def.options.every((o3) => o3._zod.pattern)) { const patterns = def.options.map((o3) => o3._zod.pattern); return new RegExp(`^(${patterns.map((p2) => cleanRegex(p2.source)).join("|")})$`); } return void 0; }); inst._zod.parse = (payload, ctx) => { let async = false; const results = []; for (const option of def.options) { const result = option._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { results.push(result); async = true; } else { if (result.issues.length === 0) return result; results.push(result); } } if (!async) return handleUnionResults(results, payload, inst, ctx); return Promise.all(results).then((results2) => { return handleUnionResults(results2, payload, inst, ctx); }); }; }); var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { $ZodUnion.init(inst, def); const _super = inst._zod.parse; defineLazy(inst._zod, "propValues", () => { const propValues = {}; for (const option of def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); for (const [k, v2] of Object.entries(pv)) { if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set(); for (const val of v2) { propValues[k].add(val); } } } return propValues; }); const disc = cached(() => { const opts = def.options; const map2 = /* @__PURE__ */ new Map(); for (const o3 of opts) { const values = o3._zod.propValues[def.discriminator]; if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o3)}"`); for (const v2 of values) { if (map2.has(v2)) { throw new Error(`Duplicate discriminator value "${String(v2)}"`); } map2.set(v2, o3); } } return map2; }); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isObject(input)) { payload.issues.push({ code: "invalid_type", expected: "object", input, inst }); return payload; } const opt = disc.value.get(input?.[def.discriminator]); if (opt) { return opt._zod.run(payload, ctx); } if (def.unionFallback) { return _super(payload, ctx); } payload.issues.push({ code: "invalid_union", errors: [], note: "No matching discriminator", input, path: [def.discriminator], inst }); return payload; }; }); var $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(([left2, right2]) => { return handleIntersectionResults(payload, left2, right2); }); } return handleIntersectionResults(payload, left, right); }; }); function mergeValues(a3, b5) { if (a3 === b5) { return { valid: true, data: a3 }; } if (a3 instanceof Date && b5 instanceof Date && +a3 === +b5) { return { valid: true, data: a3 }; } if (isPlainObject(a3) && isPlainObject(b5)) { const bKeys = Object.keys(b5); const sharedKeys = Object.keys(a3).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a3, ...b5 }; for (const key of sharedKeys) { const sharedValue = mergeValues(a3[key], b5[key]); if (!sharedValue.valid) { return { valid: false, mergeErrorPath: [key, ...sharedValue.mergeErrorPath] }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } if (Array.isArray(a3) && Array.isArray(b5)) { if (a3.length !== b5.length) { return { valid: false, mergeErrorPath: [] }; } const newArray = []; for (let index = 0; index < a3.length; index++) { const itemA = a3[index]; const itemB = b5[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) { if (left.issues.length) { result.issues.push(...left.issues); } if (right.issues.length) { result.issues.push(...right.issues); } if (aborted(result)) return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; return result; } var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); 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 = []; if (!def.rest) { const tooBig = input.length > items.length; const tooSmall = input.length < optStart - 1; if (tooBig || tooSmall) { payload.issues.push({ input, inst, origin: "array", ...tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length } }); return payload; } } let i4 = -1; for (const item of items) { i4++; if (i4 >= input.length) { if (i4 >= optStart) continue; } const result = item._zod.run({ value: input[i4], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleTupleResult(result2, payload, i4))); } else { handleTupleResult(result, payload, i4); } } if (def.rest) { const rest = input.slice(items.length); for (const el of rest) { i4++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleTupleResult(result2, payload, i4))); } else { handleTupleResult(result, payload, i4); } } } 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; } var $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 = []; if (def.keyType._zod.values) { const values = def.keyType._zod.values; payload.value = {}; for (const key of values) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } payload.value[key] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } payload.value[key] = result.value; } } } let unrecognized; for (const key in input) { if (!values.has(key)) { unrecognized = unrecognized ?? []; unrecognized.push(key); } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", input, inst, keys: unrecognized }); } } else { payload.value = {}; for (const key of Reflect.ownKeys(input)) { if (key === "__proto__") continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } if (keyResult.issues.length) { payload.issues.push({ origin: "record", code: "invalid_key", issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), input: key, path: [key], inst }); payload.value[keyResult.value] = keyResult.value; continue; } const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } payload.value[keyResult.value] = result2.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; }; }); var $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 = /* @__PURE__ */ new Map(); for (const [key, value] of input) { const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { handleMapResult(keyResult2, valueResult2, 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({ origin: "map", code: "invalid_key", input, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, 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, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); } } final.value.set(keyResult.value, valueResult.value); } var $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 = /* @__PURE__ */ 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((result2) => handleSetResult(result2, 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); } var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { $ZodType.init(inst, def); const values = getEnumValues(def.entries); inst._zod.values = new Set(values); inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o3) => typeof o3 === "string" ? escapeRegex(o3) : o3.toString()).join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (inst._zod.values.has(input)) { return payload; } payload.issues.push({ code: "invalid_value", values, input, inst }); return payload; }; }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); inst._zod.values = new Set(def.values); inst._zod.pattern = new RegExp(`^(${def.values.map((o3) => typeof o3 === "string" ? escapeRegex(o3) : o3 ? o3.toString() : String(o3)).join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (inst._zod.values.has(input)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, input, inst }); return payload; }; }); var $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; }; }); var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const _out = def.transform(payload.value, payload); if (_ctx.async) { const output = _out instanceof Promise ? _out : Promise.resolve(_out); return output.then((output2) => { payload.value = output2; return payload; }); } if (_out instanceof Promise) { throw new $ZodAsyncError(); } payload.value = _out; return payload; }; }); var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; inst._zod.optout = "optional"; defineLazy(inst._zod, "values", () => { return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; }); defineLazy(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { if (def.innerType._zod.optin === "optional") { return def.innerType._zod.run(payload, ctx); } if (payload.value === void 0) { return payload; } return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); defineLazy(inst._zod, "values", () => { return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) return payload; return def.innerType._zod.run(payload, ctx); }; }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (payload.value === void 0) { payload.value = def.defaultValue; return payload; } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => handleDefaultResult(result2, def)); } return handleDefaultResult(result, def); }; }); function handleDefaultResult(payload, def) { if (payload.value === void 0) { payload.value = def.defaultValue; } return payload; } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (payload.value === void 0) { payload.value = def.defaultValue; } return def.innerType._zod.run(payload, ctx); }; }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => { const v2 = def.innerType._zod.values; return v2 ? new Set([...v2].filter((x4) => x4 !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => handleNonOptionalResult(result2, inst)); } return handleNonOptionalResult(result, inst); }; }); function handleNonOptionalResult(payload, inst) { if (!payload.issues.length && payload.value === void 0) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: payload.value, inst }); } return payload; } var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => { payload.value = result2.issues.length === 0; return payload; }); } payload.value = result.issues.length === 0; return payload; }; }); var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => { payload.value = result2.value; if (result2.issues.length) { payload.value = def.catchValue({ ...payload, error: { issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, input: payload.value }); payload.issues = []; } return payload; }); } payload.value = result.value; if (result.issues.length) { payload.value = def.catchValue({ ...payload, error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, input: payload.value }); payload.issues = []; } return payload; }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { payload.issues.push({ input: payload.value, inst, expected: "nan", code: "invalid_type" }); return payload; } return payload; }; }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => def.in._zod.values); defineLazy(inst._zod, "optin", () => def.in._zod.optin); defineLazy(inst._zod, "optout", () => def.out._zod.optout); inst._zod.parse = (payload, ctx) => { const left = def.in._zod.run(payload, ctx); if (left instanceof Promise) { return left.then((left2) => handlePipeResult(left2, def, ctx)); } return handlePipeResult(left, def, ctx); }; }); function handlePipeResult(left, def, ctx) { if (aborted(left)) { return left; } return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); defineLazy(inst._zod, "values", () => def.innerType._zod.values); defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then(handleReadonlyResult); } return handleReadonlyResult(result); }; }); function handleReadonlyResult(payload) { payload.value = Object.freeze(payload.value); return payload; } var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (part instanceof $ZodType) { 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 (part === null || 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 (typeof payload.value !== "string") { payload.issues.push({ input: payload.value, inst, expected: "template_literal", 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: "template_literal", pattern: inst._zod.pattern.source }); return payload; } return payload; }; }); var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); }; }); var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "innerType", () => def.getter()); defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern); defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues); defineLazy(inst._zod, "optin", () => inst._zod.innerType._zod.optin); defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); }; }); var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { $ZodCheck.init(inst, def); $ZodType.init(inst, def); inst._zod.parse = (payload, _2) => { return payload; }; inst._zod.check = (payload) => { const input = payload.value; const r4 = def.fn(input); if (r4 instanceof Promise) { return r4.then((r5) => handleRefineResult(r5, payload, input, inst)); } handleRefineResult(r4, payload, input, inst); return; }; }); function handleRefineResult(result, payload, input, inst) { if (!result) { const _iss = { code: "custom", input, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], // incorporates params.error into issue reporting continue: !inst._zod.def.abort // params: inst._zod.def.params, }; if (inst._zod.def.params) _iss.params = inst._zod.def.params; payload.issues.push(issue(_iss)); } } // node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, ca: () => ca_default, cs: () => cs_default, de: () => de_default, en: () => en_default, eo: () => eo_default, es: () => es_default, fa: () => fa_default, fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, he: () => he_default, hu: () => hu_default, id: () => id_default, it: () => it_default, ja: () => ja_default, kh: () => kh_default, ko: () => ko_default, mk: () => mk_default, ms: () => ms_default, nl: () => nl_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, ru: () => ru_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, th: () => th_default, tr: () => tr_default, ua: () => ua_default, ur: () => ur_default, vi: () => vi_default, zhCN: () => zh_CN_default, zhTW: () => zh_TW_default }); // node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u0645\u062F\u062E\u0644", email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", url: "\u0631\u0627\u0628\u0637", emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`; return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`; return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`; if (_issue.format === "ends_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; if (_issue.format === "regex") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; } case "not_multiple_of": return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`; case "unrecognized_keys": return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; case "invalid_key": return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; case "invalid_union": return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; case "invalid_element": return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; default: return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; } }; }; function ar_default() { return { localeError: error() }; } // node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, set: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { 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", 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" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${issue2.expected}, daxil olan ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`; return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; if (_issue.format === "ends_with") return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; if (_issue.format === "includes") return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; if (_issue.format === "regex") return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; return `Yanl\u0131\u015F ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; case "unrecognized_keys": return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; case "invalid_union": return "Yanl\u0131\u015F d\u0259y\u0259r"; case "invalid_element": return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; default: return `Yanl\u0131\u015F d\u0259y\u0259r`; } }; }; function az_default() { return { localeError: error2() }; } // node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; const lastTwoDigits = absCount % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { return many; } if (lastDigit === 1) { return one; } if (lastDigit >= 2 && lastDigit <= 4) { return few; } return many; } var error3 = () => { const Sizable = { string: { unit: { one: "\u0441\u0456\u043C\u0432\u0430\u043B", few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u044B", many: "\u0431\u0430\u0439\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "\u043B\u0456\u043A"; } case "object": { if (Array.isArray(data)) { return "\u043C\u0430\u0441\u0456\u045E"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u0443\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0430\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0447\u0430\u0441", duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { const maxValue = Number(issue2.maximum); const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { const minValue = Number(issue2.minimum); const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; case "invalid_union": return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; case "invalid_element": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`; default: return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; } }; }; function be_default() { return { localeError: error3() }; } // node_modules/zod/v4/locales/ca.js var error4 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, set: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "entrada", email: "adre\xE7a electr\xF2nica", 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: "data i hora ISO", date: "data ISO", time: "hora ISO", duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Tipus inv\xE0lid: s'esperava ${issue2.expected}, s'ha rebut ${parsedType4(issue2.input)}`; // return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`; return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`; case "too_big": { const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de"; const sizing = getSizing(issue2.origin); if (sizing) return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de"; const sizing = getSizing(issue2.origin); if (sizing) { return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; if (_issue.format === "includes") return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; if (_issue.format === "regex") return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; return `Format inv\xE0lid per a ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`; case "unrecognized_keys": return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Clau inv\xE0lida a ${issue2.origin}`; case "invalid_union": return "Entrada inv\xE0lida"; // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general case "invalid_element": return `Element inv\xE0lid a ${issue2.origin}`; default: return `Entrada inv\xE0lida`; } }; }; function ca_default() { return { localeError: error4() }; } // node_modules/zod/v4/locales/cs.js var error5 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, set: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "\u010D\xEDslo"; } case "string": { return "\u0159et\u011Bzec"; } case "boolean": { return "boolean"; } case "bigint": { return "bigint"; } case "function": { return "funkce"; } case "symbol": { return "symbol"; } case "undefined": { return "undefined"; } case "object": { if (Array.isArray(data)) { return "pole"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "regul\xE1rn\xED v\xFDraz", email: "e-mailov\xE1 adresa", 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: "datum a \u010Das ve form\xE1tu ISO", date: "datum ve form\xE1tu ISO", time: "\u010Das ve form\xE1tu ISO", duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", jwt: "JWT", template_literal: "vstup" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${issue2.expected}, obdr\u017Eeno ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`; return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`; } return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`; } return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; if (_issue.format === "includes") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; if (_issue.format === "regex") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; return `Neplatn\xFD form\xE1t ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`; case "unrecognized_keys": return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`; case "invalid_union": return "Neplatn\xFD vstup"; case "invalid_element": return `Neplatn\xE1 hodnota v ${issue2.origin}`; default: return `Neplatn\xFD vstup`; } }; }; function cs_default() { return { localeError: error5() }; } // node_modules/zod/v4/locales/de.js var error6 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, set: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "Zahl"; } case "object": { if (Array.isArray(data)) { return "Array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "Eingabe", email: "E-Mail-Adresse", 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-Datum und -Uhrzeit", date: "ISO-Datum", time: "ISO-Uhrzeit", duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", jwt: "JWT", template_literal: "Eingabe" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Ung\xFCltige Eingabe: erwartet ${issue2.expected}, erhalten ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`; return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`; } return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; if (_issue.format === "ends_with") return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; if (_issue.format === "includes") return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; if (_issue.format === "regex") return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; return `Ung\xFCltig: ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`; case "invalid_union": return "Ung\xFCltige Eingabe"; case "invalid_element": return `Ung\xFCltiger Wert in ${issue2.origin}`; default: return `Ung\xFCltige Eingabe`; } }; }; function de_default() { return { localeError: error6() }; } // node_modules/zod/v4/locales/en.js var parsedType = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; var error7 = () => { 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" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const Nouns = { 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", 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" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Invalid string: must start with "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Invalid string: must end with "${_issue.suffix}"`; if (_issue.format === "includes") return `Invalid string: must include "${_issue.includes}"`; if (_issue.format === "regex") return `Invalid string: must match pattern ${_issue.pattern}`; return `Invalid ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Invalid number: must be a multiple of ${issue2.divisor}`; case "unrecognized_keys": return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Invalid key in ${issue2.origin}`; case "invalid_union": return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; default: return `Invalid input`; } }; }; function en_default() { return { localeError: error7() }; } // node_modules/zod/v4/locales/eo.js var parsedType2 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "nombro"; } case "object": { if (Array.isArray(data)) { return "tabelo"; } if (data === null) { return "senvalora"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; var error8 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, set: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const Nouns = { regex: "enigo", email: "retadreso", url: "URL", emoji: "emo\u011Dio", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datotempo", date: "ISO-dato", time: "ISO-tempo", duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", jwt: "JWT", template_literal: "enigo" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Nevalida enigo: atendi\u011Dis ${issue2.expected}, ricevi\u011Dis ${parsedType2(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`; return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`; return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; if (_issue.format === "includes") return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; if (_issue.format === "regex") return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; return `Nevalida ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`; case "unrecognized_keys": return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Nevalida \u015Dlosilo en ${issue2.origin}`; case "invalid_union": return "Nevalida enigo"; case "invalid_element": return `Nevalida valoro en ${issue2.origin}`; default: return `Nevalida enigo`; } }; }; function eo_default() { return { localeError: error8() }; } // node_modules/zod/v4/locales/es.js var error9 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, array: { unit: "elementos", verb: "tener" }, set: { unit: "elementos", verb: "tener" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "n\xFAmero"; } case "object": { if (Array.isArray(data)) { return "arreglo"; } if (data === null) { return "nulo"; } if (Object.getPrototypeOf(data) !== Object.prototype) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "entrada", email: "direcci\xF3n de correo electr\xF3nico", 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: "fecha y hora ISO", date: "fecha ISO", time: "hora ISO", duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Entrada inv\xE1lida: se esperaba ${issue2.expected}, recibido ${parsedType4(issue2.input)}`; // return `Entrada inválida: se esperaba ${issue.expected}, recibido ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`; return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Demasiado grande: se esperaba que ${issue2.origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; return `Demasiado grande: se esperaba que ${issue2.origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Demasiado peque\xF1o: se esperaba que ${issue2.origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Demasiado peque\xF1o: se esperaba que ${issue2.origin} fuera ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; if (_issue.format === "includes") return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; return `Inv\xE1lido ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`; case "unrecognized_keys": return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Llave inv\xE1lida en ${issue2.origin}`; case "invalid_union": return "Entrada inv\xE1lida"; case "invalid_element": return `Valor inv\xE1lido en ${issue2.origin}`; default: return `Entrada inv\xE1lida`; } }; }; function es_default() { return { localeError: error9() }; } // node_modules/zod/v4/locales/fa.js var error10 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F"; } case "object": { if (Array.isArray(data)) { return "\u0622\u0631\u0627\u06CC\u0647"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u0648\u0631\u0648\u062F\u06CC", email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", url: "URL", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${parsedType4(issue2.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; case "invalid_value": if (issue2.values.length === 1) { return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; } return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; } return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; } return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; } if (_issue.format === "ends_with") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; } if (_issue.format === "includes") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; } if (_issue.format === "regex") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; } return `${Nouns[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; } case "not_multiple_of": return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`; case "unrecognized_keys": return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`; case "invalid_union": return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; case "invalid_element": return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`; default: return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; } }; }; function fa_default() { return { localeError: error10() }; } // node_modules/zod/v4/locales/fi.js var error11 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "s\xE4\xE4nn\xF6llinen lauseke", email: "s\xE4hk\xF6postiosoite", url: "URL-osoite", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-aikaleima", date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", time: "ISO-aika", duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", jwt: "JWT", template_literal: "templaattimerkkijono" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Virheellinen tyyppi: odotettiin ${issue2.expected}, oli ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`; return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim(); } return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim(); } return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; if (_issue.format === "includes") return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; if (_issue.format === "regex") { return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; } return `Virheellinen ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return "Virheellinen avain tietueessa"; case "invalid_union": return "Virheellinen unioni"; case "invalid_element": return "Virheellinen arvo joukossa"; default: return `Virheellinen sy\xF6te`; } }; }; function fi_default() { return { localeError: error11() }; } // node_modules/zod/v4/locales/fr.js var error12 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "nombre"; } case "object": { if (Array.isArray(data)) { return "tableau"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "entr\xE9e", email: "adresse e-mail", 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: "date et heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Entr\xE9e invalide : ${issue2.expected} attendu, ${parsedType4(issue2.input)} re\xE7u`; case "invalid_value": if (issue2.values.length === 1) return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`; return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Trop grand : ${issue2.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`; return `Trop grand : ${issue2.origin ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; case "unrecognized_keys": return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Cl\xE9 invalide dans ${issue2.origin}`; case "invalid_union": return "Entr\xE9e invalide"; case "invalid_element": return `Valeur invalide dans ${issue2.origin}`; default: return `Entr\xE9e invalide`; } }; }; function fr_default() { return { localeError: error12() }; } // node_modules/zod/v4/locales/fr-CA.js var error13 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "entr\xE9e", email: "adresse courriel", 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: "date-heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Entr\xE9e invalide : attendu ${issue2.expected}, re\xE7u ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`; return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "\u2264" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`; return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? "\u2265" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; case "unrecognized_keys": return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Cl\xE9 invalide dans ${issue2.origin}`; case "invalid_union": return "Entr\xE9e invalide"; case "invalid_element": return `Valeur invalide dans ${issue2.origin}`; default: return `Entr\xE9e invalide`; } }; }; function fr_CA_default() { return { localeError: error13() }; } // node_modules/zod/v4/locales/he.js var error14 = () => { const Sizable = { string: { unit: "\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u05E7\u05DC\u05D8", email: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", url: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", emoji: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", date: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", time: "\u05D6\u05DE\u05DF ISO", duration: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", ipv4: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", ipv6: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", cidrv4: "\u05D8\u05D5\u05D5\u05D7 IPv4", cidrv6: "\u05D8\u05D5\u05D5\u05D7 IPv6", base64: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", base64url: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", json_string: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", e164: "\u05DE\u05E1\u05E4\u05E8 E.164", jwt: "JWT", template_literal: "\u05E7\u05DC\u05D8" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${parsedType4(issue2.input)}`; // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${stringifyPrimitive(issue2.values[0])}`; return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${issue2.origin ?? "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${issue2.origin ?? "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue2.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue2.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; if (_issue.format === "regex") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue2.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; } case "not_multiple_of": return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`; case "unrecognized_keys": return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue2.origin}`; case "invalid_union": return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; case "invalid_element": return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue2.origin}`; default: return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; } }; }; function he_default() { return { localeError: error14() }; } // node_modules/zod/v4/locales/hu.js var error15 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, set: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "sz\xE1m"; } case "object": { if (Array.isArray(data)) { return "t\xF6mb"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "bemenet", email: "email c\xEDm", 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 id\u0151b\xE9lyeg", date: "ISO d\xE1tum", time: "ISO id\u0151", duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", jwt: "JWT", template_literal: "bemenet" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${issue2.expected}, a kapott \xE9rt\xE9k ${parsedType4(issue2.input)}`; // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`; return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`; return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; if (_issue.format === "ends_with") return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; if (_issue.format === "includes") return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; if (_issue.format === "regex") return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; return `\xC9rv\xE9nytelen ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; case "unrecognized_keys": return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`; case "invalid_union": return "\xC9rv\xE9nytelen bemenet"; case "invalid_element": return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`; default: return `\xC9rv\xE9nytelen bemenet`; } }; }; function hu_default() { return { localeError: error15() }; } // node_modules/zod/v4/locales/id.js var error16 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, set: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "input", email: "alamat email", 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: "tanggal dan waktu format ISO", date: "tanggal format ISO", time: "jam format ISO", duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", jwt: "JWT", template_literal: "input" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Input tidak valid: diharapkan ${issue2.expected}, diterima ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`; return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; if (_issue.format === "ends_with") return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; if (_issue.format === "includes") return `String tidak valid: harus menyertakan "${_issue.includes}"`; if (_issue.format === "regex") return `String tidak valid: harus sesuai pola ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue2.format} tidak valid`; } case "not_multiple_of": return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`; case "unrecognized_keys": return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Kunci tidak valid di ${issue2.origin}`; case "invalid_union": return "Input tidak valid"; case "invalid_element": return `Nilai tidak valid di ${issue2.origin}`; default: return `Input tidak valid`; } }; }; function id_default() { return { localeError: error16() }; } // node_modules/zod/v4/locales/it.js var error17 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, set: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "numero"; } case "object": { if (Array.isArray(data)) { return "vettore"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "input", email: "indirizzo email", 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: "data e ora ISO", date: "data ISO", time: "ora ISO", duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", jwt: "JWT", template_literal: "input" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Input non valido: atteso ${issue2.expected}, ricevuto ${parsedType4(issue2.input)}`; // return `Input non valido: atteso ${issue.expected}, ricevuto ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`; return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`; return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Stringa non valida: deve terminare con "${_issue.suffix}"`; if (_issue.format === "includes") return `Stringa non valida: deve includere "${_issue.includes}"`; if (_issue.format === "regex") return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; return `Invalid ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`; case "unrecognized_keys": return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Chiave non valida in ${issue2.origin}`; case "invalid_union": return "Input non valido"; case "invalid_element": return `Valore non valido in ${issue2.origin}`; default: return `Input non valido`; } }; }; function it_default() { return { localeError: error17() }; } // node_modules/zod/v4/locales/ja.js var error18 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "\u6570\u5024"; } case "object": { if (Array.isArray(data)) { return "\u914D\u5217"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u5165\u529B\u5024", email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", url: "URL", emoji: "\u7D75\u6587\u5B57", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u6642", date: "ISO\u65E5\u4ED8", time: "ISO\u6642\u523B", duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u7121\u52B9\u306A\u5165\u529B: ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${parsedType4(issue2.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; case "invalid_value": if (issue2.values.length === 1) return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; case "too_big": { const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; const sizing = getSizing(issue2.origin); if (sizing) return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; } case "too_small": { const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; const sizing = getSizing(issue2.origin); if (sizing) return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "ends_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "includes") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "regex") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u7121\u52B9\u306A${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; case "unrecognized_keys": return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`; case "invalid_key": return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; case "invalid_union": return "\u7121\u52B9\u306A\u5165\u529B"; case "invalid_element": return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; default: return `\u7121\u52B9\u306A\u5165\u529B`; } }; }; function ja_default() { return { localeError: error18() }; } // node_modules/zod/v4/locales/kh.js var error19 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)" : "\u179B\u17C1\u1781"; } case "object": { if (Array.isArray(data)) { return "\u17A2\u17B6\u179A\u17C1 (Array)"; } if (data === null) { return "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", url: "URL", emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", time: "\u1798\u17C9\u17C4\u1784 ISO", duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`; return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`; return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; if (_issue.format === "regex") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`; case "unrecognized_keys": return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; case "invalid_union": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; case "invalid_element": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; default: return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; } }; }; function kh_default() { return { localeError: error19() }; } // node_modules/zod/v4/locales/ko.js var error20 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, set: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\uC785\uB825", email: "\uC774\uBA54\uC77C \uC8FC\uC18C", url: "URL", emoji: "\uC774\uBAA8\uC9C0", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", date: "ISO \uB0A0\uC9DC", time: "ISO \uC2DC\uAC04", duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", jwt: "JWT", template_literal: "\uC785\uB825" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${parsedType4(issue2.input)}\uC785\uB2C8\uB2E4`; case "invalid_value": if (issue2.values.length === 1) return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; case "too_big": { const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; const sizing = getSizing(issue2.origin); const unit = sizing?.unit ?? "\uC694\uC18C"; if (sizing) return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`; return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`; } case "too_small": { const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; const sizing = getSizing(issue2.origin); const unit = sizing?.unit ?? "\uC694\uC18C"; if (sizing) { return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`; } return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; } if (_issue.format === "ends_with") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; if (_issue.format === "includes") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; if (_issue.format === "regex") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; return `\uC798\uBABB\uB41C ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; case "unrecognized_keys": return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`; case "invalid_union": return `\uC798\uBABB\uB41C \uC785\uB825`; case "invalid_element": return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`; default: return `\uC798\uBABB\uB41C \uC785\uB825`; } }; }; function ko_default() { return { localeError: error20() }; } // node_modules/zod/v4/locales/mk.js var error21 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0431\u0440\u043E\u0458"; } case "object": { if (Array.isArray(data)) { return "\u043D\u0438\u0437\u0430"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u0432\u043D\u0435\u0441", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", url: "URL", emoji: "\u0435\u043C\u043E\u045F\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", date: "ISO \u0434\u0430\u0442\u0443\u043C", time: "ISO \u0432\u0440\u0435\u043C\u0435", duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${parsedType4(issue2.input)}`; // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; return `Invalid ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`; case "invalid_union": return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; case "invalid_element": return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`; default: return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; } }; }; function mk_default() { return { localeError: error21() }; } // node_modules/zod/v4/locales/ms.js var error22 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, set: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "nombor"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "input", email: "alamat e-mel", 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: "tarikh masa ISO", date: "tarikh ISO", time: "masa ISO", duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", jwt: "JWT", template_literal: "input" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Input tidak sah: dijangka ${issue2.expected}, diterima ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`; return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; if (_issue.format === "ends_with") return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; if (_issue.format === "includes") return `String tidak sah: mesti mengandungi "${_issue.includes}"`; if (_issue.format === "regex") return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue2.format} tidak sah`; } case "not_multiple_of": return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`; case "unrecognized_keys": return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Kunci tidak sah dalam ${issue2.origin}`; case "invalid_union": return "Input tidak sah"; case "invalid_element": return `Nilai tidak sah dalam ${issue2.origin}`; default: return `Input tidak sah`; } }; }; function ms_default() { return { localeError: error22() }; } // node_modules/zod/v4/locales/nl.js var error23 = () => { const Sizable = { string: { unit: "tekens" }, file: { unit: "bytes" }, array: { unit: "elementen" }, set: { unit: "elementen" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "getal"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "invoer", email: "emailadres", 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 datum en tijd", date: "ISO datum", time: "ISO tijd", duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", jwt: "JWT", template_literal: "invoer" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Ongeldige invoer: verwacht ${issue2.expected}, ontving ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`; return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Te lang: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} bevat`; return `Te lang: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Te kort: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} bevat`; } return `Te kort: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; } if (_issue.format === "ends_with") return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; if (_issue.format === "includes") return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; if (_issue.format === "regex") return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; return `Ongeldig: ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`; case "unrecognized_keys": return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ongeldige key in ${issue2.origin}`; case "invalid_union": return "Ongeldige invoer"; case "invalid_element": return `Ongeldige waarde in ${issue2.origin}`; default: return `Ongeldige invoer`; } }; }; function nl_default() { return { localeError: error23() }; } // node_modules/zod/v4/locales/no.js var error24 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, set: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "tall"; } case "object": { if (Array.isArray(data)) { return "liste"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "input", email: "e-postadresse", 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 dato- og klokkeslett", date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", ipv4: "IPv4-omr\xE5de", ipv6: "IPv6-omr\xE5de", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Ugyldig input: forventet ${issue2.expected}, fikk ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`; return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; if (_issue.format === "regex") return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; return `Ugyldig ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ugyldig n\xF8kkel i ${issue2.origin}`; case "invalid_union": return "Ugyldig input"; case "invalid_element": return `Ugyldig verdi i ${issue2.origin}`; default: return `Ugyldig input`; } }; }; function no_default() { return { localeError: error24() }; } // node_modules/zod/v4/locales/ota.js var error25 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "numara"; } case "object": { if (Array.isArray(data)) { return "saf"; } if (data === null) { return "gayb"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "giren", email: "epostag\xE2h", 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 heng\xE2m\u0131", date: "ISO tarihi", time: "ISO zaman\u0131", duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "giren" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `F\xE2sit giren: umulan ${issue2.expected}, al\u0131nan ${parsedType4(issue2.input)}`; // return `Fâsit giren: umulan ${issue.expected}, alınan ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`; return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`; return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; } return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; if (_issue.format === "ends_with") return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; if (_issue.format === "includes") return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; if (_issue.format === "regex") return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; return `F\xE2sit ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`; case "unrecognized_keys": return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`; case "invalid_union": return "Giren tan\u0131namad\u0131."; case "invalid_element": return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; default: return `K\u0131ymet tan\u0131namad\u0131.`; } }; }; function ota_default() { return { localeError: error25() }; } // node_modules/zod/v4/locales/ps.js var error26 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F"; } case "object": { if (Array.isArray(data)) { return "\u0627\u0631\u06D0"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u0648\u0631\u0648\u062F\u064A", email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", date: "\u0646\u06D0\u067C\u0647", time: "\u0648\u062E\u062A", duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${parsedType4(issue2.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; case "invalid_value": if (issue2.values.length === 1) { return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`; } return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; } return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; } return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; } if (_issue.format === "ends_with") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; } if (_issue.format === "includes") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; } if (_issue.format === "regex") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; } return `${Nouns[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; } case "not_multiple_of": return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; case "unrecognized_keys": return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; case "invalid_union": return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; case "invalid_element": return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; default: return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; } }; }; function ps_default() { return { localeError: error26() }; } // node_modules/zod/v4/locales/pl.js var error27 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, set: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "liczba"; } case "object": { if (Array.isArray(data)) { return "tablica"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "wyra\u017Cenie", email: "adres email", 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: "data i godzina w formacie ISO", date: "data w formacie ISO", time: "godzina w formacie ISO", duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", jwt: "JWT", template_literal: "wej\u015Bcie" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${issue2.expected}, otrzymano ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`; return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`; } return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`; } return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; if (_issue.format === "includes") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; if (_issue.format === "regex") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; return `Nieprawid\u0142ow(y/a/e) ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`; case "unrecognized_keys": return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Nieprawid\u0142owy klucz w ${issue2.origin}`; case "invalid_union": return "Nieprawid\u0142owe dane wej\u015Bciowe"; case "invalid_element": return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`; default: return `Nieprawid\u0142owe dane wej\u015Bciowe`; } }; }; function pl_default() { return { localeError: error27() }; } // node_modules/zod/v4/locales/pt.js var error28 = () => { const Sizable = { string: { unit: "caracteres", verb: "ter" }, file: { unit: "bytes", verb: "ter" }, array: { unit: "itens", verb: "ter" }, set: { unit: "itens", verb: "ter" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "n\xFAmero"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "nulo"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "padr\xE3o", email: "endere\xE7o de e-mail", 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: "data e hora ISO", date: "data ISO", time: "hora ISO", duration: "dura\xE7\xE3o ISO", ipv4: "endere\xE7o IPv4", ipv6: "endere\xE7o IPv6", cidrv4: "faixa de IPv4", cidrv6: "faixa de IPv6", base64: "texto codificado em base64", base64url: "URL codificada em base64", json_string: "texto JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Tipo inv\xE1lido: esperado ${issue2.expected}, recebido ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; case "unrecognized_keys": return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Chave inv\xE1lida em ${issue2.origin}`; case "invalid_union": return "Entrada inv\xE1lida"; case "invalid_element": return `Valor inv\xE1lido em ${issue2.origin}`; default: return `Campo inv\xE1lido`; } }; }; function pt_default() { return { localeError: error28() }; } // node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; const lastTwoDigits = absCount % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { return many; } if (lastDigit === 1) { return one; } if (lastDigit >= 2 && lastDigit <= 4) { return few; } return many; } var error29 = () => { const Sizable = { string: { unit: { one: "\u0441\u0438\u043C\u0432\u043E\u043B", few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u0430", many: "\u0431\u0430\u0439\u0442" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E"; } case "object": { if (Array.isArray(data)) { return "\u043C\u0430\u0441\u0441\u0438\u0432"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u0432\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0435\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0432\u0440\u0435\u043C\u044F", duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { const maxValue = Number(issue2.maximum); const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`; } return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { const minValue = Number(issue2.minimum); const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`; } return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; case "invalid_union": return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; case "invalid_element": return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`; default: return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; } }; }; function ru_default() { return { localeError: error29() }; } // node_modules/zod/v4/locales/sl.js var error30 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, set: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0161tevilo"; } case "object": { if (Array.isArray(data)) { return "tabela"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "vnos", email: "e-po\u0161tni naslov", 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 datum in \u010Das", date: "ISO datum", time: "ISO \u010Das", duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", jwt: "JWT", template_literal: "vnos" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Neveljaven vnos: pri\u010Dakovano ${issue2.expected}, prejeto ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`; return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`; return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; if (_issue.format === "includes") return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; if (_issue.format === "regex") return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; return `Neveljaven ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`; case "unrecognized_keys": return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Neveljaven klju\u010D v ${issue2.origin}`; case "invalid_union": return "Neveljaven vnos"; case "invalid_element": return `Neveljavna vrednost v ${issue2.origin}`; default: return "Neveljaven vnos"; } }; }; function sl_default() { return { localeError: error30() }; } // node_modules/zod/v4/locales/sv.js var error31 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, set: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "antal"; } case "object": { if (Array.isArray(data)) { return "lista"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "regulj\xE4rt uttryck", email: "e-postadress", 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-datum och tid", date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", ipv4: "IPv4-intervall", ipv6: "IPv6-intervall", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", jwt: "JWT", template_literal: "mall-literal" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Ogiltig inmatning: f\xF6rv\xE4ntat ${issue2.expected}, fick ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`; return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; } return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; if (_issue.format === "regex") return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; return `Ogiltig(t) ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`; case "invalid_union": return "Ogiltig input"; case "invalid_element": return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`; default: return `Ogiltig input`; } }; }; function sv_default() { return { localeError: error31() }; } // node_modules/zod/v4/locales/ta.js var error32 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1" : "\u0B8E\u0BA3\u0BCD"; } case "object": { if (Array.isArray(data)) { return "\u0B85\u0BA3\u0BBF"; } if (data === null) { return "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", 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 \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", jwt: "JWT", template_literal: "input" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`; return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "ends_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "includes") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "regex") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; case "unrecognized_keys": return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; case "invalid_union": return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; case "invalid_element": return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; default: return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; } }; }; function ta_default() { return { localeError: error32() }; } // node_modules/zod/v4/locales/th.js var error33 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)" : "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02"; } case "object": { if (Array.isArray(data)) { return "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)"; } if (data === null) { return "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", url: "URL", emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`; return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; if (_issue.format === "regex") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; case "unrecognized_keys": return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; case "invalid_union": return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; case "invalid_element": return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; default: return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; } }; }; function th_default() { return { localeError: error33() }; } // node_modules/zod/v4/locales/tr.js var parsedType3 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; var error34 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const Nouns = { regex: "girdi", email: "e-posta adresi", 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 tarih ve saat", date: "ISO tarih", time: "ISO saat", duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `Ge\xE7ersiz de\u011Fer: beklenen ${issue2.expected}, al\u0131nan ${parsedType3(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`; return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`; return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; if (_issue.format === "ends_with") return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; if (_issue.format === "includes") return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; if (_issue.format === "regex") return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; return `Ge\xE7ersiz ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`; case "unrecognized_keys": return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`; case "invalid_union": return "Ge\xE7ersiz de\u011Fer"; case "invalid_element": return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; default: return `Ge\xE7ersiz de\u011Fer`; } }; }; function tr_default() { return { localeError: error34() }; } // node_modules/zod/v4/locales/ua.js var error35 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E"; } case "object": { if (Array.isArray(data)) { return "\u043C\u0430\u0441\u0438\u0432"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", url: "URL", emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", date: "\u0434\u0430\u0442\u0430 ISO", time: "\u0447\u0430\u0441 ISO", duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${parsedType4(issue2.input)}`; // return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; case "invalid_union": return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; case "invalid_element": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`; default: return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; } }; }; function ua_default() { return { localeError: error35() }; } // node_modules/zod/v4/locales/ur.js var error36 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0646\u0645\u0628\u0631"; } case "object": { if (Array.isArray(data)) { return "\u0622\u0631\u06D2"; } if (data === null) { return "\u0646\u0644"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u0627\u0646 \u067E\u0679", email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${parsedType4(issue2.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; case "invalid_value": if (issue2.values.length === 1) return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; } return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; } if (_issue.format === "ends_with") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; if (_issue.format === "includes") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; if (_issue.format === "regex") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; return `\u063A\u0644\u0637 ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; case "unrecognized_keys": return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; case "invalid_key": return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; case "invalid_union": return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; case "invalid_element": return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; default: return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; } }; }; function ur_default() { return { localeError: error36() }; } // node_modules/zod/v4/locales/vi.js var error37 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "s\u1ED1"; } case "object": { if (Array.isArray(data)) { return "m\u1EA3ng"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u0111\u1EA7u v\xE0o", email: "\u0111\u1ECBa ch\u1EC9 email", 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: "ng\xE0y gi\u1EDD ISO", date: "ng\xE0y ISO", time: "gi\u1EDD ISO", duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`; return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`; return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; if (_issue.format === "includes") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; if (_issue.format === "regex") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`; } case "not_multiple_of": return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`; case "unrecognized_keys": return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; case "invalid_union": return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; case "invalid_element": return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; default: return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; } }; }; function vi_default() { return { localeError: error37() }; } // node_modules/zod/v4/locales/zh-CN.js var error38 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, set: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "\u975E\u6570\u5B57(NaN)" : "\u6570\u5B57"; } case "object": { if (Array.isArray(data)) { return "\u6570\u7EC4"; } if (data === null) { return "\u7A7A\u503C(null)"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u8F93\u5165", email: "\u7535\u5B50\u90AE\u4EF6", url: "URL", emoji: "\u8868\u60C5\u7B26\u53F7", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u671F\u65F6\u95F4", date: "ISO\u65E5\u671F", time: "ISO\u65F6\u95F4", duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", jwt: "JWT", template_literal: "\u8F93\u5165" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`; return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`; return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; if (_issue.format === "ends_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; if (_issue.format === "includes") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; if (_issue.format === "regex") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; return `\u65E0\u6548${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`; case "unrecognized_keys": return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; case "invalid_union": return "\u65E0\u6548\u8F93\u5165"; case "invalid_element": return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; default: return `\u65E0\u6548\u8F93\u5165`; } }; }; function zh_CN_default() { return { localeError: error38() }; } // node_modules/zod/v4/locales/zh-TW.js var error39 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType4 = (data) => { const t4 = typeof data; switch (t4) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t4; }; const Nouns = { regex: "\u8F38\u5165", email: "\u90F5\u4EF6\u5730\u5740", 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 \u65E5\u671F\u6642\u9593", date: "ISO \u65E5\u671F", time: "ISO \u6642\u9593", duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", jwt: "JWT", template_literal: "\u8F38\u5165" }; return (issue2) => { switch (issue2.code) { case "invalid_type": return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${parsedType4(issue2.input)}`; case "invalid_value": if (issue2.values.length === 1) return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`; return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`; return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; } if (_issue.format === "ends_with") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; if (_issue.format === "includes") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; if (_issue.format === "regex") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; return `\u7121\u6548\u7684 ${Nouns[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`; case "unrecognized_keys": return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`; case "invalid_key": return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; case "invalid_union": return "\u7121\u6548\u7684\u8F38\u5165\u503C"; case "invalid_element": return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; default: return `\u7121\u6548\u7684\u8F38\u5165\u503C`; } }; }; function zh_TW_default() { return { localeError: error39() }; } // node_modules/zod/v4/core/registries.js var $output = /* @__PURE__ */ Symbol("ZodOutput"); var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new Map(); this._idmap = /* @__PURE__ */ new Map(); } add(schema, ..._meta) { const meta = _meta[0]; this._map.set(schema, meta); if (meta && typeof meta === "object" && "id" in meta) { if (this._idmap.has(meta.id)) { throw new Error(`ID ${meta.id} already exists in the registry`); } this._idmap.set(meta.id, schema); } return this; } clear() { this._map = /* @__PURE__ */ new Map(); this._idmap = /* @__PURE__ */ new Map(); return this; } remove(schema) { const meta = this._map.get(schema); if (meta && typeof meta === "object" && "id" in meta) { this._idmap.delete(meta.id); } this._map.delete(schema); return this; } get(schema) { const p2 = schema._zod.parent; if (p2) { const pm = { ...this.get(p2) ?? {} }; delete pm.id; return { ...pm, ...this._map.get(schema) }; } return this._map.get(schema); } has(schema) { return this._map.has(schema); } }; function registry() { return new $ZodRegistry(); } var globalRegistry = /* @__PURE__ */ registry(); // node_modules/zod/v4/core/api.js function _string(Class2, params) { return new Class2({ type: "string", ...normalizeParams(params) }); } function _coercedString(Class2, params) { return new Class2({ type: "string", coerce: true, ...normalizeParams(params) }); } function _email(Class2, params) { return new Class2({ type: "string", format: "email", check: "string_format", abort: false, ...normalizeParams(params) }); } function _guid(Class2, params) { return new Class2({ type: "string", format: "guid", check: "string_format", abort: false, ...normalizeParams(params) }); } function _uuid(Class2, params) { return new Class2({ type: "string", format: "uuid", check: "string_format", abort: false, ...normalizeParams(params) }); } function _uuidv4(Class2, params) { return new Class2({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v4", ...normalizeParams(params) }); } function _uuidv6(Class2, params) { return new Class2({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v6", ...normalizeParams(params) }); } function _uuidv7(Class2, params) { return new Class2({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v7", ...normalizeParams(params) }); } function _url(Class2, params) { return new Class2({ type: "string", format: "url", check: "string_format", abort: false, ...normalizeParams(params) }); } function _emoji2(Class2, params) { return new Class2({ type: "string", format: "emoji", check: "string_format", abort: false, ...normalizeParams(params) }); } function _nanoid(Class2, params) { return new Class2({ type: "string", format: "nanoid", check: "string_format", abort: false, ...normalizeParams(params) }); } function _cuid(Class2, params) { return new Class2({ type: "string", format: "cuid", check: "string_format", abort: false, ...normalizeParams(params) }); } function _cuid2(Class2, params) { return new Class2({ type: "string", format: "cuid2", check: "string_format", abort: false, ...normalizeParams(params) }); } function _ulid(Class2, params) { return new Class2({ type: "string", format: "ulid", check: "string_format", abort: false, ...normalizeParams(params) }); } function _xid(Class2, params) { return new Class2({ type: "string", format: "xid", check: "string_format", abort: false, ...normalizeParams(params) }); } function _ksuid(Class2, params) { return new Class2({ type: "string", format: "ksuid", check: "string_format", abort: false, ...normalizeParams(params) }); } function _ipv4(Class2, params) { return new Class2({ type: "string", format: "ipv4", check: "string_format", abort: false, ...normalizeParams(params) }); } function _ipv6(Class2, params) { return new Class2({ type: "string", format: "ipv6", check: "string_format", abort: false, ...normalizeParams(params) }); } function _cidrv4(Class2, params) { return new Class2({ type: "string", format: "cidrv4", check: "string_format", abort: false, ...normalizeParams(params) }); } function _cidrv6(Class2, params) { return new Class2({ type: "string", format: "cidrv6", check: "string_format", abort: false, ...normalizeParams(params) }); } function _base64(Class2, params) { return new Class2({ type: "string", format: "base64", check: "string_format", abort: false, ...normalizeParams(params) }); } function _base64url(Class2, params) { return new Class2({ type: "string", format: "base64url", check: "string_format", abort: false, ...normalizeParams(params) }); } function _e164(Class2, params) { return new Class2({ type: "string", format: "e164", check: "string_format", abort: false, ...normalizeParams(params) }); } function _jwt(Class2, params) { return new Class2({ type: "string", format: "jwt", check: "string_format", abort: false, ...normalizeParams(params) }); } var TimePrecision = { Any: null, Minute: -1, Second: 0, Millisecond: 3, Microsecond: 6 }; function _isoDateTime(Class2, params) { return new Class2({ type: "string", format: "datetime", check: "string_format", offset: false, local: false, precision: null, ...normalizeParams(params) }); } function _isoDate(Class2, params) { return new Class2({ type: "string", format: "date", check: "string_format", ...normalizeParams(params) }); } function _isoTime(Class2, params) { return new Class2({ type: "string", format: "time", check: "string_format", precision: null, ...normalizeParams(params) }); } function _isoDuration(Class2, params) { return new Class2({ type: "string", format: "duration", check: "string_format", ...normalizeParams(params) }); } function _number(Class2, params) { return new Class2({ type: "number", checks: [], ...normalizeParams(params) }); } function _coercedNumber(Class2, params) { return new Class2({ type: "number", coerce: true, checks: [], ...normalizeParams(params) }); } function _int(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "safeint", ...normalizeParams(params) }); } function _float32(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "float32", ...normalizeParams(params) }); } function _float64(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "float64", ...normalizeParams(params) }); } function _int32(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "int32", ...normalizeParams(params) }); } function _uint32(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "uint32", ...normalizeParams(params) }); } function _boolean(Class2, params) { return new Class2({ type: "boolean", ...normalizeParams(params) }); } function _coercedBoolean(Class2, params) { return new Class2({ type: "boolean", coerce: true, ...normalizeParams(params) }); } function _bigint(Class2, params) { return new Class2({ type: "bigint", ...normalizeParams(params) }); } function _coercedBigint(Class2, params) { return new Class2({ type: "bigint", coerce: true, ...normalizeParams(params) }); } function _int64(Class2, params) { return new Class2({ type: "bigint", check: "bigint_format", abort: false, format: "int64", ...normalizeParams(params) }); } function _uint64(Class2, params) { return new Class2({ type: "bigint", check: "bigint_format", abort: false, format: "uint64", ...normalizeParams(params) }); } function _symbol(Class2, params) { return new Class2({ type: "symbol", ...normalizeParams(params) }); } function _undefined2(Class2, params) { return new Class2({ type: "undefined", ...normalizeParams(params) }); } function _null2(Class2, params) { return new Class2({ type: "null", ...normalizeParams(params) }); } function _any(Class2) { return new Class2({ type: "any" }); } function _unknown(Class2) { return new Class2({ type: "unknown" }); } function _never(Class2, params) { return new Class2({ type: "never", ...normalizeParams(params) }); } function _void(Class2, params) { return new Class2({ type: "void", ...normalizeParams(params) }); } function _date(Class2, params) { return new Class2({ type: "date", ...normalizeParams(params) }); } function _coercedDate(Class2, params) { return new Class2({ type: "date", coerce: true, ...normalizeParams(params) }); } function _nan(Class2, params) { return new Class2({ type: "nan", ...normalizeParams(params) }); } function _lt(value, params) { return new $ZodCheckLessThan({ check: "less_than", ...normalizeParams(params), value, inclusive: false }); } function _lte(value, params) { return new $ZodCheckLessThan({ check: "less_than", ...normalizeParams(params), value, inclusive: true }); } function _gt(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", ...normalizeParams(params), value, inclusive: false }); } function _gte(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", ...normalizeParams(params), value, inclusive: true }); } function _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(value, params) { return new $ZodCheckMultipleOf({ check: "multiple_of", ...normalizeParams(params), value }); } 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 ch2 = new $ZodCheckMaxLength({ check: "max_length", ...normalizeParams(params), maximum }); return ch2; } 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 _array(Class2, element, params) { return new Class2({ type: "array", element, // get element() { // return element; // }, ...normalizeParams(params) }); } function _union(Class2, options, params) { return new Class2({ type: "union", options, ...normalizeParams(params) }); } function _discriminatedUnion(Class2, discriminator, options, params) { return new Class2({ type: "union", options, discriminator, ...normalizeParams(params) }); } function _intersection(Class2, left, right) { return new Class2({ type: "intersection", left, right }); } function _tuple(Class2, items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new Class2({ type: "tuple", items, rest, ...normalizeParams(params) }); } function _record(Class2, keyType, valueType, params) { return new Class2({ type: "record", keyType, valueType, ...normalizeParams(params) }); } function _map(Class2, keyType, valueType, params) { return new Class2({ type: "map", keyType, valueType, ...normalizeParams(params) }); } function _set(Class2, valueType, params) { return new Class2({ type: "set", valueType, ...normalizeParams(params) }); } function _enum(Class2, values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v2) => [v2, v2])) : values; return new Class2({ type: "enum", entries, ...normalizeParams(params) }); } function _nativeEnum(Class2, entries, params) { return new Class2({ type: "enum", entries, ...normalizeParams(params) }); } function _literal(Class2, value, params) { return new Class2({ type: "literal", values: Array.isArray(value) ? value : [value], ...normalizeParams(params) }); } function _file(Class2, params) { return new Class2({ type: "file", ...normalizeParams(params) }); } function _transform(Class2, fn2) { return new Class2({ type: "transform", transform: fn2 }); } function _optional(Class2, innerType) { return new Class2({ type: "optional", innerType }); } function _nullable(Class2, innerType) { return new Class2({ type: "nullable", innerType }); } function _default(Class2, innerType, defaultValue) { return new Class2({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : defaultValue; } }); } function _nonoptional(Class2, innerType, params) { return new Class2({ type: "nonoptional", innerType, ...normalizeParams(params) }); } function _success(Class2, innerType) { return new Class2({ type: "success", innerType }); } function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } function _pipe(Class2, in_, out) { return new Class2({ type: "pipe", in: in_, out }); } function _readonly(Class2, innerType) { return new Class2({ type: "readonly", innerType }); } function _templateLiteral(Class2, parts, params) { return new Class2({ type: "template_literal", parts, ...normalizeParams(params) }); } function _lazy(Class2, getter) { return new Class2({ type: "lazy", getter }); } function _promise(Class2, innerType) { return new Class2({ type: "promise", innerType }); } function _custom(Class2, fn2, _params) { const norm = normalizeParams(_params); norm.abort ?? (norm.abort = true); const schema = new Class2({ type: "custom", check: "custom", fn: fn2, ...norm }); return schema; } function _refine(Class2, fn2, _params) { const schema = new Class2({ type: "custom", check: "custom", fn: fn2, ...normalizeParams(_params) }); return schema; } 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 (params.case !== "sensitive") { truthyArray = truthyArray.map((v2) => typeof v2 === "string" ? v2.toLowerCase() : v2); falsyArray = falsyArray.map((v2) => typeof v2 === "string" ? v2.toLowerCase() : v2); } const truthySet = new Set(truthyArray); const falsySet = new Set(falsyArray); const _Pipe = Classes.Pipe ?? $ZodPipe; const _Boolean = Classes.Boolean ?? $ZodBoolean; const _String = Classes.String ?? $ZodString; const _Transform = Classes.Transform ?? $ZodTransform; const tx = new _Transform({ type: "transform", transform: (input, payload) => { let data = input; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { return true; } else if (falsySet.has(data)) { return false; } else { payload.issues.push({ code: "invalid_value", expected: "stringbool", values: [...truthySet, ...falsySet], input: payload.value, inst: tx }); return {}; } }, error: params.error }); const innerPipe = new _Pipe({ type: "pipe", in: new _String({ type: "string", error: params.error }), out: tx, error: params.error }); const outerPipe = new _Pipe({ type: "pipe", in: innerPipe, out: new _Boolean({ type: "boolean", error: params.error }), error: params.error }); return outerPipe; } function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { ...normalizeParams(_params), check: "string_format", type: "string", format, fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), ...params }; if (fnOrRegex instanceof RegExp) { def.pattern = fnOrRegex; } const inst = new Class2(def); return inst; } // node_modules/zod/v4/core/function.js var $ZodFunction = class { constructor(def) { this._def = def; this.def = def; } implement(func) { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } const impl = ((...args) => { const parsedArgs = this._def.input ? parse(this._def.input, args, void 0, { callee: impl }) : args; if (!Array.isArray(parsedArgs)) { throw new Error("Invalid arguments schema: not an array or tuple schema."); } const output = func(...parsedArgs); return this._def.output ? parse(this._def.output, output, void 0, { callee: impl }) : output; }); return impl; } implementAsync(func) { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } const impl = (async (...args) => { const parsedArgs = this._def.input ? await parseAsync(this._def.input, args, void 0, { callee: impl }) : args; if (!Array.isArray(parsedArgs)) { throw new Error("Invalid arguments schema: not an array or tuple schema."); } const output = await func(...parsedArgs); return this._def.output ? parseAsync(this._def.output, output, void 0, { callee: impl }) : output; }); return impl; } input(...args) { const F2 = this.constructor; if (Array.isArray(args[0])) { return new F2({ type: "function", input: new $ZodTuple({ type: "tuple", items: args[0], rest: args[1] }), output: this._def.output }); } return new F2({ type: "function", input: args[0], output: this._def.output }); } output(output) { const F2 = this.constructor; return new F2({ type: "function", input: this._def.input, output }); } }; function _function(params) { return new $ZodFunction({ type: "function", input: Array.isArray(params?.input) ? _tuple($ZodTuple, params?.input) : params?.input ?? _array($ZodArray, _unknown($ZodUnknown)), output: params?.output ?? _unknown($ZodUnknown) }); } // node_modules/zod/v4/core/to-json-schema.js var JSONSchemaGenerator = class { constructor(params) { this.counter = 0; this.metadataRegistry = params?.metadata ?? globalRegistry; this.target = params?.target ?? "draft-2020-12"; this.unrepresentable = params?.unrepresentable ?? "throw"; this.override = params?.override ?? (() => { }); this.io = params?.io ?? "output"; this.seen = /* @__PURE__ */ new Map(); } process(schema, _params = { path: [], schemaPath: [] }) { var _a25; const def = schema._zod.def; const formatMap = { guid: "uuid", url: "uri", datetime: "date-time", json_string: "json-string", regex: "" // do not set }; const seen = this.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 }; this.seen.set(schema, result); const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; } else { const params = { ..._params, schemaPath: [..._params.schemaPath, schema], path: _params.path }; const parent = schema._zod.parent; if (parent) { result.ref = parent; this.process(parent, params); this.seen.get(parent).isParent = true; } else { const _json = result.schema; switch (def.type) { case "string": { const json3 = _json; json3.type = "string"; const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; if (typeof minimum === "number") json3.minLength = minimum; if (typeof maximum === "number") json3.maxLength = maximum; if (format) { json3.format = formatMap[format] ?? format; if (json3.format === "") delete json3.format; } if (contentEncoding) json3.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { const regexes = [...patterns]; if (regexes.length === 1) json3.pattern = regexes[0].source; else if (regexes.length > 1) { result.schema.allOf = [ ...regexes.map((regex) => ({ ...this.target === "draft-7" ? { type: "string" } : {}, pattern: regex.source })) ]; } } break; } case "number": { const json3 = _json; const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; if (typeof format === "string" && format.includes("int")) json3.type = "integer"; else json3.type = "number"; if (typeof exclusiveMinimum === "number") json3.exclusiveMinimum = exclusiveMinimum; if (typeof minimum === "number") { json3.minimum = minimum; if (typeof exclusiveMinimum === "number") { if (exclusiveMinimum >= minimum) delete json3.minimum; else delete json3.exclusiveMinimum; } } if (typeof exclusiveMaximum === "number") json3.exclusiveMaximum = exclusiveMaximum; if (typeof maximum === "number") { json3.maximum = maximum; if (typeof exclusiveMaximum === "number") { if (exclusiveMaximum <= maximum) delete json3.maximum; else delete json3.exclusiveMaximum; } } if (typeof multipleOf === "number") json3.multipleOf = multipleOf; break; } case "boolean": { const json3 = _json; json3.type = "boolean"; break; } case "bigint": { if (this.unrepresentable === "throw") { throw new Error("BigInt cannot be represented in JSON Schema"); } break; } case "symbol": { if (this.unrepresentable === "throw") { throw new Error("Symbols cannot be represented in JSON Schema"); } break; } case "null": { _json.type = "null"; break; } case "any": { break; } case "unknown": { break; } case "undefined": { if (this.unrepresentable === "throw") { throw new Error("Undefined cannot be represented in JSON Schema"); } break; } case "void": { if (this.unrepresentable === "throw") { throw new Error("Void cannot be represented in JSON Schema"); } break; } case "never": { _json.not = {}; break; } case "date": { if (this.unrepresentable === "throw") { throw new Error("Date cannot be represented in JSON Schema"); } break; } case "array": { const json3 = _json; const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; json3.type = "array"; json3.items = this.process(def.element, { ...params, path: [...params.path, "items"] }); break; } case "object": { const json3 = _json; json3.type = "object"; json3.properties = {}; const shape = def.shape; for (const key in shape) { json3.properties[key] = this.process(shape[key], { ...params, path: [...params.path, "properties", key] }); } const allKeys = new Set(Object.keys(shape)); const requiredKeys = new Set([...allKeys].filter((key) => { const v2 = def.shape[key]._zod; if (this.io === "input") { return v2.optin === void 0; } else { return v2.optout === void 0; } })); if (requiredKeys.size > 0) { json3.required = Array.from(requiredKeys); } if (def.catchall?._zod.def.type === "never") { json3.additionalProperties = false; } else if (!def.catchall) { if (this.io === "output") json3.additionalProperties = false; } else if (def.catchall) { json3.additionalProperties = this.process(def.catchall, { ...params, path: [...params.path, "additionalProperties"] }); } break; } case "union": { const json3 = _json; json3.anyOf = def.options.map((x4, i4) => this.process(x4, { ...params, path: [...params.path, "anyOf", i4] })); break; } case "intersection": { const json3 = _json; const a3 = this.process(def.left, { ...params, path: [...params.path, "allOf", 0] }); const b5 = this.process(def.right, { ...params, path: [...params.path, "allOf", 1] }); const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; const allOf = [ ...isSimpleIntersection(a3) ? a3.allOf : [a3], ...isSimpleIntersection(b5) ? b5.allOf : [b5] ]; json3.allOf = allOf; break; } case "tuple": { const json3 = _json; json3.type = "array"; const prefixItems = def.items.map((x4, i4) => this.process(x4, { ...params, path: [...params.path, "prefixItems", i4] })); if (this.target === "draft-2020-12") { json3.prefixItems = prefixItems; } else { json3.items = prefixItems; } if (def.rest) { const rest = this.process(def.rest, { ...params, path: [...params.path, "items"] }); if (this.target === "draft-2020-12") { json3.items = rest; } else { json3.additionalItems = rest; } } if (def.rest) { json3.items = this.process(def.rest, { ...params, path: [...params.path, "items"] }); } const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json3.minItems = minimum; if (typeof maximum === "number") json3.maxItems = maximum; break; } case "record": { const json3 = _json; json3.type = "object"; json3.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] }); json3.additionalProperties = this.process(def.valueType, { ...params, path: [...params.path, "additionalProperties"] }); break; } case "map": { if (this.unrepresentable === "throw") { throw new Error("Map cannot be represented in JSON Schema"); } break; } case "set": { if (this.unrepresentable === "throw") { throw new Error("Set cannot be represented in JSON Schema"); } break; } case "enum": { const json3 = _json; const values = getEnumValues(def.entries); if (values.every((v2) => typeof v2 === "number")) json3.type = "number"; if (values.every((v2) => typeof v2 === "string")) json3.type = "string"; json3.enum = values; break; } case "literal": { const json3 = _json; const vals = []; for (const val of def.values) { if (val === void 0) { if (this.unrepresentable === "throw") { throw new Error("Literal `undefined` cannot be represented in JSON Schema"); } else { } } else if (typeof val === "bigint") { if (this.unrepresentable === "throw") { throw new Error("BigInt literals cannot be represented in JSON Schema"); } else { vals.push(Number(val)); } } else { vals.push(val); } } if (vals.length === 0) { } else if (vals.length === 1) { const val = vals[0]; json3.type = val === null ? "null" : typeof val; json3.const = val; } else { if (vals.every((v2) => typeof v2 === "number")) json3.type = "number"; if (vals.every((v2) => typeof v2 === "string")) json3.type = "string"; if (vals.every((v2) => typeof v2 === "boolean")) json3.type = "string"; if (vals.every((v2) => v2 === null)) json3.type = "null"; json3.enum = vals; } break; } case "file": { const json3 = _json; const file2 = { type: "string", format: "binary", contentEncoding: "binary" }; const { minimum, maximum, mime } = schema._zod.bag; if (minimum !== void 0) file2.minLength = minimum; if (maximum !== void 0) file2.maxLength = maximum; if (mime) { if (mime.length === 1) { file2.contentMediaType = mime[0]; Object.assign(json3, file2); } else { json3.anyOf = mime.map((m3) => { const mFile = { ...file2, contentMediaType: m3 }; return mFile; }); } } else { Object.assign(json3, file2); } break; } case "transform": { if (this.unrepresentable === "throw") { throw new Error("Transforms cannot be represented in JSON Schema"); } break; } case "nullable": { const inner = this.process(def.innerType, params); _json.anyOf = [inner, { type: "null" }]; break; } case "nonoptional": { this.process(def.innerType, params); result.ref = def.innerType; break; } case "success": { const json3 = _json; json3.type = "boolean"; break; } case "default": { this.process(def.innerType, params); result.ref = def.innerType; _json.default = JSON.parse(JSON.stringify(def.defaultValue)); break; } case "prefault": { this.process(def.innerType, params); result.ref = def.innerType; if (this.io === "input") _json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); break; } case "catch": { this.process(def.innerType, params); result.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { throw new Error("Dynamic catch values are not supported in JSON Schema"); } _json.default = catchValue; break; } case "nan": { if (this.unrepresentable === "throw") { throw new Error("NaN cannot be represented in JSON Schema"); } break; } case "template_literal": { const json3 = _json; const pattern = schema._zod.pattern; if (!pattern) throw new Error("Pattern not found in template literal"); json3.type = "string"; json3.pattern = pattern.source; break; } case "pipe": { const innerType = this.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; this.process(innerType, params); result.ref = innerType; break; } case "readonly": { this.process(def.innerType, params); result.ref = def.innerType; _json.readOnly = true; break; } // passthrough types case "promise": { this.process(def.innerType, params); result.ref = def.innerType; break; } case "optional": { this.process(def.innerType, params); result.ref = def.innerType; break; } case "lazy": { const innerType = schema._zod.innerType; this.process(innerType, params); result.ref = innerType; break; } case "custom": { if (this.unrepresentable === "throw") { throw new Error("Custom types cannot be represented in JSON Schema"); } break; } default: { def; } } } } const meta = this.metadataRegistry.get(schema); if (meta) Object.assign(result.schema, meta); if (this.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; } if (this.io === "input" && result.schema._prefault) (_a25 = result.schema).default ?? (_a25.default = result.schema._prefault); delete result.schema._prefault; const _result = this.seen.get(schema); return _result.schema; } emit(schema, _params) { const params = { cycles: _params?.cycles ?? "ref", reused: _params?.reused ?? "inline", // unrepresentable: _params?.unrepresentable ?? "throw", // uri: _params?.uri ?? ((id) => `${id}`), external: _params?.external ?? void 0 }; const root = this.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); const makeURI = (entry) => { const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; if (params.external) { const externalId = params.external.registry.get(entry[0])?.id; const uriGenerator = params.external.uri ?? ((id2) => id2); if (externalId) { return { ref: uriGenerator(externalId) }; } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`; entry[1].defId = id; return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; } if (entry[1] === root) { return { ref: "#" }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; const defId = entry[1].schema.id ?? `__schema${this.counter++}`; return { defId, ref: defUriPrefix + defId }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { return; } const seen = entry[1]; const { ref, defId } = makeURI(entry); seen.def = { ...seen.schema }; if (defId) seen.defId = defId; const schema2 = seen.schema; for (const key in schema2) { delete schema2[key]; } schema2.$ref = ref; }; if (params.cycles === "throw") { for (const entry of this.seen.entries()) { const seen = entry[1]; if (seen.cycle) { throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); } } } for (const entry of this.seen.entries()) { const seen = entry[1]; if (schema === entry[0]) { extractToDef(entry); continue; } if (params.external) { const ext = params.external.registry.get(entry[0])?.id; if (schema !== entry[0] && ext) { extractToDef(entry); continue; } } const id = this.metadataRegistry.get(entry[0])?.id; if (id) { extractToDef(entry); continue; } if (seen.cycle) { extractToDef(entry); continue; } if (seen.count > 1) { if (params.reused === "ref") { extractToDef(entry); continue; } } } const flattenRef = (zodSchema2, params2) => { const seen = this.seen.get(zodSchema2); const schema2 = seen.def ?? seen.schema; const _cached = { ...schema2 }; if (seen.ref === null) { return; } const ref = seen.ref; seen.ref = null; if (ref) { flattenRef(ref, params2); const refSchema = this.seen.get(ref).schema; if (refSchema.$ref && params2.target === "draft-7") { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { Object.assign(schema2, refSchema); Object.assign(schema2, _cached); } } if (!seen.isParent) this.override({ zodSchema: zodSchema2, jsonSchema: schema2, path: seen.path ?? [] }); }; for (const entry of [...this.seen.entries()].reverse()) { flattenRef(entry[0], { target: this.target }); } const result = {}; if (this.target === "draft-2020-12") { result.$schema = "https://json-schema.org/draft/2020-12/schema"; } else if (this.target === "draft-7") { result.$schema = "http://json-schema.org/draft-07/schema#"; } else { console.warn(`Invalid target: ${this.target}`); } if (params.external?.uri) { const id = params.external.registry.get(schema)?.id; if (!id) throw new Error("Schema is missing an `id` property"); result.$id = params.external.uri(id); } Object.assign(result, root.def); const defs = params.external?.defs ?? {}; for (const entry of this.seen.entries()) { const seen = entry[1]; if (seen.def && seen.defId) { defs[seen.defId] = seen.def; } } if (params.external) { } else { if (Object.keys(defs).length > 0) { if (this.target === "draft-2020-12") { result.$defs = defs; } else { result.definitions = defs; } } } try { return JSON.parse(JSON.stringify(result)); } catch (_err) { throw new Error("Error converting schema to JSON."); } } }; function toJSONSchema(input, _params) { if (input instanceof $ZodRegistry) { const gen2 = new JSONSchemaGenerator(_params); const defs = {}; for (const entry of input._idmap.entries()) { const [_2, schema] = entry; gen2.process(schema); } const schemas = {}; const external = { registry: input, uri: _params?.uri, defs }; for (const entry of input._idmap.entries()) { const [key, schema] = entry; schemas[key] = gen2.emit(schema, { ..._params, external }); } if (Object.keys(defs).length > 0) { const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions"; schemas.__shared = { [defsSegment]: defs }; } return { schemas }; } const gen = new JSONSchemaGenerator(_params); gen.process(input); return gen.emit(input, _params); } function isTransforming(_schema, _ctx) { const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; if (ctx.seen.has(_schema)) return false; ctx.seen.add(_schema); const schema = _schema; const def = schema._zod.def; switch (def.type) { case "string": case "number": case "bigint": case "boolean": case "date": case "symbol": case "undefined": case "null": case "any": case "unknown": case "never": case "void": case "literal": case "enum": case "nan": case "file": case "template_literal": return false; case "array": { return isTransforming(def.element, ctx); } case "object": { for (const key in def.shape) { if (isTransforming(def.shape[key], ctx)) return true; } return false; } case "union": { for (const option of def.options) { if (isTransforming(option, ctx)) return true; } return false; } case "intersection": { return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); } case "tuple": { for (const item of def.items) { if (isTransforming(item, ctx)) return true; } if (def.rest && isTransforming(def.rest, ctx)) return true; return false; } case "record": { return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } case "map": { return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } case "set": { return isTransforming(def.valueType, ctx); } // inner types case "promise": case "optional": case "nonoptional": case "nullable": case "readonly": return isTransforming(def.innerType, ctx); case "lazy": return isTransforming(def.getter(), ctx); case "default": { return isTransforming(def.innerType, ctx); } case "prefault": { return isTransforming(def.innerType, ctx); } case "custom": { return false; } case "transform": { return true; } case "pipe": { return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); } case "success": { return false; } case "catch": { return false; } default: def; } throw new Error(`Unknown schema type: ${def.type}`); } // node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; // node_modules/zod/v4/classic/iso.js var iso_exports = {}; __export(iso_exports, { ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, date: () => date2, datetime: () => datetime2, duration: () => duration2, time: () => time2 }); var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { $ZodISODateTime.init(inst, def); ZodStringFormat.init(inst, def); }); function datetime2(params) { return _isoDateTime(ZodISODateTime, params); } var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { $ZodISODate.init(inst, def); ZodStringFormat.init(inst, def); }); function date2(params) { return _isoDate(ZodISODate, params); } var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { $ZodISOTime.init(inst, def); ZodStringFormat.init(inst, def); }); function time2(params) { return _isoTime(ZodISOTime, params); } var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { $ZodISODuration.init(inst, def); ZodStringFormat.init(inst, def); }); function duration2(params) { return _isoDuration(ZodISODuration, params); } // node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; Object.defineProperties(inst, { format: { value: (mapper) => formatError(inst, mapper) // enumerable: false, }, flatten: { value: (mapper) => flattenError(inst, mapper) // enumerable: false, }, addIssue: { value: (issue2) => inst.issues.push(issue2) // enumerable: false, }, addIssues: { value: (issues2) => inst.issues.push(...issues2) // enumerable: false, }, isEmpty: { get() { return inst.issues.length === 0; } // enumerable: false, } }); }; var ZodError = $constructor("ZodError", initializer2); var ZodRealError = $constructor("ZodError", initializer2, { Parent: Error }); // node_modules/zod/v4/classic/parse.js var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); // node_modules/zod/v4/classic/schemas.js var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { $ZodType.init(inst, def); inst.def = def; Object.defineProperty(inst, "_def", { value: def }); inst.check = (...checks) => { return inst.clone( { ...def, checks: [ ...def.checks ?? [], ...checks.map((ch2) => typeof ch2 === "function" ? { _zod: { check: ch2, def: { check: "custom" }, onattach: [] } } : ch2) ] } // { parent: true } ); }; inst.clone = (def2, params) => clone(inst, def2, params); inst.brand = () => inst; inst.register = ((reg, meta) => { reg.add(inst, meta); return inst; }); inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); inst.safeParse = (data, params) => safeParse2(inst, data, params); inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); inst.spa = inst.safeParseAsync; inst.refine = (check2, params) => inst.check(refine(check2, params)); inst.superRefine = (refinement) => inst.check(superRefine(refinement)); inst.overwrite = (fn2) => inst.check(_overwrite(fn2)); inst.optional = () => optional(inst); inst.nullable = () => nullable(inst); inst.nullish = () => optional(nullable(inst)); inst.nonoptional = (params) => nonoptional(inst, params); inst.array = () => array(inst); inst.or = (arg) => union([inst, arg]); inst.and = (arg) => intersection(inst, arg); inst.transform = (tx) => pipe(inst, transform(tx)); inst.default = (def2) => _default2(inst, def2); inst.prefault = (def2) => prefault(inst, def2); inst.catch = (params) => _catch2(inst, params); inst.pipe = (target) => pipe(inst, target); inst.readonly = () => readonly(inst); inst.describe = (description) => { const cl = inst.clone(); globalRegistry.add(cl, { description }); return cl; }; Object.defineProperty(inst, "description", { get() { return globalRegistry.get(inst)?.description; }, configurable: true }); inst.meta = (...args) => { if (args.length === 0) { return globalRegistry.get(inst); } const cl = inst.clone(); globalRegistry.add(cl, args[0]); return cl; }; inst.isOptional = () => inst.safeParse(void 0).success; inst.isNullable = () => inst.safeParse(null).success; return inst; }); var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { $ZodString.init(inst, def); ZodType.init(inst, def); const bag = inst._zod.bag; inst.format = bag.format ?? null; inst.minLength = bag.minimum ?? null; inst.maxLength = bag.maximum ?? null; inst.regex = (...args) => inst.check(_regex(...args)); inst.includes = (...args) => inst.check(_includes(...args)); inst.startsWith = (...args) => inst.check(_startsWith(...args)); inst.endsWith = (...args) => inst.check(_endsWith(...args)); inst.min = (...args) => inst.check(_minLength(...args)); inst.max = (...args) => inst.check(_maxLength(...args)); inst.length = (...args) => inst.check(_length(...args)); inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); inst.lowercase = (params) => inst.check(_lowercase(params)); inst.uppercase = (params) => inst.check(_uppercase(params)); inst.trim = () => inst.check(_trim()); inst.normalize = (...args) => inst.check(_normalize(...args)); inst.toLowerCase = () => inst.check(_toLowerCase()); inst.toUpperCase = () => inst.check(_toUpperCase()); }); var 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(_emoji2(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(datetime2(params)); inst.date = (params) => inst.check(date2(params)); inst.time = (params) => inst.check(time2(params)); inst.duration = (params) => inst.check(duration2(params)); }); function string2(params) { return _string(ZodString, params); } var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); }); function email2(params) { return _email(ZodEmail, params); } var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { $ZodGUID.init(inst, def); ZodStringFormat.init(inst, def); }); function guid2(params) { return _guid(ZodGUID, params); } var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { $ZodUUID.init(inst, def); ZodStringFormat.init(inst, def); }); function uuid2(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); } var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { $ZodURL.init(inst, def); ZodStringFormat.init(inst, def); }); function url(params) { return _url(ZodURL, params); } var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { $ZodEmoji.init(inst, def); ZodStringFormat.init(inst, def); }); function emoji2(params) { return _emoji2(ZodEmoji, params); } var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { $ZodNanoID.init(inst, def); ZodStringFormat.init(inst, def); }); function nanoid2(params) { return _nanoid(ZodNanoID, params); } var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { $ZodCUID.init(inst, def); ZodStringFormat.init(inst, def); }); function cuid3(params) { return _cuid(ZodCUID, params); } var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { $ZodCUID2.init(inst, def); ZodStringFormat.init(inst, def); }); function cuid22(params) { return _cuid2(ZodCUID2, params); } var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { $ZodULID.init(inst, def); ZodStringFormat.init(inst, def); }); function ulid2(params) { return _ulid(ZodULID, params); } var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { $ZodXID.init(inst, def); ZodStringFormat.init(inst, def); }); function xid2(params) { return _xid(ZodXID, params); } var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { $ZodKSUID.init(inst, def); ZodStringFormat.init(inst, def); }); function ksuid2(params) { return _ksuid(ZodKSUID, params); } var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { $ZodIPv4.init(inst, def); ZodStringFormat.init(inst, def); }); function ipv42(params) { return _ipv4(ZodIPv4, params); } var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { $ZodIPv6.init(inst, def); ZodStringFormat.init(inst, def); }); function ipv62(params) { return _ipv6(ZodIPv6, params); } var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { $ZodCIDRv4.init(inst, def); ZodStringFormat.init(inst, def); }); function cidrv42(params) { return _cidrv4(ZodCIDRv4, params); } var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { $ZodCIDRv6.init(inst, def); ZodStringFormat.init(inst, def); }); function cidrv62(params) { return _cidrv6(ZodCIDRv6, params); } var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { $ZodBase64.init(inst, def); ZodStringFormat.init(inst, def); }); function base642(params) { return _base64(ZodBase64, params); } var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { $ZodBase64URL.init(inst, def); ZodStringFormat.init(inst, def); }); function base64url2(params) { return _base64url(ZodBase64URL, params); } var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { $ZodE164.init(inst, def); ZodStringFormat.init(inst, def); }); function e1642(params) { return _e164(ZodE164, params); } var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); }); function jwt(params) { return _jwt(ZodJWT, params); } var 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); } var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { $ZodNumber.init(inst, def); ZodType.init(inst, def); inst.gt = (value, params) => inst.check(_gt(value, params)); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); inst.lt = (value, params) => inst.check(_lt(value, params)); inst.lte = (value, params) => inst.check(_lte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); inst.int = (params) => inst.check(int(params)); inst.safe = (params) => inst.check(int(params)); inst.positive = (params) => inst.check(_gt(0, params)); inst.nonnegative = (params) => inst.check(_gte(0, params)); inst.negative = (params) => inst.check(_lt(0, params)); inst.nonpositive = (params) => inst.check(_lte(0, params)); inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); inst.step = (value, params) => inst.check(_multipleOf(value, params)); inst.finite = () => inst; const bag = inst._zod.bag; inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); inst.isFinite = true; inst.format = bag.format ?? null; }); function number2(params) { return _number(ZodNumber, params); } var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { $ZodNumberFormat.init(inst, def); ZodNumber.init(inst, def); }); function 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); } var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { $ZodBoolean.init(inst, def); ZodType.init(inst, def); }); function boolean2(params) { return _boolean(ZodBoolean, params); } var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { $ZodBigInt.init(inst, def); ZodType.init(inst, def); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); inst.gt = (value, params) => inst.check(_gt(value, params)); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); inst.lt = (value, params) => inst.check(_lt(value, params)); inst.lte = (value, params) => inst.check(_lte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); inst.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 = (value, params) => inst.check(_multipleOf(value, params)); const bag = inst._zod.bag; inst.minValue = bag.minimum ?? null; inst.maxValue = bag.maximum ?? null; inst.format = bag.format ?? null; }); function bigint2(params) { return _bigint(ZodBigInt, params); } var 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); } var ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { $ZodSymbol.init(inst, def); ZodType.init(inst, def); }); function symbol(params) { return _symbol(ZodSymbol, params); } var ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { $ZodUndefined.init(inst, def); ZodType.init(inst, def); }); function _undefined3(params) { return _undefined2(ZodUndefined, params); } var ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { $ZodNull.init(inst, def); ZodType.init(inst, def); }); function _null3(params) { return _null2(ZodNull, params); } var ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { $ZodAny.init(inst, def); ZodType.init(inst, def); }); function any() { return _any(ZodAny); } var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { $ZodUnknown.init(inst, def); ZodType.init(inst, def); }); function unknown() { return _unknown(ZodUnknown); } var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { $ZodNever.init(inst, def); ZodType.init(inst, def); }); function never(params) { return _never(ZodNever, params); } var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { $ZodVoid.init(inst, def); ZodType.init(inst, def); }); function _void2(params) { return _void(ZodVoid, params); } var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { $ZodDate.init(inst, def); ZodType.init(inst, def); inst.min = (value, params) => inst.check(_gte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); const c2 = inst._zod.bag; inst.minDate = c2.minimum ? new Date(c2.minimum) : null; inst.maxDate = c2.maximum ? new Date(c2.maximum) : null; }); function date3(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { $ZodArray.init(inst, def); ZodType.init(inst, def); inst.element = def.element; inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); inst.nonempty = (params) => inst.check(_minLength(1, params)); inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); inst.length = (len, params) => inst.check(_length(len, params)); inst.unwrap = () => inst.element; }); function array(element, params) { return _array(ZodArray, element, params); } function keyof(schema) { const shape = schema._zod.def.shape; return literal(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { $ZodObject.init(inst, def); ZodType.init(inst, def); util_exports.defineLazy(inst, "shape", () => def.shape); inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape)); inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); inst.extend = (incoming) => { return util_exports.extend(inst, incoming); }; inst.merge = (other) => util_exports.merge(inst, other); inst.pick = (mask) => util_exports.pick(inst, mask); inst.omit = (mask) => util_exports.omit(inst, mask); inst.partial = (...args) => util_exports.partial(ZodOptional, inst, args[0]); inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); }); function object(shape, params) { const def = { type: "object", get shape() { util_exports.assignProp(this, "shape", { ...shape }); return this.shape; }, ...util_exports.normalizeParams(params) }; return new ZodObject(def); } function strictObject(shape, params) { return new ZodObject({ type: "object", get shape() { util_exports.assignProp(this, "shape", { ...shape }); return this.shape; }, catchall: never(), ...util_exports.normalizeParams(params) }); } function looseObject(shape, params) { return new ZodObject({ type: "object", get shape() { util_exports.assignProp(this, "shape", { ...shape }); return this.shape; }, catchall: unknown(), ...util_exports.normalizeParams(params) }); } var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { $ZodUnion.init(inst, def); ZodType.init(inst, def); inst.options = def.options; }); function union(options, params) { return new ZodUnion({ type: "union", options, ...util_exports.normalizeParams(params) }); } var ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { ZodUnion.init(inst, def); $ZodDiscriminatedUnion.init(inst, def); }); function discriminatedUnion(discriminator, options, params) { return new ZodDiscriminatedUnion({ type: "union", options, discriminator, ...util_exports.normalizeParams(params) }); } var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { $ZodIntersection.init(inst, def); ZodType.init(inst, def); }); function intersection(left, right) { return new ZodIntersection({ type: "intersection", left, right }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { $ZodTuple.init(inst, def); ZodType.init(inst, def); inst.rest = (rest) => inst.clone({ ...inst._zod.def, 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, rest, ...util_exports.normalizeParams(params) }); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { $ZodRecord.init(inst, def); ZodType.init(inst, def); inst.keyType = def.keyType; inst.valueType = def.valueType; }); function record(keyType, valueType, params) { return new ZodRecord({ type: "record", keyType, valueType, ...util_exports.normalizeParams(params) }); } function partialRecord(keyType, valueType, params) { return new ZodRecord({ type: "record", keyType: union([keyType, never()]), valueType, ...util_exports.normalizeParams(params) }); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { $ZodMap.init(inst, def); ZodType.init(inst, def); inst.keyType = def.keyType; inst.valueType = def.valueType; }); function map(keyType, valueType, params) { return new ZodMap({ type: "map", keyType, valueType, ...util_exports.normalizeParams(params) }); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { $ZodSet.init(inst, def); ZodType.init(inst, def); 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 set(valueType, params) { return new ZodSet({ type: "set", valueType, ...util_exports.normalizeParams(params) }); } var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { $ZodEnum.init(inst, def); ZodType.init(inst, def); inst.enum = def.entries; inst.options = Object.values(def.entries); const keys = new Set(Object.keys(def.entries)); inst.extract = (values, params) => { const newEntries = {}; for (const value of values) { if (keys.has(value)) { newEntries[value] = def.entries[value]; } else throw new Error(`Key ${value} not found in enum`); } return new ZodEnum({ ...def, checks: [], ...util_exports.normalizeParams(params), entries: newEntries }); }; inst.exclude = (values, params) => { const newEntries = { ...def.entries }; for (const value of values) { if (keys.has(value)) { delete newEntries[value]; } else throw new Error(`Key ${value} not found in enum`); } return new ZodEnum({ ...def, checks: [], ...util_exports.normalizeParams(params), entries: newEntries }); }; }); function _enum2(values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v2) => [v2, v2])) : values; return new ZodEnum({ type: "enum", entries, ...util_exports.normalizeParams(params) }); } function nativeEnum(entries, params) { return new ZodEnum({ type: "enum", entries, ...util_exports.normalizeParams(params) }); } var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { $ZodLiteral.init(inst, def); ZodType.init(inst, def); inst.values = new Set(def.values); Object.defineProperty(inst, "value", { get() { if (def.values.length > 1) { throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); } return def.values[0]; } }); }); function literal(value, params) { return new ZodLiteral({ type: "literal", values: Array.isArray(value) ? value : [value], ...util_exports.normalizeParams(params) }); } var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { $ZodFile.init(inst, def); ZodType.init(inst, def); 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 file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { payload.addIssue = (issue2) => { if (typeof issue2 === "string") { payload.issues.push(util_exports.issue(issue2, payload.value, def)); } else { const _issue = issue2; if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); _issue.input ?? (_issue.input = payload.value); _issue.inst ?? (_issue.inst = inst); _issue.continue ?? (_issue.continue = true); payload.issues.push(util_exports.issue(_issue)); } }; const output = def.transform(payload.value, payload); if (output instanceof Promise) { return output.then((output2) => { payload.value = output2; return payload; }); } payload.value = output; return payload; }; }); function transform(fn2) { return new ZodTransform({ type: "transform", transform: fn2 }); } var ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { $ZodOptional.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function optional(innerType) { return new ZodOptional({ type: "optional", innerType }); } var ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { $ZodNullable.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function nullable(innerType) { return new ZodNullable({ type: "nullable", innerType }); } function nullish2(innerType) { return optional(nullable(innerType)); } var ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { $ZodDefault.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; inst.removeDefault = inst.unwrap; }); function _default2(innerType, defaultValue) { return new ZodDefault({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : defaultValue; } }); } var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { $ZodPrefault.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function prefault(innerType, defaultValue) { return new ZodPrefault({ type: "prefault", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : defaultValue; } }); } var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { $ZodNonOptional.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function nonoptional(innerType, params) { return new ZodNonOptional({ type: "nonoptional", innerType, ...util_exports.normalizeParams(params) }); } var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { $ZodSuccess.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function success(innerType) { return new ZodSuccess({ type: "success", innerType }); } var ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { $ZodCatch.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; inst.removeCatch = inst.unwrap; }); function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { $ZodNaN.init(inst, def); ZodType.init(inst, def); }); function nan(params) { return _nan(ZodNaN, params); } var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { $ZodPipe.init(inst, def); ZodType.init(inst, def); inst.in = def.in; inst.out = def.out; }); function pipe(in_, out) { return new ZodPipe({ type: "pipe", in: in_, out // ...util.normalizeParams(params), }); } var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { $ZodReadonly.init(inst, def); ZodType.init(inst, def); }); function readonly(innerType) { return new ZodReadonly({ type: "readonly", innerType }); } var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { $ZodTemplateLiteral.init(inst, def); ZodType.init(inst, def); }); function templateLiteral(parts, params) { return new ZodTemplateLiteral({ type: "template_literal", parts, ...util_exports.normalizeParams(params) }); } var ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { $ZodLazy.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.getter(); }); function lazy(getter) { return new ZodLazy({ type: "lazy", getter }); } var ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { $ZodPromise.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function promise(innerType) { return new ZodPromise({ type: "promise", innerType }); } var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { $ZodCustom.init(inst, def); ZodType.init(inst, def); }); function check(fn2) { const ch2 = new $ZodCheck({ check: "custom" // ...util.normalizeParams(params), }); ch2._zod.check = fn2; return ch2; } function custom(fn2, _params) { return _custom(ZodCustom, fn2 ?? (() => true), _params); } function refine(fn2, _params = {}) { return _refine(ZodCustom, fn2, _params); } function superRefine(fn2) { const ch2 = check((payload) => { payload.addIssue = (issue2) => { if (typeof issue2 === "string") { payload.issues.push(util_exports.issue(issue2, payload.value, ch2._zod.def)); } else { const _issue = issue2; if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); _issue.input ?? (_issue.input = payload.value); _issue.inst ?? (_issue.inst = ch2); _issue.continue ?? (_issue.continue = !ch2._zod.def.abort); payload.issues.push(util_exports.issue(_issue)); } }; return fn2(payload.value, payload); }); return ch2; } function _instanceof(cls, params = { error: `Input not instance of ${cls.name}` }) { const inst = new ZodCustom({ type: "custom", check: "custom", fn: (data) => data instanceof cls, abort: true, ...util_exports.normalizeParams(params) }); inst._zod.bag.Class = cls; return inst; } var stringbool = (...args) => _stringbool({ Pipe: ZodPipe, Boolean: ZodBoolean, String: ZodString, Transform: ZodTransform }, ...args); function json(params) { const jsonSchema2 = lazy(() => { return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema2), record(string2(), jsonSchema2)]); }); return jsonSchema2; } function preprocess(fn2, schema) { return pipe(transform(fn2), schema); } // node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", too_small: "too_small", invalid_format: "invalid_format", not_multiple_of: "not_multiple_of", unrecognized_keys: "unrecognized_keys", invalid_union: "invalid_union", invalid_key: "invalid_key", invalid_element: "invalid_element", invalid_value: "invalid_value", custom: "custom" }; function setErrorMap(map2) { config({ customError: map2 }); } function getErrorMap() { return config().customError; } // node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, boolean: () => boolean3, date: () => date4, number: () => number3, string: () => string3 }); function string3(params) { return _coercedString(ZodString, params); } function number3(params) { return _coercedNumber(ZodNumber, params); } function boolean3(params) { return _coercedBoolean(ZodBoolean, params); } function bigint3(params) { return _coercedBigint(ZodBigInt, params); } function date4(params) { return _coercedDate(ZodDate, params); } // node_modules/zod/v4/classic/external.js config(en_default()); // node_modules/@modelcontextprotocol/sdk/dist/esm/types.js var LATEST_PROTOCOL_VERSION = "2025-11-25"; var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"]; var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; var JSONRPC_VERSION = "2.0"; var AssertObjectSchema = custom((v2) => v2 !== null && (typeof v2 === "object" || typeof v2 === "function")); var ProgressTokenSchema = union([string2(), number2().int()]); var CursorSchema = string2(); var TaskCreationParamsSchema = looseObject({ /** * Requested duration in milliseconds to retain task from creation. */ ttl: number2().optional(), /** * Time in milliseconds to wait between task status requests. */ pollInterval: number2().optional() }); var TaskMetadataSchema = object({ ttl: number2().optional() }); var RelatedTaskMetadataSchema = object({ taskId: string2() }); var RequestMetaSchema = looseObject({ /** * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. */ progressToken: ProgressTokenSchema.optional(), /** * If specified, this request is related to the provided task. */ [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() }); var BaseRequestParamsSchema = object({ /** * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. */ _meta: RequestMetaSchema.optional() }); var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * If specified, the caller is requesting task-augmented execution for this request. * The request will return a CreateTaskResult immediately, and the actual result can be * retrieved later via tasks/result. * * Task augmentation is subject to capability negotiation - receivers MUST declare support * for task augmentation of specific request types in their capabilities. */ task: TaskMetadataSchema.optional() }); var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; var RequestSchema = object({ method: string2(), params: BaseRequestParamsSchema.loose().optional() }); var NotificationsParamsSchema = object({ /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: RequestMetaSchema.optional() }); var NotificationSchema = object({ method: string2(), params: NotificationsParamsSchema.loose().optional() }); var ResultSchema = looseObject({ /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: RequestMetaSchema.optional() }); var RequestIdSchema = union([string2(), number2().int()]); var JSONRPCRequestSchema = object({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema, ...RequestSchema.shape }).strict(); var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; var JSONRPCNotificationSchema = object({ jsonrpc: literal(JSONRPC_VERSION), ...NotificationSchema.shape }).strict(); var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; var JSONRPCResultResponseSchema = object({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema, result: ResultSchema }).strict(); var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; var ErrorCode; (function(ErrorCode2) { ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed"; ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout"; ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError"; ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest"; ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound"; ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams"; ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError"; ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; })(ErrorCode || (ErrorCode = {})); var JSONRPCErrorResponseSchema = object({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema.optional(), error: object({ /** * The error type that occurred. */ code: number2().int(), /** * A short description of the error. The message SHOULD be limited to a concise single sentence. */ message: string2(), /** * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). */ data: unknown().optional() }) }).strict(); var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; var JSONRPCMessageSchema = union([ JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema ]); var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); var EmptyResultSchema = ResultSchema.strict(); var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The ID of the request to cancel. * * This MUST correspond to the ID of a request previously issued in the same direction. */ requestId: RequestIdSchema.optional(), /** * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. */ reason: string2().optional() }); var CancelledNotificationSchema = NotificationSchema.extend({ method: literal("notifications/cancelled"), params: CancelledNotificationParamsSchema }); var IconSchema = object({ /** * URL or data URI for the icon. */ src: string2(), /** * Optional MIME type for the icon. */ mimeType: string2().optional(), /** * Optional array of strings that specify sizes at which the icon can be used. * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. * * If not provided, the client should assume that the icon can be used at any size. */ sizes: array(string2()).optional(), /** * Optional specifier for the theme this icon is designed for. `light` indicates * the icon is designed to be used with a light background, and `dark` indicates * the icon is designed to be used with a dark background. * * If not provided, the client should assume the icon can be used with any theme. */ theme: _enum2(["light", "dark"]).optional() }); var IconsSchema = object({ /** * Optional set of sized icons that the client can display in a user interface. * * Clients that support rendering icons MUST support at least the following MIME types: * - `image/png` - PNG images (safe, universal compatibility) * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) * * Clients that support rendering icons SHOULD also support: * - `image/svg+xml` - SVG images (scalable but requires security precautions) * - `image/webp` - WebP images (modern, efficient format) */ icons: array(IconSchema).optional() }); var BaseMetadataSchema = object({ /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ name: string2(), /** * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, * even by those unfamiliar with domain-specific terminology. * * If not provided, the name should be used for display (except for Tool, * where `annotations.title` should be given precedence over using `name`, * if present). */ title: string2().optional() }); var ImplementationSchema = BaseMetadataSchema.extend({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, version: string2(), /** * An optional URL of the website for this implementation. */ websiteUrl: string2().optional(), /** * An optional human-readable description of what this implementation does. * * This can be used by clients or servers to provide context about their purpose * and capabilities. For example, a server might describe the types of resources * or tools it provides, while a client might describe its intended use case. */ description: string2().optional() }); var FormElicitationCapabilitySchema = intersection(object({ applyDefaults: boolean2().optional() }), record(string2(), unknown())); var ElicitationCapabilitySchema = preprocess((value) => { if (value && typeof value === "object" && !Array.isArray(value)) { if (Object.keys(value).length === 0) { return { form: {} }; } } return value; }, intersection(object({ form: FormElicitationCapabilitySchema.optional(), url: AssertObjectSchema.optional() }), record(string2(), unknown()).optional())); var ClientTasksCapabilitySchema = looseObject({ /** * Present if the client supports listing tasks. */ list: AssertObjectSchema.optional(), /** * Present if the client supports cancelling tasks. */ cancel: AssertObjectSchema.optional(), /** * Capabilities for task creation on specific request types. */ requests: looseObject({ /** * Task support for sampling requests. */ sampling: looseObject({ createMessage: AssertObjectSchema.optional() }).optional(), /** * Task support for elicitation requests. */ elicitation: looseObject({ create: AssertObjectSchema.optional() }).optional() }).optional() }); var ServerTasksCapabilitySchema = looseObject({ /** * Present if the server supports listing tasks. */ list: AssertObjectSchema.optional(), /** * Present if the server supports cancelling tasks. */ cancel: AssertObjectSchema.optional(), /** * Capabilities for task creation on specific request types. */ requests: looseObject({ /** * Task support for tool requests. */ tools: looseObject({ call: AssertObjectSchema.optional() }).optional() }).optional() }); var ClientCapabilitiesSchema = object({ /** * Experimental, non-standard capabilities that the client supports. */ experimental: record(string2(), AssertObjectSchema).optional(), /** * Present if the client supports sampling from an LLM. */ sampling: object({ /** * Present if the client supports context inclusion via includeContext parameter. * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). */ context: AssertObjectSchema.optional(), /** * Present if the client supports tool use via tools and toolChoice parameters. */ tools: AssertObjectSchema.optional() }).optional(), /** * Present if the client supports eliciting user input. */ elicitation: ElicitationCapabilitySchema.optional(), /** * Present if the client supports listing roots. */ roots: object({ /** * Whether the client supports issuing notifications for changes to the roots list. */ listChanged: boolean2().optional() }).optional(), /** * Present if the client supports task creation. */ tasks: ClientTasksCapabilitySchema.optional(), /** * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name). */ extensions: record(string2(), AssertObjectSchema).optional() }); var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. */ protocolVersion: string2(), capabilities: ClientCapabilitiesSchema, clientInfo: ImplementationSchema }); var InitializeRequestSchema = RequestSchema.extend({ method: literal("initialize"), params: InitializeRequestParamsSchema }); var ServerCapabilitiesSchema = object({ /** * Experimental, non-standard capabilities that the server supports. */ experimental: record(string2(), AssertObjectSchema).optional(), /** * Present if the server supports sending log messages to the client. */ logging: AssertObjectSchema.optional(), /** * Present if the server supports sending completions to the client. */ completions: AssertObjectSchema.optional(), /** * Present if the server offers any prompt templates. */ prompts: object({ /** * Whether this server supports issuing notifications for changes to the prompt list. */ listChanged: boolean2().optional() }).optional(), /** * Present if the server offers any resources to read. */ resources: object({ /** * Whether this server supports clients subscribing to resource updates. */ subscribe: boolean2().optional(), /** * Whether this server supports issuing notifications for changes to the resource list. */ listChanged: boolean2().optional() }).optional(), /** * Present if the server offers any tools to call. */ tools: object({ /** * Whether this server supports issuing notifications for changes to the tool list. */ listChanged: boolean2().optional() }).optional(), /** * Present if the server supports task creation. */ tasks: ServerTasksCapabilitySchema.optional(), /** * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name). */ extensions: record(string2(), AssertObjectSchema).optional() }); var InitializeResultSchema = ResultSchema.extend({ /** * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. */ protocolVersion: string2(), capabilities: ServerCapabilitiesSchema, serverInfo: ImplementationSchema, /** * Instructions describing how to use the server and its features. * * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. */ instructions: string2().optional() }); var InitializedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/initialized"), params: NotificationsParamsSchema.optional() }); var PingRequestSchema = RequestSchema.extend({ method: literal("ping"), params: BaseRequestParamsSchema.optional() }); var ProgressSchema = object({ /** * The progress thus far. This should increase every time progress is made, even if the total is unknown. */ progress: number2(), /** * Total number of items to process (or total progress required), if known. */ total: optional(number2()), /** * An optional message describing the current progress. */ message: optional(string2()) }); var ProgressNotificationParamsSchema = object({ ...NotificationsParamsSchema.shape, ...ProgressSchema.shape, /** * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. */ progressToken: ProgressTokenSchema }); var ProgressNotificationSchema = NotificationSchema.extend({ method: literal("notifications/progress"), params: ProgressNotificationParamsSchema }); var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * An opaque token representing the current pagination position. * If provided, the server should return results starting after this cursor. */ cursor: CursorSchema.optional() }); var PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); var PaginatedResultSchema = ResultSchema.extend({ /** * An opaque token representing the pagination position after the last returned result. * If present, there may be more results available. */ nextCursor: CursorSchema.optional() }); var TaskStatusSchema = _enum2(["working", "input_required", "completed", "failed", "cancelled"]); var TaskSchema = object({ taskId: string2(), status: TaskStatusSchema, /** * Time in milliseconds to keep task results available after completion. * If null, the task has unlimited lifetime until manually cleaned up. */ ttl: union([number2(), _null3()]), /** * ISO 8601 timestamp when the task was created. */ createdAt: string2(), /** * ISO 8601 timestamp when the task was last updated. */ lastUpdatedAt: string2(), pollInterval: optional(number2()), /** * Optional diagnostic message for failed tasks or other status information. */ statusMessage: optional(string2()) }); var CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); var TaskStatusNotificationSchema = NotificationSchema.extend({ method: literal("notifications/tasks/status"), params: TaskStatusNotificationParamsSchema }); var GetTaskRequestSchema = RequestSchema.extend({ method: literal("tasks/get"), params: BaseRequestParamsSchema.extend({ taskId: string2() }) }); var GetTaskResultSchema = ResultSchema.merge(TaskSchema); var GetTaskPayloadRequestSchema = RequestSchema.extend({ method: literal("tasks/result"), params: BaseRequestParamsSchema.extend({ taskId: string2() }) }); var GetTaskPayloadResultSchema = ResultSchema.loose(); var ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); var ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: array(TaskSchema) }); var CancelTaskRequestSchema = RequestSchema.extend({ method: literal("tasks/cancel"), params: BaseRequestParamsSchema.extend({ taskId: string2() }) }); var CancelTaskResultSchema = ResultSchema.merge(TaskSchema); var ResourceContentsSchema = object({ /** * The URI of this resource. */ uri: string2(), /** * The MIME type of this resource, if known. */ mimeType: optional(string2()), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var TextResourceContentsSchema = ResourceContentsSchema.extend({ /** * The text of the item. This must only be set if the item can actually be represented as text (not binary data). */ text: string2() }); var Base64Schema = string2().refine((val) => { try { atob(val); return true; } catch { return false; } }, { message: "Invalid Base64 string" }); var BlobResourceContentsSchema = ResourceContentsSchema.extend({ /** * A base64-encoded string representing the binary data of the item. */ blob: Base64Schema }); var RoleSchema = _enum2(["user", "assistant"]); var AnnotationsSchema = object({ /** * Intended audience(s) for the resource. */ audience: array(RoleSchema).optional(), /** * Importance hint for the resource, from 0 (least) to 1 (most). */ priority: number2().min(0).max(1).optional(), /** * ISO 8601 timestamp for the most recent modification. */ lastModified: iso_exports.datetime({ offset: true }).optional() }); var ResourceSchema = object({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * The URI of this resource. */ uri: string2(), /** * A description of what this resource represents. * * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. */ description: optional(string2()), /** * The MIME type of this resource, if known. */ mimeType: optional(string2()), /** * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. * * This can be used by Hosts to display file sizes and estimate context window usage. */ size: optional(number2()), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: optional(looseObject({})) }); var ResourceTemplateSchema = object({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * A URI template (according to RFC 6570) that can be used to construct resource URIs. */ uriTemplate: string2(), /** * A description of what this template is for. * * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. */ description: optional(string2()), /** * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. */ mimeType: optional(string2()), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: optional(looseObject({})) }); var ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); var ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: array(ResourceSchema) }); var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: array(ResourceTemplateSchema) }); var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. * * @format uri */ uri: string2() }); var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; var ReadResourceRequestSchema = RequestSchema.extend({ method: literal("resources/read"), params: ReadResourceRequestParamsSchema }); var ReadResourceResultSchema = ResultSchema.extend({ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); var ResourceListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/resources/list_changed"), params: NotificationsParamsSchema.optional() }); var SubscribeRequestParamsSchema = ResourceRequestParamsSchema; var SubscribeRequestSchema = RequestSchema.extend({ method: literal("resources/subscribe"), params: SubscribeRequestParamsSchema }); var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; var UnsubscribeRequestSchema = RequestSchema.extend({ method: literal("resources/unsubscribe"), params: UnsubscribeRequestParamsSchema }); var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. */ uri: string2() }); var ResourceUpdatedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/resources/updated"), params: ResourceUpdatedNotificationParamsSchema }); var PromptArgumentSchema = object({ /** * The name of the argument. */ name: string2(), /** * A human-readable description of the argument. */ description: optional(string2()), /** * Whether this argument must be provided. */ required: optional(boolean2()) }); var PromptSchema = object({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * An optional description of what this prompt provides */ description: optional(string2()), /** * A list of arguments to use for templating the prompt. */ arguments: optional(array(PromptArgumentSchema)), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: optional(looseObject({})) }); var ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); var ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema) }); var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The name of the prompt or prompt template. */ name: string2(), /** * Arguments to use for templating the prompt. */ arguments: record(string2(), string2()).optional() }); var GetPromptRequestSchema = RequestSchema.extend({ method: literal("prompts/get"), params: GetPromptRequestParamsSchema }); var TextContentSchema = object({ type: literal("text"), /** * The text content of the message. */ text: string2(), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ImageContentSchema = object({ type: literal("image"), /** * The base64-encoded image data. */ data: Base64Schema, /** * The MIME type of the image. Different providers may support different image types. */ mimeType: string2(), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var AudioContentSchema = object({ type: literal("audio"), /** * The base64-encoded audio data. */ data: Base64Schema, /** * The MIME type of the audio. Different providers may support different audio types. */ mimeType: string2(), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ToolUseContentSchema = object({ type: literal("tool_use"), /** * The name of the tool to invoke. * Must match a tool name from the request's tools array. */ name: string2(), /** * Unique identifier for this tool call. * Used to correlate with ToolResultContent in subsequent messages. */ id: string2(), /** * Arguments to pass to the tool. * Must conform to the tool's inputSchema. */ input: record(string2(), unknown()), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var EmbeddedResourceSchema = object({ type: literal("resource"), resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); var ContentBlockSchema = union([ TextContentSchema, ImageContentSchema, AudioContentSchema, ResourceLinkSchema, EmbeddedResourceSchema ]); var PromptMessageSchema = object({ role: RoleSchema, content: ContentBlockSchema }); var GetPromptResultSchema = ResultSchema.extend({ /** * An optional description for the prompt. */ description: string2().optional(), messages: array(PromptMessageSchema) }); var PromptListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/prompts/list_changed"), params: NotificationsParamsSchema.optional() }); var ToolAnnotationsSchema = object({ /** * A human-readable title for the tool. */ title: string2().optional(), /** * If true, the tool does not modify its environment. * * Default: false */ readOnlyHint: boolean2().optional(), /** * If true, the tool may perform destructive updates to its environment. * If false, the tool performs only additive updates. * * (This property is meaningful only when `readOnlyHint == false`) * * Default: true */ destructiveHint: boolean2().optional(), /** * If true, calling the tool repeatedly with the same arguments * will have no additional effect on the its environment. * * (This property is meaningful only when `readOnlyHint == false`) * * Default: false */ idempotentHint: boolean2().optional(), /** * If true, this tool may interact with an "open world" of external * entities. If false, the tool's domain of interaction is closed. * For example, the world of a web search tool is open, whereas that * of a memory tool is not. * * Default: true */ openWorldHint: boolean2().optional() }); var ToolExecutionSchema = object({ /** * Indicates the tool's preference for task-augmented execution. * - "required": Clients MUST invoke the tool as a task * - "optional": Clients MAY invoke the tool as a task or normal request * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task * * If not present, defaults to "forbidden". */ taskSupport: _enum2(["required", "optional", "forbidden"]).optional() }); var ToolSchema = object({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * A human-readable description of the tool. */ description: string2().optional(), /** * A JSON Schema 2020-12 object defining the expected parameters for the tool. * Must have type: 'object' at the root level per MCP spec. */ inputSchema: object({ type: literal("object"), properties: record(string2(), AssertObjectSchema).optional(), required: array(string2()).optional() }).catchall(unknown()), /** * An optional JSON Schema 2020-12 object defining the structure of the tool's output * returned in the structuredContent field of a CallToolResult. * Must have type: 'object' at the root level per MCP spec. */ outputSchema: object({ type: literal("object"), properties: record(string2(), AssertObjectSchema).optional(), required: array(string2()).optional() }).catchall(unknown()).optional(), /** * Optional additional tool information. */ annotations: ToolAnnotationsSchema.optional(), /** * Execution-related properties for this tool. */ execution: ToolExecutionSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); var ListToolsResultSchema = PaginatedResultSchema.extend({ tools: array(ToolSchema) }); var CallToolResultSchema = ResultSchema.extend({ /** * A list of content objects that represent the result of the tool call. * * If the Tool does not define an outputSchema, this field MUST be present in the result. * For backwards compatibility, this field is always present, but it may be empty. */ content: array(ContentBlockSchema).default([]), /** * An object containing structured tool output. * * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. */ structuredContent: record(string2(), unknown()).optional(), /** * Whether the tool call ended in an error. * * If not set, this is assumed to be false (the call was successful). * * Any errors that originate from the tool SHOULD be reported inside the result * object, with `isError` set to true, _not_ as an MCP protocol-level error * response. Otherwise, the LLM would not be able to see that an error occurred * and self-correct. * * However, any errors in _finding_ the tool, an error indicating that the * server does not support tool calls, or any other exceptional conditions, * should be reported as an MCP error response. */ isError: boolean2().optional() }); var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The name of the tool to call. */ name: string2(), /** * Arguments to pass to the tool. */ arguments: record(string2(), unknown()).optional() }); var CallToolRequestSchema = RequestSchema.extend({ method: literal("tools/call"), params: CallToolRequestParamsSchema }); var ToolListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/tools/list_changed"), params: NotificationsParamsSchema.optional() }); var ListChangedOptionsBaseSchema = object({ /** * If true, the list will be refreshed automatically when a list changed notification is received. * The callback will be called with the updated list. * * If false, the callback will be called with null items, allowing manual refresh. * * @default true */ autoRefresh: boolean2().default(true), /** * Debounce time in milliseconds for list changed notification processing. * * Multiple notifications received within this timeframe will only trigger one refresh. * Set to 0 to disable debouncing. * * @default 300 */ debounceMs: number2().int().nonnegative().default(300) }); var LoggingLevelSchema = _enum2(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]); var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. */ level: LoggingLevelSchema }); var SetLevelRequestSchema = RequestSchema.extend({ method: literal("logging/setLevel"), params: SetLevelRequestParamsSchema }); var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The severity of this log message. */ level: LoggingLevelSchema, /** * An optional name of the logger issuing this message. */ logger: string2().optional(), /** * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. */ data: unknown() }); var LoggingMessageNotificationSchema = NotificationSchema.extend({ method: literal("notifications/message"), params: LoggingMessageNotificationParamsSchema }); var ModelHintSchema = object({ /** * A hint for a model name. */ name: string2().optional() }); var ModelPreferencesSchema = object({ /** * Optional hints to use for model selection. */ hints: array(ModelHintSchema).optional(), /** * How much to prioritize cost when selecting a model. */ costPriority: number2().min(0).max(1).optional(), /** * How much to prioritize sampling speed (latency) when selecting a model. */ speedPriority: number2().min(0).max(1).optional(), /** * How much to prioritize intelligence and capabilities when selecting a model. */ intelligencePriority: number2().min(0).max(1).optional() }); var ToolChoiceSchema = object({ /** * Controls when tools are used: * - "auto": Model decides whether to use tools (default) * - "required": Model MUST use at least one tool before completing * - "none": Model MUST NOT use any tools */ mode: _enum2(["auto", "required", "none"]).optional() }); var ToolResultContentSchema = object({ type: literal("tool_result"), toolUseId: string2().describe("The unique identifier for the corresponding tool call."), content: array(ContentBlockSchema).default([]), structuredContent: object({}).loose().optional(), isError: boolean2().optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]); var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, ToolResultContentSchema ]); var SamplingMessageSchema = object({ role: RoleSchema, content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ messages: array(SamplingMessageSchema), /** * The server's preferences for which model to select. The client MAY modify or omit this request. */ modelPreferences: ModelPreferencesSchema.optional(), /** * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. */ systemPrompt: string2().optional(), /** * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. * The client MAY ignore this request. * * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. */ includeContext: _enum2(["none", "thisServer", "allServers"]).optional(), temperature: number2().optional(), /** * The requested maximum number of tokens to sample (to prevent runaway completions). * * The client MAY choose to sample fewer tokens than the requested maximum. */ maxTokens: number2().int(), stopSequences: array(string2()).optional(), /** * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. */ metadata: AssertObjectSchema.optional(), /** * Tools that the model may use during generation. * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. */ tools: array(ToolSchema).optional(), /** * Controls how the model uses tools. * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. * Default is `{ mode: "auto" }`. */ toolChoice: ToolChoiceSchema.optional() }); var CreateMessageRequestSchema = RequestSchema.extend({ method: literal("sampling/createMessage"), params: CreateMessageRequestParamsSchema }); var CreateMessageResultSchema = ResultSchema.extend({ /** * The name of the model that generated the message. */ model: string2(), /** * The reason why sampling stopped, if known. * * Standard values: * - "endTurn": Natural end of the assistant's turn * - "stopSequence": A stop sequence was encountered * - "maxTokens": Maximum token limit was reached * * This field is an open string to allow for provider-specific stop reasons. */ stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens"]).or(string2())), role: RoleSchema, /** * Response content. Single content block (text, image, or audio). */ content: SamplingContentSchema }); var CreateMessageResultWithToolsSchema = ResultSchema.extend({ /** * The name of the model that generated the message. */ model: string2(), /** * The reason why sampling stopped, if known. * * Standard values: * - "endTurn": Natural end of the assistant's turn * - "stopSequence": A stop sequence was encountered * - "maxTokens": Maximum token limit was reached * - "toolUse": The model wants to use one or more tools * * This field is an open string to allow for provider-specific stop reasons. */ stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())), role: RoleSchema, /** * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". */ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) }); var BooleanSchemaSchema = object({ type: literal("boolean"), title: string2().optional(), description: string2().optional(), default: boolean2().optional() }); var StringSchemaSchema = object({ type: literal("string"), title: string2().optional(), description: string2().optional(), minLength: number2().optional(), maxLength: number2().optional(), format: _enum2(["email", "uri", "date", "date-time"]).optional(), default: string2().optional() }); var NumberSchemaSchema = object({ type: _enum2(["number", "integer"]), title: string2().optional(), description: string2().optional(), minimum: number2().optional(), maximum: number2().optional(), default: number2().optional() }); var UntitledSingleSelectEnumSchemaSchema = object({ type: literal("string"), title: string2().optional(), description: string2().optional(), enum: array(string2()), default: string2().optional() }); var TitledSingleSelectEnumSchemaSchema = object({ type: literal("string"), title: string2().optional(), description: string2().optional(), oneOf: array(object({ const: string2(), title: string2() })), default: string2().optional() }); var LegacyTitledEnumSchemaSchema = object({ type: literal("string"), title: string2().optional(), description: string2().optional(), enum: array(string2()), enumNames: array(string2()).optional(), default: string2().optional() }); var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); var UntitledMultiSelectEnumSchemaSchema = object({ type: literal("array"), title: string2().optional(), description: string2().optional(), minItems: number2().optional(), maxItems: number2().optional(), items: object({ type: literal("string"), enum: array(string2()) }), default: array(string2()).optional() }); var TitledMultiSelectEnumSchemaSchema = object({ type: literal("array"), title: string2().optional(), description: string2().optional(), minItems: number2().optional(), maxItems: number2().optional(), items: object({ anyOf: array(object({ const: string2(), title: string2() })) }), default: array(string2()).optional() }); var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The elicitation mode. * * Optional for backward compatibility. Clients MUST treat missing mode as "form". */ mode: literal("form").optional(), /** * The message to present to the user describing what information is being requested. */ message: string2(), /** * A restricted subset of JSON Schema. * Only top-level properties are allowed, without nesting. */ requestedSchema: object({ type: literal("object"), properties: record(string2(), PrimitiveSchemaDefinitionSchema), required: array(string2()).optional() }) }); var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The elicitation mode. */ mode: literal("url"), /** * The message to present to the user explaining why the interaction is needed. */ message: string2(), /** * The ID of the elicitation, which must be unique within the context of the server. * The client MUST treat this ID as an opaque value. */ elicitationId: string2(), /** * The URL that the user should navigate to. */ url: string2().url() }); var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); var ElicitRequestSchema = RequestSchema.extend({ method: literal("elicitation/create"), params: ElicitRequestParamsSchema }); var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The ID of the elicitation that completed. */ elicitationId: string2() }); var ElicitationCompleteNotificationSchema = NotificationSchema.extend({ method: literal("notifications/elicitation/complete"), params: ElicitationCompleteNotificationParamsSchema }); var ElicitResultSchema = ResultSchema.extend({ /** * The user action in response to the elicitation. * - "accept": User submitted the form/confirmed the action * - "decline": User explicitly decline the action * - "cancel": User dismissed without making an explicit choice */ action: _enum2(["accept", "decline", "cancel"]), /** * The submitted form data, only present when action is "accept". * Contains values matching the requested schema. * Per MCP spec, content is "typically omitted" for decline/cancel actions. * We normalize null to undefined for leniency while maintaining type compatibility. */ content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional()) }); var ResourceTemplateReferenceSchema = object({ type: literal("ref/resource"), /** * The URI or URI template of the resource. */ uri: string2() }); var PromptReferenceSchema = object({ type: literal("ref/prompt"), /** * The name of the prompt or prompt template */ name: string2() }); var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), /** * The argument's information */ argument: object({ /** * The name of the argument */ name: string2(), /** * The value of the argument to use for completion matching. */ value: string2() }), context: object({ /** * Previously-resolved variables in a URI template or prompt. */ arguments: record(string2(), string2()).optional() }).optional() }); var CompleteRequestSchema = RequestSchema.extend({ method: literal("completion/complete"), params: CompleteRequestParamsSchema }); function assertCompleteRequestPrompt(request) { if (request.params.ref.type !== "ref/prompt") { throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); } void request; } function assertCompleteRequestResourceTemplate(request) { if (request.params.ref.type !== "ref/resource") { throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); } void request; } var CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ /** * An array of completion values. Must not exceed 100 items. */ values: array(string2()).max(100), /** * The total number of completion options available. This can exceed the number of values actually sent in the response. */ total: optional(number2().int()), /** * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. */ hasMore: optional(boolean2()) }) }); var RootSchema = object({ /** * The URI identifying the root. This *must* start with file:// for now. */ uri: string2().startsWith("file://"), /** * An optional name for the root. */ name: string2().optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ListRootsRequestSchema = RequestSchema.extend({ method: literal("roots/list"), params: BaseRequestParamsSchema.optional() }); var ListRootsResultSchema = ResultSchema.extend({ roots: array(RootSchema) }); var RootsListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/roots/list_changed"), params: NotificationsParamsSchema.optional() }); var ClientRequestSchema = union([ PingRequestSchema, InitializeRequestSchema, CompleteRequestSchema, SetLevelRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, SubscribeRequestSchema, UnsubscribeRequestSchema, CallToolRequestSchema, ListToolsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, CancelTaskRequestSchema ]); var ClientNotificationSchema = union([ CancelledNotificationSchema, ProgressNotificationSchema, InitializedNotificationSchema, RootsListChangedNotificationSchema, TaskStatusNotificationSchema ]); var ClientResultSchema = union([ EmptyResultSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitResultSchema, ListRootsResultSchema, GetTaskResultSchema, ListTasksResultSchema, CreateTaskResultSchema ]); var ServerRequestSchema = union([ PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, CancelTaskRequestSchema ]); var ServerNotificationSchema = union([ CancelledNotificationSchema, ProgressNotificationSchema, LoggingMessageNotificationSchema, ResourceUpdatedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, TaskStatusNotificationSchema, ElicitationCompleteNotificationSchema ]); var ServerResultSchema = union([ EmptyResultSchema, InitializeResultSchema, CompleteResultSchema, GetPromptResultSchema, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ReadResourceResultSchema, CallToolResultSchema, ListToolsResultSchema, GetTaskResultSchema, ListTasksResultSchema, CreateTaskResultSchema ]); var McpError = class _McpError extends Error { constructor(code, message, data) { super(`MCP error ${code}: ${message}`); this.code = code; this.data = data; this.name = "McpError"; } /** * Factory method to create the appropriate error type based on the error code and data */ static fromError(code, message, data) { if (code === ErrorCode.UrlElicitationRequired && data) { const errorData = data; if (errorData.elicitations) { return new UrlElicitationRequiredError(errorData.elicitations, message); } } return new _McpError(code, message, data); } }; var UrlElicitationRequiredError = class extends McpError { constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { super(ErrorCode.UrlElicitationRequired, message, { elicitations }); } get elicitations() { return this.data?.elicitations ?? []; } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; var ReadBuffer = class { constructor(options) { this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; } append(chunk) { const newSize = (this._buffer?.length ?? 0) + chunk.length; if (newSize > this._maxBufferSize) { this.clear(); throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); } this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; } readMessage() { if (!this._buffer) { return null; } const index = this._buffer.indexOf("\n"); if (index === -1) { return null; } const line2 = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); this._buffer = this._buffer.subarray(index + 1); return deserializeMessage(line2); } clear() { this._buffer = void 0; } }; function deserializeMessage(line2) { return JSONRPCMessageSchema.parse(JSON.parse(line2)); } function serializeMessage(message) { return JSON.stringify(message) + "\n"; } // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js var StdioServerTransport = class { constructor(_stdin = process2.stdin, _stdout = process2.stdout, options) { this._stdin = _stdin; this._stdout = _stdout; this._started = false; this._ondata = (chunk) => { try { this._readBuffer.append(chunk); this.processReadBuffer(); } catch (error40) { this.onerror?.(error40); this.close().catch(() => { }); } }; this._onerror = (error40) => { this.onerror?.(error40); }; this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); } /** * Starts listening for messages on stdin. */ async start() { if (this._started) { throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); } this._started = true; this._stdin.on("data", this._ondata); this._stdin.on("error", this._onerror); } processReadBuffer() { while (true) { try { const message = this._readBuffer.readMessage(); if (message === null) { break; } this.onmessage?.(message); } catch (error40) { this.onerror?.(error40); } } } async close() { this._stdin.off("data", this._ondata); this._stdin.off("error", this._onerror); const remainingDataListeners = this._stdin.listenerCount("data"); if (remainingDataListeners === 0) { this._stdin.pause(); } this._readBuffer.clear(); this.onclose?.(); } send(message) { return new Promise((resolve3) => { const json3 = serializeMessage(message); if (this._stdout.write(json3)) { resolve3(); } else { this._stdout.once("drain", resolve3); } }); } }; // node_modules/@ai-sdk/provider/dist/index.js var marker = "vercel.ai.error"; var symbol2 = Symbol.for(marker); var _a; var _b; var AISDKError = class _AISDKError extends (_b = Error, _a = symbol2, _b) { /** * Creates an AI SDK Error. * * @param {Object} params - The parameters for creating the error. * @param {string} params.name - The name of the error. * @param {string} params.message - The error message. * @param {unknown} [params.cause] - The underlying cause of the error. */ constructor({ name: name153, message, cause }) { super(message); this[_a] = true; this.name = name153; this.cause = cause; } /** * Checks if the given error is an AI SDK Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is an AI SDK Error, false otherwise. */ static isInstance(error40) { return _AISDKError.hasMarker(error40, marker); } static hasMarker(error40, marker163) { const markerSymbol = Symbol.for(marker163); return error40 != null && typeof error40 === "object" && markerSymbol in error40 && typeof error40[markerSymbol] === "boolean" && error40[markerSymbol] === true; } }; var name = "AI_APICallError"; var marker2 = `vercel.ai.error.${name}`; var symbol22 = Symbol.for(marker2); var _a2; var _b2; var APICallError = class extends (_b2 = AISDKError, _a2 = symbol22, _b2) { constructor({ message, url: url2, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || // request timeout statusCode === 409 || // conflict statusCode === 429 || // too many requests statusCode >= 500), // server error data }) { super({ name, message, cause }); this[_a2] = true; this.url = url2; this.requestBodyValues = requestBodyValues; this.statusCode = statusCode; this.responseHeaders = responseHeaders; this.responseBody = responseBody; this.isRetryable = isRetryable; this.data = data; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker2); } }; var name2 = "AI_EmptyResponseBodyError"; var marker3 = `vercel.ai.error.${name2}`; var symbol3 = Symbol.for(marker3); var _a3; var _b3; var EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) { // used in isInstance constructor({ message = "Empty response body" } = {}) { super({ name: name2, message }); this[_a3] = true; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker3); } }; function getErrorMessage(error40) { if (error40 == null) { return "unknown error"; } if (typeof error40 === "string") { return error40; } if (error40 instanceof Error) { return error40.toString(); } return JSON.stringify(error40); } var name3 = "AI_InvalidArgumentError"; var marker4 = `vercel.ai.error.${name3}`; var symbol4 = Symbol.for(marker4); var _a4; var _b4; var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) { constructor({ message, cause, argument }) { super({ name: name3, message, cause }); this[_a4] = true; this.argument = argument; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker4); } }; var name4 = "AI_InvalidPromptError"; var marker5 = `vercel.ai.error.${name4}`; var symbol5 = Symbol.for(marker5); var _a5; var _b5; var InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) { constructor({ prompt, message, cause }) { super({ name: name4, message: `Invalid prompt: ${message}`, cause }); this[_a5] = true; this.prompt = prompt; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker5); } }; var name5 = "AI_InvalidResponseDataError"; var marker6 = `vercel.ai.error.${name5}`; var symbol6 = Symbol.for(marker6); var _a6; var _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(error40) { return AISDKError.hasMarker(error40, marker6); } }; var name6 = "AI_JSONParseError"; var marker7 = `vercel.ai.error.${name6}`; var symbol7 = Symbol.for(marker7); var _a7; var _b7; var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) { constructor({ text: text2, cause }) { super({ name: name6, message: `JSON parsing failed: Text: ${text2}. Error message: ${getErrorMessage(cause)}`, cause }); this[_a7] = true; this.text = text2; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker7); } }; var name7 = "AI_LoadAPIKeyError"; var marker8 = `vercel.ai.error.${name7}`; var symbol8 = Symbol.for(marker8); var _a8; var _b8; var LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) { // used in isInstance constructor({ message }) { super({ name: name7, message }); this[_a8] = true; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker8); } }; var name8 = "AI_LoadSettingError"; var marker9 = `vercel.ai.error.${name8}`; var symbol9 = Symbol.for(marker9); var _a9; var _b9; var LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) { // used in isInstance constructor({ message }) { super({ name: name8, message }); this[_a9] = true; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker9); } }; var name9 = "AI_NoContentGeneratedError"; var marker10 = `vercel.ai.error.${name9}`; var symbol10 = Symbol.for(marker10); var _a10; var _b10; var NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) { // used in isInstance constructor({ message = "No content generated." } = {}) { super({ name: name9, message }); this[_a10] = true; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker10); } }; var name10 = "AI_NoSuchModelError"; var marker11 = `vercel.ai.error.${name10}`; var symbol11 = Symbol.for(marker11); var _a11; var _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(error40) { return AISDKError.hasMarker(error40, marker11); } }; var name11 = "AI_NoSuchProviderReferenceError"; var marker12 = `vercel.ai.error.${name11}`; var symbol12 = Symbol.for(marker12); var _a12; var _b12; var NoSuchProviderReferenceError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) { constructor({ provider, reference, message = `No provider reference found for provider '${provider}'. Available providers: ${Object.keys(reference).join(", ")}` }) { super({ name: name11, message }); this[_a12] = true; this.provider = provider; this.reference = reference; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker12); } }; var name12 = "AI_TooManyEmbeddingValuesForCallError"; var marker13 = `vercel.ai.error.${name12}`; var symbol13 = Symbol.for(marker13); var _a13; var _b13; var TooManyEmbeddingValuesForCallError = class extends (_b13 = AISDKError, _a13 = symbol13, _b13) { constructor(options) { super({ name: name12, message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.` }); this[_a13] = true; this.provider = options.provider; this.modelId = options.modelId; this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall; this.values = options.values; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker13); } }; var name13 = "AI_TypeValidationError"; var marker14 = `vercel.ai.error.${name13}`; var symbol14 = Symbol.for(marker14); var _a14; var _b14; var TypeValidationError = class _TypeValidationError extends (_b14 = AISDKError, _a14 = symbol14, _b14) { constructor({ value, cause, context }) { let contextPrefix = "Type validation failed"; if (context == null ? void 0 : context.field) { contextPrefix += ` for ${context.field}`; } if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) { contextPrefix += " ("; const parts = []; if (context.entityName) { parts.push(context.entityName); } if (context.entityId) { parts.push(`id: "${context.entityId}"`); } contextPrefix += parts.join(", "); contextPrefix += ")"; } super({ name: name13, message: `${contextPrefix}: Value: ${JSON.stringify(value)}. Error message: ${getErrorMessage(cause)}`, cause }); this[_a14] = true; this.value = value; this.context = context; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker14); } /** * Wraps an error into a TypeValidationError. * If the cause is already a TypeValidationError with the same value and context, it returns the cause. * Otherwise, it creates a new TypeValidationError. * * @param {Object} params - The parameters for wrapping the error. * @param {unknown} params.value - The value that failed validation. * @param {unknown} params.cause - The original error or cause of the validation failure. * @param {TypeValidationContext} params.context - Optional context about what is being validated. * @returns {TypeValidationError} A TypeValidationError instance. */ static wrap({ value, cause, context }) { var _a163, _b162, _c; if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a163 = cause.context) == null ? void 0 : _a163.field) === (context == null ? void 0 : context.field) && ((_b162 = cause.context) == null ? void 0 : _b162.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) { return cause; } return new _TypeValidationError({ value, cause, context }); } }; var name14 = "AI_UnsupportedFunctionalityError"; var marker15 = `vercel.ai.error.${name14}`; var symbol15 = Symbol.for(marker15); var _a15; var _b15; var UnsupportedFunctionalityError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) { constructor({ functionality, message = `'${functionality}' functionality not supported.` }) { super({ name: name14, message }); this[_a15] = true; this.functionality = functionality; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker15); } }; // node_modules/zod/v3/external.js var external_exports2 = {}; __export(external_exports2, { BRAND: () => BRAND, DIRTY: () => DIRTY, EMPTY_PATH: () => EMPTY_PATH, INVALID: () => INVALID, NEVER: () => NEVER2, OK: () => OK, ParseStatus: () => ParseStatus, Schema: () => ZodType2, ZodAny: () => ZodAny2, ZodArray: () => ZodArray2, ZodBigInt: () => ZodBigInt2, ZodBoolean: () => ZodBoolean2, ZodBranded: () => ZodBranded, ZodCatch: () => ZodCatch2, ZodDate: () => ZodDate2, ZodDefault: () => ZodDefault2, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, ZodEffects: () => ZodEffects, ZodEnum: () => ZodEnum2, ZodError: () => ZodError2, ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodIntersection: () => ZodIntersection2, ZodIssueCode: () => ZodIssueCode2, ZodLazy: () => ZodLazy2, ZodLiteral: () => ZodLiteral2, ZodMap: () => ZodMap2, ZodNaN: () => ZodNaN2, ZodNativeEnum: () => ZodNativeEnum, ZodNever: () => ZodNever2, ZodNull: () => ZodNull2, ZodNullable: () => ZodNullable2, ZodNumber: () => ZodNumber2, ZodObject: () => ZodObject2, ZodOptional: () => ZodOptional2, ZodParsedType: () => ZodParsedType, ZodPipeline: () => ZodPipeline, ZodPromise: () => ZodPromise2, ZodReadonly: () => ZodReadonly2, ZodRecord: () => ZodRecord2, ZodSchema: () => ZodType2, ZodSet: () => ZodSet2, ZodString: () => ZodString2, ZodSymbol: () => ZodSymbol2, ZodTransformer: () => ZodEffects, ZodTuple: () => ZodTuple2, ZodType: () => ZodType2, ZodUndefined: () => ZodUndefined2, ZodUnion: () => ZodUnion2, ZodUnknown: () => ZodUnknown2, ZodVoid: () => ZodVoid2, addIssueToContext: () => addIssueToContext, any: () => anyType, array: () => arrayType, bigint: () => bigIntType, boolean: () => booleanType, coerce: () => coerce, custom: () => custom2, date: () => dateType, datetimeRegex: () => datetimeRegex, defaultErrorMap: () => en_default2, discriminatedUnion: () => discriminatedUnionType, effect: () => effectsType, enum: () => enumType, function: () => functionType, getErrorMap: () => getErrorMap2, getParsedType: () => getParsedType2, instanceof: () => instanceOfType, intersection: () => intersectionType, isAborted: () => isAborted, isAsync: () => isAsync, isDirty: () => isDirty, isValid: () => isValid, late: () => late, lazy: () => lazyType, literal: () => literalType, makeIssue: () => makeIssue, map: () => mapType, nan: () => nanType, nativeEnum: () => nativeEnumType, never: () => neverType, null: () => nullType, nullable: () => nullableType, number: () => numberType, object: () => objectType, objectUtil: () => objectUtil, oboolean: () => oboolean, onumber: () => onumber, optional: () => optionalType, ostring: () => ostring, pipeline: () => pipelineType, preprocess: () => preprocessType, promise: () => promiseType, quotelessJson: () => quotelessJson, record: () => recordType, set: () => setType, setErrorMap: () => setErrorMap2, strictObject: () => strictObjectType, string: () => stringType, symbol: () => symbolType, transformer: () => effectsType, tuple: () => tupleType, undefined: () => undefinedType, union: () => unionType, unknown: () => unknownType, util: () => util, void: () => voidType }); // node_modules/zod/v3/helpers/util.js var util; (function(util2) { util2.assertEqual = (_2) => { }; function assertIs2(_arg) { } util2.assertIs = assertIs2; function assertNever2(_x) { throw new Error(); } util2.assertNever = assertNever2; util2.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util2.getValidEnumValues = (obj) => { const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util2.objectValues(filtered); }; util2.objectValues = (obj) => { return util2.objectKeys(obj).map(function(e5) { return obj[e5]; }); }; util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object4) => { const keys = []; for (const key in object4) { if (Object.prototype.hasOwnProperty.call(object4, key)) { keys.push(key); } } return keys; }; util2.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; function joinValues2(array3, separator = " | ") { return array3.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } util2.joinValues = joinValues2; util2.jsonStringifyReplacer = (_2, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); var objectUtil; (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => { return { ...first, ...second // second overwrites first }; }; })(objectUtil || (objectUtil = {})); var ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); var getParsedType2 = (data) => { const t4 = typeof data; switch (t4) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; // node_modules/zod/v3/ZodError.js var ZodIssueCode2 = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite" ]); var quotelessJson = (obj) => { const json3 = JSON.stringify(obj, null, 2); return json3.replace(/"([^"]+)":/g, "$1:"); }; var ZodError2 = class _ZodError extends Error { get errors() { return this.issues; } constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } format(_mapper) { const mapper = _mapper || function(issue2) { return issue2.message; }; const fieldErrors = { _errors: [] }; const processError = (error40) => { for (const issue2 of error40.issues) { if (issue2.code === "invalid_union") { issue2.unionErrors.map(processError); } else if (issue2.code === "invalid_return_type") { processError(issue2.returnTypeError); } else if (issue2.code === "invalid_arguments") { processError(issue2.argumentsError); } else if (issue2.path.length === 0) { fieldErrors._errors.push(mapper(issue2)); } else { let curr = fieldErrors; let i4 = 0; while (i4 < issue2.path.length) { const el = issue2.path[i4]; const terminal = i4 === issue2.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue2)); } curr = curr[el]; i4++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof _ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { const firstEl = sub.path[0]; fieldErrors[firstEl] = fieldErrors[firstEl] || []; fieldErrors[firstEl].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } }; ZodError2.create = (issues) => { const error40 = new ZodError2(issues); return error40; }; // node_modules/zod/v3/locales/en.js var errorMap = (issue2, _ctx) => { let message; switch (issue2.code) { case ZodIssueCode2.invalid_type: if (issue2.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue2.expected}, received ${issue2.received}`; } break; case ZodIssueCode2.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`; break; case ZodIssueCode2.unrecognized_keys: message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`; break; case ZodIssueCode2.invalid_union: message = `Invalid input`; break; case ZodIssueCode2.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`; break; case ZodIssueCode2.invalid_enum_value: message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`; break; case ZodIssueCode2.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode2.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode2.invalid_date: message = `Invalid date`; break; case ZodIssueCode2.invalid_string: if (typeof issue2.validation === "object") { if ("includes" in issue2.validation) { message = `Invalid input: must include "${issue2.validation.includes}"`; if (typeof issue2.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; } } else if ("startsWith" in issue2.validation) { message = `Invalid input: must start with "${issue2.validation.startsWith}"`; } else if ("endsWith" in issue2.validation) { message = `Invalid input: must end with "${issue2.validation.endsWith}"`; } else { util.assertNever(issue2.validation); } } else if (issue2.validation !== "regex") { message = `Invalid ${issue2.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode2.too_small: if (issue2.type === "array") message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; else if (issue2.type === "string") message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; else if (issue2.type === "number") message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; else if (issue2.type === "bigint") message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; else if (issue2.type === "date") message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode2.too_big: if (issue2.type === "array") message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; else if (issue2.type === "string") message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; else if (issue2.type === "number") message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; else if (issue2.type === "bigint") message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; else if (issue2.type === "date") message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode2.custom: message = `Invalid input`; break; case ZodIssueCode2.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode2.not_multiple_of: message = `Number must be a multiple of ${issue2.multipleOf}`; break; case ZodIssueCode2.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util.assertNever(issue2); } return { message }; }; var en_default2 = errorMap; // node_modules/zod/v3/errors.js var overrideErrorMap = en_default2; function setErrorMap2(map2) { overrideErrorMap = map2; } function getErrorMap2() { return overrideErrorMap; } // node_modules/zod/v3/helpers/parseUtil.js var makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath }; if (issueData.message !== void 0) { return { ...issueData, path: fullPath, message: issueData.message }; } let errorMessage = ""; const maps = errorMaps.filter((m3) => !!m3).slice().reverse(); for (const map2 of maps) { errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: errorMessage }; }; var EMPTY_PATH = []; function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap2(); const issue2 = makeIssue({ issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, // contextual error map is first priority ctx.schemaErrorMap, // then schema-bound map if available overrideMap, // then global override map overrideMap === en_default2 ? void 0 : en_default2 // then global default map ].filter((x4) => !!x4) }); ctx.common.issues.push(issue2); } var ParseStatus = class _ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s2 of results) { if (s2.status === "aborted") return INVALID; if (s2.status === "dirty") status.dirty(); arrayValue.push(s2.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs) { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value }); } return _ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs) { const finalObject = {}; for (const pair of pairs) { const { key, value } = pair; if (key.status === "aborted") return INVALID; if (value.status === "aborted") return INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } }; var INVALID = Object.freeze({ status: "aborted" }); var DIRTY = (value) => ({ status: "dirty", value }); var OK = (value) => ({ status: "valid", value }); var isAborted = (x4) => x4.status === "aborted"; var isDirty = (x4) => x4.status === "dirty"; var isValid = (x4) => x4.status === "valid"; var isAsync = (x4) => typeof Promise !== "undefined" && x4 instanceof Promise; // node_modules/zod/v3/helpers/errorUtil.js var errorUtil; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; })(errorUtil || (errorUtil = {})); // node_modules/zod/v3/types.js var ParseInputLazyPath = class { constructor(parent, value, path, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path; this._key = key; } get path() { if (!this._cachedPath.length) { if (Array.isArray(this._key)) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } }; var handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error40 = new ZodError2(ctx.common.issues); this._error = error40; return this._error; } }; } }; function processCreateParams(params) { if (!params) return {}; const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; if (errorMap2 && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap2) return { errorMap: errorMap2, description }; const customMap = (iss, ctx) => { const { message } = params; if (iss.code === "invalid_enum_value") { return { message: message ?? ctx.defaultError }; } if (typeof ctx.data === "undefined") { return { message: message ?? required_error ?? ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; return { message: message ?? invalid_type_error ?? ctx.defaultError }; }; return { errorMap: customMap, description }; } var ZodType2 = class { get description() { return this._def.description; } _getType(input) { return getParsedType2(input.data); } _getOrReturnCtx(input, ctx) { return ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType2(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: getParsedType2(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: getParsedType2(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: getParsedType2(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 (err2) { if (err2?.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: getParsedType2(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(check2, message) { const getIssueProperties = (val) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check2(val); const setError = () => ctx.addIssue({ code: ZodIssueCode2.custom, ...getIssueProperties(val) }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check2, refinementData) { return this._refinement((val, ctx) => { if (!check2(val)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement } }); } superRefine(refinement) { return this._refinement(refinement); } constructor(def) { 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 ZodOptional2.create(this, this._def); } nullable() { return ZodNullable2.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray2.create(this); } promise() { return ZodPromise2.create(this, this._def); } or(option) { return ZodUnion2.create([this, option], this._def); } and(incoming) { return ZodIntersection2.create(this, incoming, this._def); } transform(transform2) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform: transform2 } }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault2({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def) }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new ZodCatch2({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind.ZodCatch }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description }); } pipe(target) { return ZodPipeline.create(this, target); } readonly() { return ZodReadonly2.create(this); } isOptional() { return this.safeParse(void 0).success; } isNullable() { return this.safeParse(null).success; } }; var cuidRegex = /^c[^\s-]{8,}$/i; var cuid2Regex = /^[0-9a-z]+$/; var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; var 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; var nanoidRegex = /^[a-z0-9_-]{21}$/i; var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; var 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)?)??$/; var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; var emojiRegex; var 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])$/; var 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])$/; var 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]))$/; var 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])$/; var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; var 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])))`; var dateRegex = new RegExp(`^${dateRegexSource}$`); function timeRegexSource(args) { let secondsRegexSource = `[0-5]\\d`; if (args.precision) { secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; } else if (args.precision == null) { secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; } const secondsQuantifier = args.precision ? "+" : "?"; return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; } function timeRegex(args) { return new RegExp(`^${timeRegexSource(args)}$`); } function datetimeRegex(args) { let regex = `${dateRegexSource}T${timeRegexSource(args)}`; const opts = []; opts.push(args.local ? `Z?` : `Z`); if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); regex = `${regex}(${opts.join("|")})`; return new RegExp(`^${regex}$`); } function isValidIP(ip, version2) { if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) { return true; } if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) { return true; } return false; } function isValidJWT2(jwt2, alg) { if (!jwtRegex.test(jwt2)) return false; try { const [header] = jwt2.split("."); if (!header) return false; const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); const decoded = JSON.parse(atob(base643)); if (typeof decoded !== "object" || decoded === null) return false; if ("typ" in decoded && decoded?.typ !== "JWT") return false; if (!decoded.alg) return false; if (alg && decoded.alg !== alg) return false; return true; } catch { return false; } } function isValidCidr(ip, version2) { if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) { return true; } if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) { return true; } return false; } var ZodString2 = class _ZodString2 extends ZodType2 { _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType4 = this._getType(input); if (parsedType4 !== ZodParsedType.string) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.string, received: ctx2.parsedType }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check2 of this._def.checks) { if (check2.kind === "min") { if (input.data.length < check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_small, minimum: check2.value, type: "string", inclusive: true, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "max") { if (input.data.length > check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_big, maximum: check2.value, type: "string", inclusive: true, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "length") { const tooBig = input.data.length > check2.value; const tooSmall = input.data.length < check2.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { addIssueToContext(ctx, { code: ZodIssueCode2.too_big, maximum: check2.value, type: "string", inclusive: true, exact: true, message: check2.message }); } else if (tooSmall) { addIssueToContext(ctx, { code: ZodIssueCode2.too_small, minimum: check2.value, type: "string", inclusive: true, exact: true, message: check2.message }); } status.dirty(); } } else if (check2.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "email", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "emoji") { if (!emojiRegex) { emojiRegex = new RegExp(_emojiRegex, "u"); } if (!emojiRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "emoji", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "nanoid") { if (!nanoidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "nanoid", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid2", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ulid", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "url") { try { new URL(input.data); } catch { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "regex") { check2.regex.lastIndex = 0; const testResult = check2.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "trim") { input.data = input.data.trim(); } else if (check2.kind === "includes") { if (!input.data.includes(check2.value, check2.position)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_string, validation: { includes: check2.value, position: check2.position }, message: check2.message }); status.dirty(); } } else if (check2.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check2.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check2.kind === "startsWith") { if (!input.data.startsWith(check2.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_string, validation: { startsWith: check2.value }, message: check2.message }); status.dirty(); } } else if (check2.kind === "endsWith") { if (!input.data.endsWith(check2.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_string, validation: { endsWith: check2.value }, message: check2.message }); status.dirty(); } } else if (check2.kind === "datetime") { const regex = datetimeRegex(check2); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_string, validation: "datetime", message: check2.message }); status.dirty(); } } else if (check2.kind === "date") { const regex = dateRegex; if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_string, validation: "date", message: check2.message }); status.dirty(); } } else if (check2.kind === "time") { const regex = timeRegex(check2); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_string, validation: "time", message: check2.message }); status.dirty(); } } else if (check2.kind === "duration") { if (!durationRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "duration", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "ip") { if (!isValidIP(input.data, check2.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ip", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "jwt") { if (!isValidJWT2(input.data, check2.alg)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "jwt", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "cidr") { if (!isValidCidr(input.data, check2.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cidr", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "base64") { if (!base64Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "base64url") { if (!base64urlRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64url", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else { util.assertNever(check2); } } return { status: status.value, value: input.data }; } _regex(regex, validation, message) { return this.refinement((data) => regex.test(data), { validation, code: ZodIssueCode2.invalid_string, ...errorUtil.errToObj(message) }); } _addCheck(check2) { return new _ZodString2({ ...this._def, checks: [...this._def.checks, check2] }); } email(message) { return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } url(message) { return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } emoji(message) { return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } uuid(message) { return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } nanoid(message) { return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); } cuid(message) { return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } cuid2(message) { return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); } ulid(message) { return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); } base64(message) { return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); } base64url(message) { return this._addCheck({ kind: "base64url", ...errorUtil.errToObj(message) }); } jwt(options) { return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } cidr(options) { return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); } datetime(options) { if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: options }); } return this._addCheck({ kind: "datetime", precision: typeof options?.precision === "undefined" ? null : options?.precision, offset: options?.offset ?? false, local: options?.local ?? false, ...errorUtil.errToObj(options?.message) }); } date(message) { return this._addCheck({ kind: "date", message }); } time(options) { if (typeof options === "string") { return this._addCheck({ kind: "time", precision: null, message: options }); } return this._addCheck({ kind: "time", precision: typeof options?.precision === "undefined" ? null : options?.precision, ...errorUtil.errToObj(options?.message) }); } duration(message) { return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); } regex(regex, message) { return this._addCheck({ kind: "regex", regex, ...errorUtil.errToObj(message) }); } includes(value, options) { return this._addCheck({ kind: "includes", value, position: options?.position, ...errorUtil.errToObj(options?.message) }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value, ...errorUtil.errToObj(message) }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", value, ...errorUtil.errToObj(message) }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil.errToObj(message) }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil.errToObj(message) }); } length(len, message) { return this._addCheck({ kind: "length", value: len, ...errorUtil.errToObj(message) }); } /** * Equivalent to `.min(1)` */ nonempty(message) { return this.min(1, errorUtil.errToObj(message)); } trim() { return new _ZodString2({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] }); } toLowerCase() { return new _ZodString2({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] }); } toUpperCase() { return new _ZodString2({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] }); } get isDatetime() { return !!this._def.checks.find((ch2) => ch2.kind === "datetime"); } get isDate() { return !!this._def.checks.find((ch2) => ch2.kind === "date"); } get isTime() { return !!this._def.checks.find((ch2) => ch2.kind === "time"); } get isDuration() { return !!this._def.checks.find((ch2) => ch2.kind === "duration"); } get isEmail() { return !!this._def.checks.find((ch2) => ch2.kind === "email"); } get isURL() { return !!this._def.checks.find((ch2) => ch2.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch2) => ch2.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch2) => ch2.kind === "uuid"); } get isNANOID() { return !!this._def.checks.find((ch2) => ch2.kind === "nanoid"); } get isCUID() { return !!this._def.checks.find((ch2) => ch2.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch2) => ch2.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch2) => ch2.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch2) => ch2.kind === "ip"); } get isCIDR() { return !!this._def.checks.find((ch2) => ch2.kind === "cidr"); } get isBase64() { return !!this._def.checks.find((ch2) => ch2.kind === "base64"); } get isBase64url() { return !!this._def.checks.find((ch2) => ch2.kind === "base64url"); } get minLength() { let min = null; for (const ch2 of this._def.checks) { if (ch2.kind === "min") { if (min === null || ch2.value > min) min = ch2.value; } } return min; } get maxLength() { let max2 = null; for (const ch2 of this._def.checks) { if (ch2.kind === "max") { if (max2 === null || ch2.value < max2) max2 = ch2.value; } } return max2; } }; ZodString2.create = (params) => { return new ZodString2({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: params?.coerce ?? false, ...processCreateParams(params) }); }; function floatSafeRemainder2(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; } var ZodNumber2 = class _ZodNumber extends ZodType2 { 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 parsedType4 = this._getType(input); if (parsedType4 !== ZodParsedType.number) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.number, received: ctx2.parsedType }); return INVALID; } let ctx = void 0; const status = new ParseStatus(); for (const check2 of this._def.checks) { if (check2.kind === "int") { if (!util.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: "integer", received: "float", message: check2.message }); status.dirty(); } } else if (check2.kind === "min") { const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_small, minimum: check2.value, type: "number", inclusive: check2.inclusive, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "max") { const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_big, maximum: check2.value, type: "number", inclusive: check2.inclusive, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "multipleOf") { if (floatSafeRemainder2(input.data, check2.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.not_multiple_of, multipleOf: check2.value, message: check2.message }); status.dirty(); } } else if (check2.kind === "finite") { if (!Number.isFinite(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.not_finite, message: check2.message }); status.dirty(); } } else { util.assertNever(check2); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new _ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check2) { return new _ZodNumber({ ...this._def, checks: [...this._def.checks, check2] }); } int(message) { return this._addCheck({ kind: "int", message: errorUtil.toString(message) }); } positive(message) { return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } finite(message) { return this._addCheck({ kind: "finite", message: errorUtil.toString(message) }); } safe(message) { return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: errorUtil.toString(message) })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch2 of this._def.checks) { if (ch2.kind === "min") { if (min === null || ch2.value > min) min = ch2.value; } } return min; } get maxValue() { let max2 = null; for (const ch2 of this._def.checks) { if (ch2.kind === "max") { if (max2 === null || ch2.value < max2) max2 = ch2.value; } } return max2; } get isInt() { return !!this._def.checks.find((ch2) => ch2.kind === "int" || ch2.kind === "multipleOf" && util.isInteger(ch2.value)); } get isFinite() { let max2 = null; let min = null; for (const ch2 of this._def.checks) { if (ch2.kind === "finite" || ch2.kind === "int" || ch2.kind === "multipleOf") { return true; } else if (ch2.kind === "min") { if (min === null || ch2.value > min) min = ch2.value; } else if (ch2.kind === "max") { if (max2 === null || ch2.value < max2) max2 = ch2.value; } } return Number.isFinite(min) && Number.isFinite(max2); } }; ZodNumber2.create = (params) => { return new ZodNumber2({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: params?.coerce || false, ...processCreateParams(params) }); }; var ZodBigInt2 = class _ZodBigInt extends ZodType2 { 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 parsedType4 = this._getType(input); if (parsedType4 !== ZodParsedType.bigint) { return this._getInvalidInput(input); } let ctx = void 0; const status = new ParseStatus(); for (const check2 of this._def.checks) { if (check2.kind === "min") { const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_small, type: "bigint", minimum: check2.value, inclusive: check2.inclusive, message: check2.message }); status.dirty(); } } else if (check2.kind === "max") { const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_big, type: "bigint", maximum: check2.value, inclusive: check2.inclusive, message: check2.message }); status.dirty(); } } else if (check2.kind === "multipleOf") { if (input.data % check2.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.not_multiple_of, multipleOf: check2.value, message: check2.message }); status.dirty(); } } else { util.assertNever(check2); } } return { status: status.value, value: input.data }; } _getInvalidInput(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.bigint, received: ctx.parsedType }); return INVALID; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new _ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check2) { return new _ZodBigInt({ ...this._def, checks: [...this._def.checks, check2] }); } positive(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch2 of this._def.checks) { if (ch2.kind === "min") { if (min === null || ch2.value > min) min = ch2.value; } } return min; } get maxValue() { let max2 = null; for (const ch2 of this._def.checks) { if (ch2.kind === "max") { if (max2 === null || ch2.value < max2) max2 = ch2.value; } } return max2; } }; ZodBigInt2.create = (params) => { return new ZodBigInt2({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: params?.coerce ?? false, ...processCreateParams(params) }); }; var ZodBoolean2 = class extends ZodType2 { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType4 = this._getType(input); if (parsedType4 !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodBoolean2.create = (params) => { return new ZodBoolean2({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: params?.coerce || false, ...processCreateParams(params) }); }; var ZodDate2 = class _ZodDate extends ZodType2 { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType4 = this._getType(input); if (parsedType4 !== ZodParsedType.date) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.date, received: ctx2.parsedType }); return INVALID; } if (Number.isNaN(input.data.getTime())) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode2.invalid_date }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check2 of this._def.checks) { if (check2.kind === "min") { if (input.data.getTime() < check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_small, message: check2.message, inclusive: true, exact: false, minimum: check2.value, type: "date" }); status.dirty(); } } else if (check2.kind === "max") { if (input.data.getTime() > check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_big, message: check2.message, inclusive: true, exact: false, maximum: check2.value, type: "date" }); status.dirty(); } } else { util.assertNever(check2); } } return { status: status.value, value: new Date(input.data.getTime()) }; } _addCheck(check2) { return new _ZodDate({ ...this._def, checks: [...this._def.checks, check2] }); } min(minDate, message) { return this._addCheck({ kind: "min", value: minDate.getTime(), message: errorUtil.toString(message) }); } max(maxDate, message) { return this._addCheck({ kind: "max", value: maxDate.getTime(), message: errorUtil.toString(message) }); } get minDate() { let min = null; for (const ch2 of this._def.checks) { if (ch2.kind === "min") { if (min === null || ch2.value > min) min = ch2.value; } } return min != null ? new Date(min) : null; } get maxDate() { let max2 = null; for (const ch2 of this._def.checks) { if (ch2.kind === "max") { if (max2 === null || ch2.value < max2) max2 = ch2.value; } } return max2 != null ? new Date(max2) : null; } }; ZodDate2.create = (params) => { return new ZodDate2({ checks: [], coerce: params?.coerce || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params) }); }; var ZodSymbol2 = class extends ZodType2 { _parse(input) { const parsedType4 = this._getType(input); if (parsedType4 !== ZodParsedType.symbol) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.symbol, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodSymbol2.create = (params) => { return new ZodSymbol2({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params) }); }; var ZodUndefined2 = class extends ZodType2 { _parse(input) { const parsedType4 = this._getType(input); if (parsedType4 !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.undefined, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodUndefined2.create = (params) => { return new ZodUndefined2({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params) }); }; var ZodNull2 = class extends ZodType2 { _parse(input) { const parsedType4 = this._getType(input); if (parsedType4 !== ZodParsedType.null) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.null, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodNull2.create = (params) => { return new ZodNull2({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params) }); }; var ZodAny2 = class extends ZodType2 { constructor() { super(...arguments); this._any = true; } _parse(input) { return OK(input.data); } }; ZodAny2.create = (params) => { return new ZodAny2({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params) }); }; var ZodUnknown2 = class extends ZodType2 { constructor() { super(...arguments); this._unknown = true; } _parse(input) { return OK(input.data); } }; ZodUnknown2.create = (params) => { return new ZodUnknown2({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params) }); }; var ZodNever2 = class extends ZodType2 { _parse(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.never, received: ctx.parsedType }); return INVALID; } }; ZodNever2.create = (params) => { return new ZodNever2({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(params) }); }; var ZodVoid2 = class extends ZodType2 { _parse(input) { const parsedType4 = this._getType(input); if (parsedType4 !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.void, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodVoid2.create = (params) => { return new ZodVoid2({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params) }); }; var ZodArray2 = class _ZodArray extends ZodType2 { _parse(input) { const { ctx, status } = this._processInputParams(input); const def = this._def; if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (def.exactLength !== null) { const tooBig = ctx.data.length > def.exactLength.value; const tooSmall = ctx.data.length < def.exactLength.value; if (tooBig || tooSmall) { addIssueToContext(ctx, { code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small, minimum: tooSmall ? def.exactLength.value : void 0, maximum: tooBig ? def.exactLength.value : void 0, type: "array", inclusive: true, exact: true, message: def.exactLength.message }); status.dirty(); } } if (def.minLength !== null) { if (ctx.data.length < def.minLength.value) { addIssueToContext(ctx, { code: ZodIssueCode2.too_small, minimum: def.minLength.value, type: "array", inclusive: true, exact: false, message: def.minLength.message }); status.dirty(); } } if (def.maxLength !== null) { if (ctx.data.length > def.maxLength.value) { addIssueToContext(ctx, { code: ZodIssueCode2.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, i4) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i4)); })).then((result2) => { return ParseStatus.mergeArray(status, result2); }); } const result = [...ctx.data].map((item, i4) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i4)); }); return ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new _ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) } }); } max(maxLength, message) { return new _ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) } }); } length(len, message) { return new _ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil.toString(message) } }); } nonempty(message) { return this.min(1, message); } }; ZodArray2.create = (schema, params) => { return new ZodArray2({ type: schema, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params) }); }; function deepPartialify(schema) { if (schema instanceof ZodObject2) { const newShape = {}; for (const key in schema.shape) { const fieldSchema = schema.shape[key]; newShape[key] = ZodOptional2.create(deepPartialify(fieldSchema)); } return new ZodObject2({ ...schema._def, shape: () => newShape }); } else if (schema instanceof ZodArray2) { return new ZodArray2({ ...schema._def, type: deepPartialify(schema.element) }); } else if (schema instanceof ZodOptional2) { return ZodOptional2.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodNullable2) { return ZodNullable2.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodTuple2) { return ZodTuple2.create(schema.items.map((item) => deepPartialify(item))); } else { return schema; } } var ZodObject2 = class _ZodObject extends ZodType2 { constructor() { super(...arguments); this._cached = null; this.nonstrict = this.passthrough; this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util.objectKeys(shape); this._cached = { shape, keys }; return this._cached; } _parse(input) { const parsedType4 = this._getType(input); if (parsedType4 !== ZodParsedType.object) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.object, received: ctx2.parsedType }); return INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data }); } if (this._def.catchall instanceof ZodNever2) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] } }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { addIssueToContext(ctx, { code: ZodIssueCode2.unrecognized_keys, keys: extraKeys }); status.dirty(); } } else if (unknownKeys === "strip") { } else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: catchall._parse( new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) ), alwaysSet: key in ctx.data }); } } if (ctx.common.async) { return Promise.resolve().then(async () => { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value, alwaysSet: pair.alwaysSet }); } return syncPairs; }).then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new _ZodObject({ ...this._def, unknownKeys: "strict", ...message !== void 0 ? { errorMap: (issue2, ctx) => { const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; if (issue2.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError }; return { message: defaultError }; } } : {} }); } strip() { return new _ZodObject({ ...this._def, unknownKeys: "strip" }); } passthrough() { return new _ZodObject({ ...this._def, unknownKeys: "passthrough" }); } // const AugmentFactory = // (def: Def) => // ( // augmentation: Augmentation // ): ZodObject< // extendShape, Augmentation>, // Def["unknownKeys"], // Def["catchall"] // > => { // return new ZodObject({ // ...def, // shape: () => ({ // ...def.shape(), // ...augmentation, // }), // }) as any; // }; extend(augmentation) { return new _ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation }) }); } /** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge(merging) { const merged = new _ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape() }), typeName: ZodFirstPartyTypeKind.ZodObject }); return merged; } // merge< // Incoming extends AnyZodObject, // Augmentation extends Incoming["shape"], // NewOutput extends { // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }, // NewInput extends { // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // } // >( // merging: Incoming // ): ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"], // NewOutput, // NewInput // > { // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } setKey(key, schema) { return this.augment({ [key]: schema }); } // merge( // merging: Incoming // ): //ZodObject = (merging) => { // ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"] // > { // // const mergedShape = objectUtil.mergeShapes( // // this._def.shape(), // // merging._def.shape() // // ); // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } catchall(index) { return new _ZodObject({ ...this._def, catchall: index }); } pick(mask) { const shape = {}; for (const key of util.objectKeys(mask)) { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } } return new _ZodObject({ ...this._def, shape: () => shape }); } omit(mask) { const shape = {}; for (const key of util.objectKeys(this.shape)) { if (!mask[key]) { shape[key] = this.shape[key]; } } return new _ZodObject({ ...this._def, shape: () => shape }); } /** * @deprecated */ deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; for (const key of util.objectKeys(this.shape)) { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } } return new _ZodObject({ ...this._def, shape: () => newShape }); } required(mask) { const newShape = {}; for (const key of util.objectKeys(this.shape)) { if (mask && !mask[key]) { newShape[key] = this.shape[key]; } else { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional2) { newField = newField._def.innerType; } newShape[key] = newField; } } return new _ZodObject({ ...this._def, shape: () => newShape }); } keyof() { return createZodEnum(util.objectKeys(this.shape)); } }; ZodObject2.create = (shape, params) => { return new ZodObject2({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever2.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject2.strictCreate = (shape, params) => { return new ZodObject2({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever2.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject2.lazycreate = (shape, params) => { return new ZodObject2({ shape, unknownKeys: "strip", catchall: ZodNever2.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; var ZodUnion2 = class extends ZodType2 { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_union, unionErrors }); return INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx }), ctx: childCtx }; })).then(handleResults); } else { let dirty = void 0; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues2) => new ZodError2(issues2)); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_union, unionErrors }); return INVALID; } } get options() { return this._def.options; } }; ZodUnion2.create = (types, params) => { return new ZodUnion2({ options: types, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params) }); }; var getDiscriminator = (type) => { if (type instanceof ZodLazy2) { return getDiscriminator(type.schema); } else if (type instanceof ZodEffects) { return getDiscriminator(type.innerType()); } else if (type instanceof ZodLiteral2) { return [type.value]; } else if (type instanceof ZodEnum2) { return type.options; } else if (type instanceof ZodNativeEnum) { return util.objectValues(type.enum); } else if (type instanceof ZodDefault2) { return getDiscriminator(type._def.innerType); } else if (type instanceof ZodUndefined2) { return [void 0]; } else if (type instanceof ZodNull2) { return [null]; } else if (type instanceof ZodOptional2) { return [void 0, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodNullable2) { return [null, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodBranded) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodReadonly2) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodCatch2) { return getDiscriminator(type._def.innerType); } else { return []; } }; var ZodDiscriminatedUnion2 = class _ZodDiscriminatedUnion extends ZodType2 { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator] }); return INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } /** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */ static create(discriminator, options, params) { const optionsMap = /* @__PURE__ */ new Map(); for (const type of options) { const discriminatorValues = getDiscriminator(type.shape[discriminator]); if (!discriminatorValues.length) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type); } } return new _ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params) }); } }; function mergeValues2(a3, b5) { const aType = getParsedType2(a3); const bType = getParsedType2(b5); if (a3 === b5) { return { valid: true, data: a3 }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util.objectKeys(b5); const sharedKeys = util.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a3, ...b5 }; for (const key of sharedKeys) { const sharedValue = mergeValues2(a3[key], b5[key]); if (!sharedValue.valid) { return { valid: false }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { if (a3.length !== b5.length) { return { valid: false }; } const newArray = []; for (let index = 0; index < a3.length; index++) { const itemA = a3[index]; const itemB = b5[index]; const sharedValue = mergeValues2(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a3 === +b5) { return { valid: true, data: a3 }; } else { return { valid: false }; } } var ZodIntersection2 = class extends ZodType2 { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID; } const merged = mergeValues2(parsedLeft.value, parsedRight.value); if (!merged.valid) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_intersection_types }); return INVALID; } if (isDirty(parsedLeft) || isDirty(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })); } } }; ZodIntersection2.create = (left, right, params) => { return new ZodIntersection2({ left, right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params) }); }; var ZodTuple2 = class _ZodTuple extends ZodType2 { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode2.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }); return INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode2.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((x4) => !!x4); if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new _ZodTuple({ ...this._def, rest }); } }; ZodTuple2.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple2({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params) }); }; var ZodRecord2 = class _ZodRecord extends ZodType2 { 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: ZodIssueCode2.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const pairs = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), alwaysSet: key in ctx.data }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof ZodType2) { return new _ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third) }); } return new _ZodRecord({ keyType: ZodString2.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second) }); } }; var ZodMap2 = class extends ZodType2 { 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: ZodIssueCode2.invalid_type, expected: ZodParsedType.map, received: ctx.parsedType }); return INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs = [...ctx.data.entries()].map(([key, value], index) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) }; }); if (ctx.common.async) { const finalMap = /* @__PURE__ */ new Map(); return Promise.resolve().then(async () => { for (const pair of pairs) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = /* @__PURE__ */ new Map(); for (const pair of pairs) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } }; ZodMap2.create = (keyType, valueType, params) => { return new ZodMap2({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params) }); }; var ZodSet2 = class _ZodSet extends ZodType2 { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType }); return INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode2.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode2.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(elements2) { const parsedSet = /* @__PURE__ */ new Set(); for (const element of elements2) { if (element.status === "aborted") return INVALID; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i4) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i4))); if (ctx.common.async) { return Promise.all(elements).then((elements2) => finalizeSet(elements2)); } else { return finalizeSet(elements); } } min(minSize, message) { return new _ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil.toString(message) } }); } max(maxSize, message) { return new _ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil.toString(message) } }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } }; ZodSet2.create = (valueType, params) => { return new ZodSet2({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params) }); }; var ZodFunction = class _ZodFunction extends ZodType2 { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.function, received: ctx.parsedType }); return INVALID; } function makeArgsIssue(args, error40) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x4) => !!x4), issueData: { code: ZodIssueCode2.invalid_arguments, argumentsError: error40 } }); } function makeReturnsIssue(returns, error40) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x4) => !!x4), issueData: { code: ZodIssueCode2.invalid_return_type, returnTypeError: error40 } }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn2 = ctx.data; if (this._def.returns instanceof ZodPromise2) { const me2 = this; return OK(async function(...args) { const error40 = new ZodError2([]); const parsedArgs = await me2._def.args.parseAsync(args, params).catch((e5) => { error40.addIssue(makeArgsIssue(args, e5)); throw error40; }); const result = await Reflect.apply(fn2, this, parsedArgs); const parsedReturns = await me2._def.returns._def.type.parseAsync(result, params).catch((e5) => { error40.addIssue(makeReturnsIssue(result, e5)); throw error40; }); return parsedReturns; }); } else { const me2 = this; return OK(function(...args) { const parsedArgs = me2._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]); } const result = Reflect.apply(fn2, this, parsedArgs.data); const parsedReturns = me2._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new _ZodFunction({ ...this._def, args: ZodTuple2.create(items).rest(ZodUnknown2.create()) }); } returns(returnType) { return new _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 _ZodFunction({ args: args ? args : ZodTuple2.create([]).rest(ZodUnknown2.create()), returns: returns || ZodUnknown2.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params) }); } }; var ZodLazy2 = class extends ZodType2 { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema2 = this._def.getter(); return lazySchema2._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } }; ZodLazy2.create = (getter, params) => { return new ZodLazy2({ getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params) }); }; var ZodLiteral2 = class extends ZodType2 { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode2.invalid_literal, expected: this._def.value }); return INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } }; ZodLiteral2.create = (value, params) => { return new ZodLiteral2({ value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params) }); }; function createZodEnum(values, params) { return new ZodEnum2({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params) }); } var ZodEnum2 = class _ZodEnum extends ZodType2 { _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode2.invalid_type }); return INVALID; } if (!this._cache) { this._cache = new Set(this._def.values); } if (!this._cache.has(input.data)) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode2.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Values() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } extract(values, newDef = this._def) { return _ZodEnum.create(values, { ...this._def, ...newDef }); } exclude(values, newDef = this._def) { return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { ...this._def, ...newDef }); } }; ZodEnum2.create = createZodEnum; var ZodNativeEnum = class extends ZodType2 { _parse(input) { const nativeEnumValues = util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode2.invalid_type }); return INVALID; } if (!this._cache) { this._cache = new Set(util.getValidEnumValues(this._def.values)); } if (!this._cache.has(input.data)) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode2.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get enum() { return this._def.values; } }; ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params) }); }; var ZodPromise2 = class extends ZodType2 { unwrap() { return this._def.type; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.promise, received: ctx.parsedType }); return INVALID; } const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return OK(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap }); })); } }; ZodPromise2.create = (schema, params) => { return new ZodPromise2({ type: schema, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params) }); }; var ZodEffects = class extends ZodType2 { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; const checkCtx = { addIssue: (arg) => { addIssueToContext(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; } }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "preprocess") { const processed = effect.transform(ctx.data, checkCtx); if (ctx.common.async) { return Promise.resolve(processed).then(async (processed2) => { if (status.value === "aborted") return INVALID; const result = await this._def.schema._parseAsync({ data: processed2, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; }); } else { if (status.value === "aborted") return INVALID; const result = this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; } } if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (!isValid(base)) return INVALID; const result = effect.transform(base.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { if (!isValid(base)) return INVALID; return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util.assertNever(effect); } }; ZodEffects.create = (schema, effect, params) => { return new ZodEffects({ schema, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params) }); }; ZodEffects.createWithPreprocess = (preprocess2, schema, params) => { return new ZodEffects({ schema, effect: { type: "preprocess", transform: preprocess2 }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params) }); }; var ZodOptional2 = class extends ZodType2 { _parse(input) { const parsedType4 = this._getType(input); if (parsedType4 === ZodParsedType.undefined) { return OK(void 0); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodOptional2.create = (type, params) => { return new ZodOptional2({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params) }); }; var ZodNullable2 = class extends ZodType2 { _parse(input) { const parsedType4 = this._getType(input); if (parsedType4 === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodNullable2.create = (type, params) => { return new ZodNullable2({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params) }); }; var ZodDefault2 = class extends ZodType2 { _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; } }; ZodDefault2.create = (type, params) => { return new ZodDefault2({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params) }); }; var ZodCatch2 = class extends ZodType2 { _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((result2) => { return { status: "valid", value: result2.status === "valid" ? result2.value : this._def.catchValue({ get error() { return new ZodError2(newCtx.common.issues); }, input: newCtx.data }) }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError2(newCtx.common.issues); }, input: newCtx.data }) }; } } removeCatch() { return this._def.innerType; } }; ZodCatch2.create = (type, params) => { return new ZodCatch2({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params) }); }; var ZodNaN2 = class extends ZodType2 { _parse(input) { const parsedType4 = this._getType(input); if (parsedType4 !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType }); return INVALID; } return { status: "valid", value: input.data }; } }; ZodNaN2.create = (params) => { return new ZodNaN2({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params) }); }; var BRAND = /* @__PURE__ */ Symbol("zod_brand"); var ZodBranded = class extends ZodType2 { _parse(input) { const { ctx } = this._processInputParams(input); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx }); } unwrap() { return this._def.type; } }; var ZodPipeline = class _ZodPipeline extends ZodType2 { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { const handleAsync = async () => { const inResult = await this._def.in._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return DIRTY(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx }); } } } static create(a3, b5) { return new _ZodPipeline({ in: a3, out: b5, typeName: ZodFirstPartyTypeKind.ZodPipeline }); } }; var ZodReadonly2 = class extends ZodType2 { _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; } }; ZodReadonly2.create = (type, params) => { return new ZodReadonly2({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodReadonly, ...processCreateParams(params) }); }; function cleanParams(params, data) { const p2 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; const p22 = typeof p2 === "string" ? { message: p2 } : p2; return p22; } function custom2(check2, _params = {}, fatal) { if (check2) return ZodAny2.create().superRefine((data, ctx) => { const r4 = check2(data); if (r4 instanceof Promise) { return r4.then((r5) => { if (!r5) { const params = cleanParams(_params, data); const _fatal = params.fatal ?? fatal ?? true; ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } }); } if (!r4) { const params = cleanParams(_params, data); const _fatal = params.fatal ?? fatal ?? true; ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } return; }); return ZodAny2.create(); } var late = { object: ZodObject2.lazycreate }; var ZodFirstPartyTypeKind; (function(ZodFirstPartyTypeKind2) { ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); var instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}` }) => custom2((data) => data instanceof cls, params); var stringType = ZodString2.create; var numberType = ZodNumber2.create; var nanType = ZodNaN2.create; var bigIntType = ZodBigInt2.create; var booleanType = ZodBoolean2.create; var dateType = ZodDate2.create; var symbolType = ZodSymbol2.create; var undefinedType = ZodUndefined2.create; var nullType = ZodNull2.create; var anyType = ZodAny2.create; var unknownType = ZodUnknown2.create; var neverType = ZodNever2.create; var voidType = ZodVoid2.create; var arrayType = ZodArray2.create; var objectType = ZodObject2.create; var strictObjectType = ZodObject2.strictCreate; var unionType = ZodUnion2.create; var discriminatedUnionType = ZodDiscriminatedUnion2.create; var intersectionType = ZodIntersection2.create; var tupleType = ZodTuple2.create; var recordType = ZodRecord2.create; var mapType = ZodMap2.create; var setType = ZodSet2.create; var functionType = ZodFunction.create; var lazyType = ZodLazy2.create; var literalType = ZodLiteral2.create; var enumType = ZodEnum2.create; var nativeEnumType = ZodNativeEnum.create; var promiseType = ZodPromise2.create; var effectsType = ZodEffects.create; var optionalType = ZodOptional2.create; var nullableType = ZodNullable2.create; var preprocessType = ZodEffects.createWithPreprocess; var pipelineType = ZodPipeline.create; var ostring = () => stringType().optional(); var onumber = () => numberType().optional(); var oboolean = () => booleanType().optional(); var coerce = { string: ((arg) => ZodString2.create({ ...arg, coerce: true })), number: ((arg) => ZodNumber2.create({ ...arg, coerce: true })), boolean: ((arg) => ZodBoolean2.create({ ...arg, coerce: true })), bigint: ((arg) => ZodBigInt2.create({ ...arg, coerce: true })), date: ((arg) => ZodDate2.create({ ...arg, coerce: true })) }; var NEVER2 = INVALID; // node_modules/eventsource-parser/dist/index.js var ParseError = class extends Error { constructor(message, options) { super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; } }; var LF = 10; var CR = 13; var SPACE = 32; function noop(_arg) { } function createParser(config2) { if (typeof config2 == "function") throw new TypeError( "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?" ); const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config2, pendingFragments = []; let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false; function feed(chunk) { if (terminated) throw new Error( "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing." ); if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) { const trailing2 = processLines(chunk); trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize(); return; } if (chunk.indexOf(` `) === -1 && chunk.indexOf("\r") === -1) { pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize(); return; } pendingFragments.push(chunk); const input = pendingFragments.join(""); pendingFragments.length = 0, pendingFragmentsLength = 0; const trailing = processLines(input); trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize(); } function checkBufferSize() { maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError( new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, { type: "max-buffer-size-exceeded" }) ))); } function processLines(chunk) { let searchIndex = 0; if (chunk.indexOf("\r") === -1) { let lfIndex = chunk.indexOf(` `, searchIndex); for (; lfIndex !== -1; ) { if (searchIndex === lfIndex) { dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(` `, searchIndex); continue; } const firstCharCode = chunk.charCodeAt(searchIndex); if (isDataPrefix(chunk, searchIndex, firstCharCode)) { const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex); if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) { onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(` `, searchIndex); continue; } data = dataLines === 0 ? value : `${data} ${value}`, dataLines++; } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice( chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex ) || void 0 : parseLine(chunk, searchIndex, lfIndex); searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(` `, searchIndex); } return chunk.slice(searchIndex); } for (; searchIndex < chunk.length; ) { const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` `, searchIndex); let lineEnd = -1; if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) break; parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++; } return chunk.slice(searchIndex); } function parseLine(chunk, start, end) { if (start === end) { dispatchEvent(); return; } const firstCharCode = chunk.charCodeAt(start); if (isDataPrefix(chunk, start, firstCharCode)) { const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end); data = dataLines === 0 ? value2 : `${data} ${value2}`, dataLines++; return; } if (isEventPrefix(chunk, start, firstCharCode)) { eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0; return; } if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) { const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end); id = value2.includes("\0") ? void 0 : value2; return; } if (firstCharCode === 58) { if (onComment) { const line22 = chunk.slice(start, end); onComment(line22.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1)); } return; } const line2 = chunk.slice(start, end), fieldSeparatorIndex = line2.indexOf(":"); if (fieldSeparatorIndex === -1) { processField(line2, "", line2); return; } const field = line2.slice(0, fieldSeparatorIndex), offset = line2.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line2.slice(fieldSeparatorIndex + offset); processField(field, value, line2); } function processField(field, value, line2) { switch (field) { case "event": eventType = value || void 0; break; case "data": data = dataLines === 0 ? value : `${data} ${value}`, dataLines++; break; case "id": id = value.includes("\0") ? void 0 : value; break; case "retry": /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError( new ParseError(`Invalid \`retry\` value: "${value}"`, { type: "invalid-retry", value, line: line2 }) ); break; default: onError( new ParseError( `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { type: "unknown-field", field, value, line: line2 } ) ); break; } } function dispatchEvent() { dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0; } function reset(options = {}) { if (options.consume && pendingFragments.length > 0) { const incompleteLine = pendingFragments.join(""); parseLine(incompleteLine, 0, incompleteLine.length); } isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false; } return { feed, reset }; } function isDataPrefix(chunk, i4, firstCharCode) { return firstCharCode === 100 && chunk.charCodeAt(i4 + 1) === 97 && chunk.charCodeAt(i4 + 2) === 116 && chunk.charCodeAt(i4 + 3) === 97 && chunk.charCodeAt(i4 + 4) === 58; } function isEventPrefix(chunk, i4, firstCharCode) { return firstCharCode === 101 && chunk.charCodeAt(i4 + 1) === 118 && chunk.charCodeAt(i4 + 2) === 101 && chunk.charCodeAt(i4 + 3) === 110 && chunk.charCodeAt(i4 + 4) === 116 && chunk.charCodeAt(i4 + 5) === 58; } // node_modules/eventsource-parser/dist/stream.js var EventSourceParserStream = class extends TransformStream { constructor({ onError, onRetry, onComment, maxBufferSize } = {}) { let parser; super({ start(controller) { parser = createParser({ onEvent: (event) => { controller.enqueue(event); }, onError(error40) { typeof onError == "function" && onError(error40), (onError === "terminate" || error40.type === "max-buffer-size-exceeded") && controller.error(error40); }, onRetry, onComment, maxBufferSize }); }, transform(chunk) { parser.feed(chunk); } }); } }; // node_modules/@workflow/serde/dist/index.js var WORKFLOW_SERIALIZE = /* @__PURE__ */ Symbol.for("workflow-serialize"); var WORKFLOW_DESERIALIZE = /* @__PURE__ */ Symbol.for("workflow-deserialize"); // node_modules/@ai-sdk/provider-utils/dist/index.js function asArray(value) { return value === void 0 ? [] : Array.isArray(value) ? value : [value]; } function combineHeaders(...headers) { return headers.reduce( (combinedHeaders, currentHeaders) => ({ ...combinedHeaders, ...currentHeaders != null ? currentHeaders : {} }), {} ); } function removeUndefinedEntries(record2) { return Object.fromEntries( Object.entries(record2).filter(([_key, value]) => value != null) ); } async function delay(delayInMs, options) { if (delayInMs == null) { return Promise.resolve(); } const signal = options == null ? void 0 : options.abortSignal; return new Promise((resolve22, reject) => { if (signal == null ? void 0 : signal.aborted) { reject(createAbortError()); return; } const timeoutId = setTimeout(() => { cleanup(); resolve22(); }, delayInMs); const cleanup = () => { clearTimeout(timeoutId); signal == null ? void 0 : signal.removeEventListener("abort", onAbort); }; const onAbort = () => { cleanup(); reject(createAbortError()); }; signal == null ? void 0 : signal.addEventListener("abort", onAbort); }); } function createAbortError() { return new DOMException("Delay was aborted", "AbortError"); } function getWebSocketConstructor(webSocket) { const WebSocketConstructor = webSocket != null ? webSocket : globalThis.WebSocket; if (WebSocketConstructor == null) { throw new Error("No WebSocket implementation available."); } return WebSocketConstructor; } function toWebSocketUrl(url2) { const wsUrl = new URL(url2); if (wsUrl.protocol === "http:") { wsUrl.protocol = "ws:"; } else if (wsUrl.protocol === "https:") { wsUrl.protocol = "wss:"; } return wsUrl; } var textDecoder = new TextDecoder(); async function readWebSocketMessageText(data) { if (typeof data === "string") return data; if (data instanceof ArrayBuffer) return textDecoder.decode(data); if (ArrayBuffer.isView(data)) { return textDecoder.decode(data); } if (typeof Blob !== "undefined" && data instanceof Blob) { return data.text(); } return String(data); } var WEBSOCKET_OPEN_STATE = 1; async function waitForWebSocketBufferDrain(socket, { highWaterMark = 1024 * 1024, pollIntervalMs = 20, abortSignal } = {}) { var _a25; while (socket.readyState === WEBSOCKET_OPEN_STATE && ((_a25 = socket.bufferedAmount) != null ? _a25 : 0) > highWaterMark) { if ((abortSignal == null ? void 0 : abortSignal.aborted) === true) { return; } await delay(pollIntervalMs); } } function connectToWebSocket({ url: url2, protocols, headers, webSocket, abortSignal, onOpen, onMessageText, onProcessingError, onSocketError, onClose, onAbort }) { var _a25; let socket; let abortListener; const close = (code) => { if (abortListener != null) { abortSignal == null ? void 0 : abortSignal.removeEventListener("abort", abortListener); abortListener = void 0; } try { socket == null ? void 0 : socket.close(code); } catch (e5) { } }; if (abortSignal == null ? void 0 : abortSignal.aborted) { onAbort == null ? void 0 : onAbort((_a25 = abortSignal.reason) != null ? _a25 : new Error("Aborted")); return { socket: void 0, close }; } try { const WebSocketConstructor = getWebSocketConstructor(webSocket); socket = new WebSocketConstructor(url2, protocols, { headers: removeUndefinedEntries(headers != null ? headers : {}) }); } catch (error40) { onProcessingError(error40); return { socket: void 0, close }; } if (abortSignal != null && onAbort != null) { abortListener = () => { var _a34; return onAbort((_a34 = abortSignal.reason) != null ? _a34 : new Error("Aborted")); }; abortSignal.addEventListener("abort", abortListener, { once: true }); } const openedSocket = socket; socket.onopen = () => { try { onOpen == null ? void 0 : onOpen(openedSocket); } catch (error40) { onProcessingError(error40); } }; let tail = Promise.resolve(); socket.onmessage = (event) => { tail = tail.then(() => readWebSocketMessageText(event.data)).then((text2) => onMessageText(text2)).catch(onProcessingError); }; socket.onerror = () => { tail = tail.then(() => onSocketError == null ? void 0 : onSocketError()).catch(onProcessingError); }; socket.onclose = () => { tail = tail.then(() => onClose == null ? void 0 : onClose()).catch(onProcessingError); }; return { socket, close }; } var { btoa: btoa2, atob: atob2 } = globalThis; function convertBase64ToUint8Array(base64String) { const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/"); const latin1string = atob2(base64Url); return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0)); } function convertUint8ArrayToBase64(array3) { let latin1string = ""; for (let i4 = 0; i4 < array3.length; i4++) { latin1string += String.fromCodePoint(array3[i4]); } return btoa2(latin1string); } function convertToBase64(value) { return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value; } function convertInlineFileDataToUint8Array(data) { if (data.type === "text") { return new TextEncoder().encode(data.text); } if (data.data instanceof Uint8Array) { return data.data; } if (data.data instanceof ArrayBuffer) { return new Uint8Array(data.data); } return convertBase64ToUint8Array(data.data); } function convertToFormData(input, options = {}) { const { useArrayBrackets = true } = options; const formData = new FormData(); for (const [key, value] of Object.entries(input)) { if (value == null) { continue; } if (Array.isArray(value)) { if (value.length === 1) { formData.append(key, value[0]); continue; } const arrayKey = useArrayBrackets ? `${key}[]` : key; for (const item of value) { formData.append(arrayKey, item); } continue; } formData.append(key, value); } return formData; } function createToolNameMapping({ tools: tools2 = [], providerToolNames }) { const customToolNameToProviderToolName = {}; const providerToolNameToCustomToolName = {}; for (const tool2 of tools2) { if (tool2.type === "provider" && tool2.id in providerToolNames) { const providerToolName = providerToolNames[tool2.id]; customToolNameToProviderToolName[tool2.name] = providerToolName; providerToolNameToCustomToolName[providerToolName] = tool2.name; } } return { toProviderToolName: (customToolName) => { var _a25; return (_a25 = customToolNameToProviderToolName[customToolName]) != null ? _a25 : customToolName; }, toCustomToolName: (providerToolName) => { var _a25; return (_a25 = providerToolNameToCustomToolName[providerToolName]) != null ? _a25 : providerToolName; } }; } var imageMediaTypeSignatures = [ { mediaType: "image/gif", bytesPrefix: [71, 73, 70] // GIF }, { mediaType: "image/png", bytesPrefix: [137, 80, 78, 71] // PNG }, { mediaType: "image/jpeg", bytesPrefix: [255, 216] // JPEG }, { mediaType: "image/webp", bytesPrefix: [ 82, 73, 70, 70, // "RIFF" null, null, null, null, // file size (variable) 87, 69, 66, 80 // "WEBP" ] }, { mediaType: "image/bmp", bytesPrefix: [66, 77] }, { mediaType: "image/tiff", bytesPrefix: [73, 73, 42, 0] }, { mediaType: "image/tiff", bytesPrefix: [77, 77, 0, 42] }, { mediaType: "image/avif", bytesPrefix: [ 0, 0, 0, 32, 102, 116, 121, 112, 97, 118, 105, 102 ] }, { mediaType: "image/heic", bytesPrefix: [ 0, 0, 0, 32, 102, 116, 121, 112, 104, 101, 105, 99 ] } ]; var documentMediaTypeSignatures = [ { mediaType: "application/pdf", bytesPrefix: [37, 80, 68, 70] // %PDF } ]; var audioMediaTypeSignatures = [ { mediaType: "audio/mpeg", bytesPrefix: [255, 251] }, { mediaType: "audio/mpeg", bytesPrefix: [255, 250] }, { mediaType: "audio/mpeg", bytesPrefix: [255, 243] }, { mediaType: "audio/mpeg", bytesPrefix: [255, 242] }, { mediaType: "audio/mpeg", bytesPrefix: [255, 227] }, { mediaType: "audio/mpeg", bytesPrefix: [255, 226] }, { mediaType: "audio/wav", bytesPrefix: [ 82, // R 73, // I 70, // F 70, // F null, null, null, null, 87, // W 65, // A 86, // V 69 // E ] }, { mediaType: "audio/ogg", bytesPrefix: [79, 103, 103, 83] }, { mediaType: "audio/flac", bytesPrefix: [102, 76, 97, 67] }, { mediaType: "audio/aac", bytesPrefix: [64, 21, 0, 0] }, { mediaType: "audio/mp4", bytesPrefix: [102, 116, 121, 112] }, { mediaType: "audio/webm", bytesPrefix: [26, 69, 223, 163] } ]; var videoMediaTypeSignatures = [ { mediaType: "video/mp4", bytesPrefix: [ 0, 0, 0, null, 102, 116, 121, 112 // ftyp ] }, { mediaType: "video/webm", bytesPrefix: [26, 69, 223, 163] // EBML }, { mediaType: "video/quicktime", bytesPrefix: [ 0, 0, 0, 20, 102, 116, 121, 112, 113, 116 // ftypqt ] }, { mediaType: "video/x-msvideo", bytesPrefix: [82, 73, 70, 70] // RIFF (AVI) } ]; var stripID3 = (data) => { const bytes = typeof data === "string" ? convertBase64ToUint8Array(data) : data; const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127; return bytes.slice(id3Size + 10); }; function stripID3TagsIfPresent(data) { const hasId3 = typeof data === "string" && data.startsWith("SUQz") || typeof data !== "string" && data.length > 10 && data[0] === 73 && // 'I' data[1] === 68 && // 'D' data[2] === 51; return hasId3 ? stripID3(data) : data; } function detectMediaTypeBySignatures({ data, signatures }) { const processedData = stripID3TagsIfPresent(data); const bytes = typeof processedData === "string" ? convertBase64ToUint8Array( processedData.substring(0, Math.min(processedData.length, 24)) ) : processedData; for (const signature of signatures) { if (bytes.length >= signature.bytesPrefix.length && signature.bytesPrefix.every( (byte, index) => byte === null || bytes[index] === byte )) { return signature.mediaType; } } return void 0; } var topLevelSignatureTables = { image: imageMediaTypeSignatures, audio: audioMediaTypeSignatures, video: videoMediaTypeSignatures, application: documentMediaTypeSignatures }; function detectMediaType({ data, topLevelType }) { if (topLevelType === void 0) { return detectMediaTypeBySignatures({ data, signatures: [ ...imageMediaTypeSignatures, ...documentMediaTypeSignatures, ...audioMediaTypeSignatures, ...videoMediaTypeSignatures ] }); } const signatures = topLevelSignatureTables[topLevelType]; if (signatures === void 0) { return void 0; } return detectMediaTypeBySignatures({ data, signatures }); } function getTopLevelMediaType(mediaType) { const slashIndex = mediaType.indexOf("/"); return slashIndex === -1 ? mediaType : mediaType.substring(0, slashIndex); } function isFullMediaType(mediaType) { const slashIndex = mediaType.indexOf("/"); if (slashIndex === -1) { return false; } const subtype = mediaType.substring(slashIndex + 1); return subtype.length > 0 && subtype !== "*"; } async function cancelResponseBody(response) { var _a25; try { await ((_a25 = response.body) == null ? void 0 : _a25.cancel()); } catch (e5) { } } var name15 = "AI_DownloadError"; var marker16 = `vercel.ai.error.${name15}`; var symbol16 = Symbol.for(marker16); var _a16; var _b16; var DownloadError = class extends (_b16 = AISDKError, _a16 = symbol16, _b16) { constructor({ url: url2, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url2}: ${statusCode} ${statusText}` : `Failed to download ${url2}: ${cause}` }) { super({ name: name15, message, cause }); this[_a16] = true; this.url = url2; this.statusCode = statusCode; this.statusText = statusText; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker16); } }; function isBrowserRuntime(globalThisAny = globalThis) { return globalThisAny.window != null; } function isSameOrigin(url2, baseUrl) { try { return new URL(url2).origin === new URL(baseUrl).origin; } catch (e5) { return false; } } var BLOCKED_REQUEST_HEADERS = [ // Hop-by-hop / transport (RFC 7230 §6.1) "connection", "keep-alive", "te", "trailer", "transfer-encoding", "upgrade", // Host / virtual-host routing "host", // Proxy / origin spoofing "forwarded", "proxy-authorization", "via", "x-forwarded-for", "x-forwarded-host", "x-forwarded-proto", "x-real-ip", // Cloud metadata (GCP, AWS IMDSv1/v2, Azure, Alibaba, DigitalOcean) "metadata", "metadata-flavor", "x-aws-ec2-metadata-token", "x-metadata-token", // Session / cookie "cookie", "set-cookie" ]; function sanitizeRequestHeaders(input) { const headers = new Headers(input); for (const name24 of BLOCKED_REQUEST_HEADERS) { headers.delete(name24); } return headers; } function validateDownloadUrl(url2) { let parsed; try { parsed = new URL(url2); } catch (e5) { throw new DownloadError({ url: url2, message: `Invalid URL: ${url2}` }); } if (parsed.protocol === "data:") { return; } if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { throw new DownloadError({ url: url2, message: `URL scheme must be http, https, or data, got ${parsed.protocol}` }); } const hostname2 = parsed.hostname.toLowerCase().replace(/\.+$/, ""); if (!hostname2) { throw new DownloadError({ url: url2, message: `URL must have a hostname` }); } if (hostname2 === "localhost" || hostname2.endsWith(".local") || hostname2.endsWith(".localhost")) { throw new DownloadError({ url: url2, message: `URL with hostname ${hostname2} is not allowed` }); } if (hostname2.startsWith("[") && hostname2.endsWith("]")) { const ipv63 = hostname2.slice(1, -1); if (isPrivateIPv6(ipv63)) { throw new DownloadError({ url: url2, message: `URL with IPv6 address ${hostname2} is not allowed` }); } return; } if (isIPv4(hostname2)) { if (isPrivateIPv4(hostname2)) { throw new DownloadError({ url: url2, message: `URL with IP address ${hostname2} is not allowed` }); } return; } } function isIPv4(hostname2) { const parts = hostname2.split("."); if (parts.length !== 4) return false; return parts.every((part) => { const num3 = Number(part); return Number.isInteger(num3) && num3 >= 0 && num3 <= 255 && String(num3) === part; }); } function isPrivateIPv4(ip) { const parts = ip.split(".").map(Number); const [a3, b5, c2] = parts; if (a3 === 0) return true; if (a3 === 10) return true; if (a3 === 100 && b5 >= 64 && b5 <= 127) return true; if (a3 === 127) return true; if (a3 === 169 && b5 === 254) return true; if (a3 === 172 && b5 >= 16 && b5 <= 31) return true; if (a3 === 192 && b5 === 0 && c2 === 0) return true; if (a3 === 192 && b5 === 0 && c2 === 2) return true; if (a3 === 192 && b5 === 168) return true; if (a3 === 198 && (b5 === 18 || b5 === 19)) return true; if (a3 === 198 && b5 === 51 && c2 === 100) return true; if (a3 === 203 && b5 === 0 && c2 === 113) return true; if (a3 >= 224) return true; return false; } function parseIPv6(ip) { let address = ip.toLowerCase(); const zoneIndex = address.indexOf("%"); if (zoneIndex !== -1) { address = address.slice(0, zoneIndex); } const halves = address.split("::"); if (halves.length > 2) return null; const toGroups = (segment2) => { if (segment2 === "") return []; const groups = []; const parts = segment2.split(":"); for (let i4 = 0; i4 < parts.length; i4++) { const part = parts[i4]; if (part.includes(".")) { if (i4 !== parts.length - 1 || !isIPv4(part)) return null; const [a3, b5, c2, d2] = part.split(".").map(Number); groups.push(a3 << 8 | b5, c2 << 8 | d2); continue; } if (!/^[0-9a-f]{1,4}$/.test(part)) return null; groups.push(parseInt(part, 16)); } return groups; }; const head = toGroups(halves[0]); if (head === null) return null; if (halves.length === 2) { const tail = toGroups(halves[1]); if (tail === null) return null; const fill = 8 - head.length - tail.length; if (fill < 0) return null; return [...head, ...new Array(fill).fill(0), ...tail]; } return head.length === 8 ? head : null; } function isPrivateIPv6(ip) { const groups = parseIPv6(ip); if (groups === null) return true; const topZero = (count) => groups.slice(0, count).every((group) => group === 0); if (topZero(7) && (groups[7] === 0 || groups[7] === 1)) return true; if ((groups[0] & 65024) === 64512) return true; if ((groups[0] & 65472) === 65152) return true; if ((groups[0] & 65472) === 65216) return true; if ((groups[0] & 65280) === 65280) return true; if (groups[0] === 8193 && groups[1] === 3512) return true; if (groups[0] === 16383 && (groups[1] & 61440) === 0) return true; const embedsIPv4 = ( // ::/96 — IPv4-compatible (deprecated) topZero(6) || // ::ffff:0:0/96 — IPv4-mapped (ffff in group 5) topZero(5) && groups[5] === 65535 || // ::ffff:0:0/96 — IPv4-translated form (ffff in group 4, group 5 zero) topZero(4) && groups[4] === 65535 && groups[5] === 0 || // 64:ff9b::/96 — NAT64 well-known prefix groups[0] === 100 && groups[1] === 65435 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0 || // 64:ff9b:1::/48 — NAT64 local-use prefix groups[0] === 100 && groups[1] === 65435 && groups[2] === 1 ); if (embedsIPv4) { const a3 = groups[6] >> 8 & 255; const b5 = groups[6] & 255; const c2 = groups[7] >> 8 & 255; const d2 = groups[7] & 255; return isPrivateIPv4(`${a3}.${b5}.${c2}.${d2}`); } return false; } var MAX_DOWNLOAD_REDIRECTS = 10; var REDIRECT_STATUS_CODES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]); async function fetchWithValidatedRedirects({ url: url2, headers, abortSignal, maxRedirects = MAX_DOWNLOAD_REDIRECTS, fetch: fetch2 = globalThis.fetch, trustedOrigin }) { let currentHeaders = headers === void 0 ? void 0 : sanitizeRequestHeaders(headers); const perHopInit = (redirect) => { const init = { signal: abortSignal, redirect }; if (currentHeaders !== void 0) { init.headers = new Headers(currentHeaders); } return init; }; let currentUrl = url2; for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) { if (trustedOrigin === void 0 || !isSameOrigin(currentUrl, trustedOrigin)) { validateDownloadUrl(currentUrl); } const response = await fetch2(currentUrl, perHopInit("manual")); if (response.type === "opaqueredirect") { if (!isBrowserRuntime()) { throw new DownloadError({ url: url2, message: `Redirect from ${currentUrl} could not be validated and was blocked` }); } return await fetch2(currentUrl, perHopInit("follow")); } const location = response.headers.get("location"); if (REDIRECT_STATUS_CODES.has(response.status) && location) { await cancelResponseBody(response); const nextUrl = new URL(location, currentUrl).toString(); if (currentHeaders !== void 0 && !isSameOrigin(nextUrl, currentUrl)) { const userAgent = currentHeaders.get("user-agent"); currentHeaders = new Headers( userAgent == null ? void 0 : { "user-agent": userAgent } ); } currentUrl = nextUrl; continue; } return response; } throw new DownloadError({ url: url2, message: `Too many redirects (max ${maxRedirects})` }); } var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024; async function readResponseWithSizeLimit({ response, url: url2, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE }) { const contentLength = response.headers.get("content-length"); if (contentLength != null) { const length = parseInt(contentLength, 10); if (!isNaN(length) && length > maxBytes) { await cancelResponseBody(response); throw new DownloadError({ url: url2, message: `Download of ${url2} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).` }); } } const body = response.body; if (body == null) { return new Uint8Array(0); } const reader = body.getReader(); const chunks = []; let totalBytes = 0; try { while (true) { const { done, value } = await reader.read(); if (done) { break; } totalBytes += value.length; if (totalBytes > maxBytes) { throw new DownloadError({ url: url2, message: `Download of ${url2} exceeded maximum size of ${maxBytes} bytes.` }); } chunks.push(value); } } finally { try { await reader.cancel(); } finally { reader.releaseLock(); } } const result = new Uint8Array(totalBytes); let offset = 0; for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.length; } return result; } async function downloadBlob(url2, options) { var _a25, _b23; try { const response = await fetchWithValidatedRedirects({ url: url2, abortSignal: options == null ? void 0 : options.abortSignal }); if (!response.ok) { await cancelResponseBody(response); throw new DownloadError({ url: url2, statusCode: response.status, statusText: response.statusText }); } const data = await readResponseWithSizeLimit({ response, url: url2, maxBytes: (_a25 = options == null ? void 0 : options.maxBytes) != null ? _a25 : DEFAULT_MAX_DOWNLOAD_SIZE }); const contentType = (_b23 = response.headers.get("content-type")) != null ? _b23 : void 0; return new Blob([data], contentType ? { type: contentType } : void 0); } catch (error40) { if (DownloadError.isInstance(error40)) { throw error40; } throw new DownloadError({ url: url2, cause: error40 }); } } function extractResponseHeaders(response) { return Object.fromEntries([...response.headers]); } function filterNullable(...values) { return values.filter((value) => value != null); } var createIdGenerator = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => { const generator = () => { const alphabetLength = alphabet.length; const chars = new Array(size); for (let i4 = 0; i4 < size; i4++) { chars[i4] = alphabet[Math.random() * alphabetLength | 0]; } return chars.join(""); }; if (prefix == null) { return generator; } if (alphabet.includes(separator)) { throw new InvalidArgumentError({ argument: "separator", message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".` }); } return () => `${prefix}${separator}${generator()}`; }; var generateId = createIdGenerator(); function isAbortError(error40) { return (error40 instanceof Error || error40 instanceof DOMException) && (error40.name === "AbortError" || error40.name === "ResponseAborted" || // Next.js error40.name === "TimeoutError"); } var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"]; var BUN_ERROR_CODES = [ "ConnectionRefused", "ConnectionClosed", "FailedToOpenSocket", "ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "EPIPE" ]; function isBunNetworkError(error40) { if (!(error40 instanceof Error)) { return false; } const code = error40.code; if (typeof code === "string" && BUN_ERROR_CODES.includes(code)) { return true; } return false; } function handleFetchError({ error: error40, url: url2, requestBodyValues }) { if (isAbortError(error40)) { return error40; } if (error40 instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error40.message.toLowerCase())) { const cause = error40.cause; if (cause != null) { return new APICallError({ message: `Cannot connect to API: ${cause.message}`, cause, url: url2, requestBodyValues, isRetryable: true // retry when network error }); } } if (isBunNetworkError(error40)) { return new APICallError({ message: `Cannot connect to API: ${error40.message}`, cause: error40, url: url2, requestBodyValues, isRetryable: true }); } return error40; } function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) { var _a25, _b23, _c; if (globalThisAny.window) { return `runtime/browser`; } if ((_a25 = globalThisAny.navigator) == null ? void 0 : _a25.userAgent) { return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`; } if ((_c = (_b23 = globalThisAny.process) == null ? void 0 : _b23.versions) == null ? void 0 : _c.node) { return `runtime/node.js/${globalThisAny.process.version.substring(0)}`; } if (globalThisAny.EdgeRuntime) { return `runtime/vercel-edge`; } return "runtime/unknown"; } function normalizeHeaders(headers) { if (headers == null) { return {}; } const normalized = {}; if (headers instanceof Headers) { headers.forEach((value, key) => { normalized[key.toLowerCase()] = value; }); } else { if (!Array.isArray(headers)) { headers = Object.entries(headers); } for (const [key, value] of headers) { if (value != null) { normalized[key.toLowerCase()] = value; } } } return normalized; } function withUserAgentSuffix(headers, ...userAgentSuffixParts) { const normalizedHeaders = new Headers(normalizeHeaders(headers)); const currentUserAgentHeader = normalizedHeaders.get("user-agent") || ""; normalizedHeaders.set( "user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ") ); return Object.fromEntries(normalizedHeaders.entries()); } var VERSION = true ? "5.0.11" : "0.0.0-test"; var getOriginalFetch = () => globalThis.fetch; var getFromApi = async ({ url: url2, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch(), validateUrl, credentialedOrigin, trustedOrigin }) => { try { const outgoingHeaders = credentialedOrigin !== void 0 && !isSameOrigin(url2, credentialedOrigin) ? {} : headers; const requestHeaders = withUserAgentSuffix( outgoingHeaders, `ai-sdk/provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent() ); const response = validateUrl ? await fetchWithValidatedRedirects({ url: url2, headers: requestHeaders, abortSignal, fetch: fetch2, trustedOrigin }) : await fetch2(url2, { method: "GET", headers: requestHeaders, signal: abortSignal }); const responseHeaders = extractResponseHeaders(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url: url2, requestBodyValues: {} }); } catch (error40) { if (isAbortError(error40) || APICallError.isInstance(error40)) { throw error40; } throw new APICallError({ message: "Failed to process error response", cause: error40, statusCode: response.status, url: url2, responseHeaders, requestBodyValues: {} }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url: url2, requestBodyValues: {} }); } catch (error40) { if (error40 instanceof Error) { if (isAbortError(error40) || APICallError.isInstance(error40)) { throw error40; } } throw new APICallError({ message: "Failed to process successful response", cause: error40, statusCode: response.status, url: url2, responseHeaders, requestBodyValues: {} }); } } catch (error40) { throw handleFetchError({ error: error40, url: url2, requestBodyValues: {} }); } }; function isBuffer(value) { var _a25, _b23; return (_b23 = (_a25 = globalThis.Buffer) == null ? void 0 : _a25.isBuffer(value)) != null ? _b23 : false; } function isNonNullable(value) { return value != null; } function isProviderReference(data) { return typeof data === "object" && data !== null && !(data instanceof Uint8Array) && !(data instanceof URL) && !(data instanceof ArrayBuffer) && !isBuffer(data) && !("type" in data); } function isUrlSupported({ mediaType, url: url2, supportedUrls }) { url2 = url2.toLowerCase(); mediaType = mediaType.toLowerCase(); const isTopLevelOnly = !mediaType.includes("/"); return Object.entries(supportedUrls).map(([key, value]) => { const mediaType2 = key.toLowerCase(); return mediaType2 === "*" || mediaType2 === "*/*" ? { mediaTypePrefix: "", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\*/, ""), regexes: value }; }).filter(({ mediaTypePrefix }) => { if (mediaTypePrefix === "") { return true; } if (isTopLevelOnly) { return `${mediaType}/` === mediaTypePrefix; } return mediaType.startsWith(mediaTypePrefix); }).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url2)); } function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName = "apiKey", description }) { if (typeof apiKey === "string") { return apiKey; } if (apiKey != null) { throw new LoadAPIKeyError({ message: `${description} API key must be a string.` }); } if (typeof process === "undefined") { 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 (apiKey == null) { throw new LoadAPIKeyError({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.` }); } if (typeof apiKey !== "string") { 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 (typeof settingValue === "string") { return settingValue; } if (settingValue != null || typeof process === "undefined") { return void 0; } settingValue = process.env[environmentVariableName]; if (settingValue == null || typeof settingValue !== "string") { return void 0; } return settingValue; } function isCustomReasoning(reasoning) { return reasoning !== void 0 && reasoning !== "provider-default"; } function mediaTypeToExtension(mediaType) { var _a25; const [_type, subtype = ""] = mediaType.toLowerCase().split("/"); return (_a25 = { mpeg: "mp3", "x-wav": "wav", opus: "ogg", mp4: "m4a", "x-m4a": "m4a" }[subtype]) != null ? _a25 : 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 _parse2(text2) { const obj = JSON.parse(text2); if (obj === null || typeof obj !== "object") { return obj; } if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) { return obj; } return filter(obj); } function filter(obj) { let next = [obj]; while (next.length) { const nodes = next; next = []; for (const node of nodes) { if (Object.prototype.hasOwnProperty.call(node, "__proto__")) { throw new SyntaxError("Object contains forbidden prototype property"); } if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { throw new SyntaxError("Object contains forbidden prototype property"); } for (const key in node) { const value = node[key]; if (value && typeof value === "object") { next.push(value); } } } } return obj; } function secureJsonParse(text2) { const { stackTraceLimit } = Error; try { Error.stackTraceLimit = 0; } catch (e5) { return _parse2(text2); } try { return _parse2(text2); } finally { Error.stackTraceLimit = stackTraceLimit; } } function addAdditionalPropertiesToJsonSchema(jsonSchema2) { if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) { jsonSchema2.additionalProperties = false; const { properties } = jsonSchema2; if (properties != null) { for (const key of Object.keys(properties)) { properties[key] = visit(properties[key]); } } } if (jsonSchema2.items != null) { jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items); } if (jsonSchema2.anyOf != null) { jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit); } if (jsonSchema2.allOf != null) { jsonSchema2.allOf = jsonSchema2.allOf.map(visit); } if (jsonSchema2.oneOf != null) { jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit); } const { definitions } = jsonSchema2; if (definitions != null) { for (const key of Object.keys(definitions)) { definitions[key] = visit(definitions[key]); } } return jsonSchema2; } function visit(def) { if (typeof def === "boolean") return def; return addAdditionalPropertiesToJsonSchema(def); } var ignoreOverride = /* @__PURE__ */ Symbol( "Let zodToJsonSchema decide on which parser to use" ); var defaultOptions = { name: void 0, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "format:date-time", mapStrategy: "entries", removeAdditionalStrategy: "passthrough", allowedAdditionalProperties: true, rejectedAdditionalProperties: false, definitionPath: "definitions", strictUnions: false, definitions: {}, errorMessages: false, patternStrategy: "escape", applyRegexFlags: false, emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref" }; var getDefaultOptions = (options) => typeof options === "string" ? { ...defaultOptions, name: options } : { ...defaultOptions, ...options }; function parseAnyDef() { return {}; } function parseArrayDef(def, refs) { var _a25, _b23, _c; const res = { type: "array" }; if (((_a25 = def.type) == null ? void 0 : _a25._def) && ((_c = (_b23 = def.type) == null ? void 0 : _b23._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) { res.items = parseDef(def.type._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); } if (def.minLength) { res.minItems = def.minLength.value; } if (def.maxLength) { res.maxItems = def.maxLength.value; } if (def.exactLength) { res.minItems = def.exactLength.value; res.maxItems = def.exactLength.value; } return res; } function parseBigintDef(def) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check2 of def.checks) { switch (check2.kind) { case "min": if (check2.inclusive) { res.minimum = check2.value; } else { res.exclusiveMinimum = check2.value; } break; case "max": if (check2.inclusive) { res.maximum = check2.value; } else { res.exclusiveMaximum = check2.value; } break; case "multipleOf": res.multipleOf = check2.value; break; } } return res; } function parseBooleanDef() { return { type: "boolean" }; } function parseBrandedDef(_def, refs) { return parseDef(_def.type._def, refs); } var parseCatchDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; function parseDateDef(def, refs, overrideDateStrategy) { const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy; if (Array.isArray(strategy)) { return { anyOf: strategy.map((item) => parseDateDef(def, refs, item)) }; } switch (strategy) { case "string": case "format:date-time": return { type: "string", format: "date-time" }; case "format:date": return { type: "string", format: "date" }; case "integer": return integerDateParser(def); } } var integerDateParser = (def) => { const res = { type: "integer", format: "unix-time" }; for (const check2 of def.checks) { switch (check2.kind) { case "min": res.minimum = check2.value; break; case "max": res.maximum = check2.value; break; } } return res; }; function parseDefaultDef(_def, refs) { return { ...parseDef(_def.innerType._def, refs), default: _def.defaultValue() }; } function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(); } function parseEnumDef(def) { return { type: "string", enum: Array.from(def.values) }; } var isJsonSchema7AllOfType = (type) => { if ("type" in type && type.type === "string") return false; return "allOf" in type; }; function parseIntersectionDef(def, refs) { const allOf = [ parseDef(def.left._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }), parseDef(def.right._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "1"] }) ].filter((x4) => !!x4); const mergedAllOf = []; allOf.forEach((schema) => { if (isJsonSchema7AllOfType(schema)) { mergedAllOf.push(...schema.allOf); } else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const { additionalProperties: _additionalProperties, ...rest } = schema; nestedSchema = rest; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf } : void 0; } function parseLiteralDef(def) { const parsedType4 = typeof def.value; if (parsedType4 !== "bigint" && parsedType4 !== "number" && parsedType4 !== "boolean" && parsedType4 !== "string") { return { type: Array.isArray(def.value) ? "array" : "object" }; } return { type: parsedType4 === "bigint" ? "integer" : parsedType4, const: def.value }; } var emojiRegex2 = void 0; var zodPatterns = { /** * `c` was changed to `[cC]` to replicate /i flag */ cuid: /^[cC][^\s-]{8,}$/, cuid2: /^[0-9a-z]+$/, ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, /** * `a-z` was added to replicate /i flag */ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, /** * Constructed a valid Unicode RegExp * * Lazily instantiate since this type of regex isn't supported * in all envs (e.g. React Native). * * See: * https://github.com/colinhacks/zod/issues/2433 * Fix in Zod: * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b */ emoji: () => { if (emojiRegex2 === void 0) { emojiRegex2 = RegExp( "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u" ); } return emojiRegex2; }, /** * Unused */ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, /** * Unused */ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, /** * Unused */ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, nanoid: /^[a-zA-Z0-9_-]{21}$/, jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ }; function parseStringDef(def, refs) { const res = { type: "string" }; if (def.checks) { for (const check2 of def.checks) { switch (check2.kind) { case "min": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value; break; case "max": res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value; break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat(res, "email", check2.message, refs); break; case "format:idn-email": addFormat(res, "idn-email", check2.message, refs); break; case "pattern:zod": addPattern(res, zodPatterns.email, check2.message, refs); break; } break; case "url": addFormat(res, "uri", check2.message, refs); break; case "uuid": addFormat(res, "uuid", check2.message, refs); break; case "regex": addPattern(res, check2.regex, check2.message, refs); break; case "cuid": addPattern(res, zodPatterns.cuid, check2.message, refs); break; case "cuid2": addPattern(res, zodPatterns.cuid2, check2.message, refs); break; case "startsWith": addPattern( res, RegExp(`^${escapeLiteralCheckValue(check2.value, refs)}`), check2.message, refs ); break; case "endsWith": addPattern( res, RegExp(`${escapeLiteralCheckValue(check2.value, refs)}$`), check2.message, refs ); break; case "datetime": addFormat(res, "date-time", check2.message, refs); break; case "date": addFormat(res, "date", check2.message, refs); break; case "time": addFormat(res, "time", check2.message, refs); break; case "duration": addFormat(res, "duration", check2.message, refs); break; case "length": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value; res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value; break; case "includes": { addPattern( res, RegExp(escapeLiteralCheckValue(check2.value, refs)), check2.message, refs ); break; } case "ip": { if (check2.version !== "v6") { addFormat(res, "ipv4", check2.message, refs); } if (check2.version !== "v4") { addFormat(res, "ipv6", check2.message, refs); } break; } case "base64url": addPattern(res, zodPatterns.base64url, check2.message, refs); break; case "jwt": addPattern(res, zodPatterns.jwt, check2.message, refs); break; case "cidr": { if (check2.version !== "v6") { addPattern(res, zodPatterns.ipv4Cidr, check2.message, refs); } if (check2.version !== "v4") { addPattern(res, zodPatterns.ipv6Cidr, check2.message, refs); } break; } case "emoji": addPattern(res, zodPatterns.emoji(), check2.message, refs); break; case "ulid": { addPattern(res, zodPatterns.ulid, check2.message, refs); break; } case "base64": { switch (refs.base64Strategy) { case "format:binary": { addFormat(res, "binary", check2.message, refs); break; } case "contentEncoding:base64": { res.contentEncoding = "base64"; break; } case "pattern:zod": { addPattern(res, zodPatterns.base64, check2.message, refs); break; } } break; } case "nanoid": { addPattern(res, zodPatterns.nanoid, check2.message, refs); } case "toLowerCase": case "toUpperCase": case "trim": break; default: /* @__PURE__ */ ((_2) => { })(check2); } } } return res; } function escapeLiteralCheckValue(literal2, refs) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal2) : literal2; } var ALPHA_NUMERIC = new Set( "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789" ); function escapeNonAlphaNumeric(source) { let result = ""; for (let i4 = 0; i4 < source.length; i4++) { if (!ALPHA_NUMERIC.has(source[i4])) { result += "\\"; } result += source[i4]; } return result; } function addFormat(schema, value, message, refs) { var _a25; if (schema.format || ((_a25 = schema.anyOf) == null ? void 0 : _a25.some((x4) => x4.format))) { if (!schema.anyOf) { schema.anyOf = []; } if (schema.format) { schema.anyOf.push({ format: schema.format }); delete schema.format; } schema.anyOf.push({ format: value, ...message && refs.errorMessages && { errorMessage: { format: message } } }); } else { schema.format = value; } } function addPattern(schema, regex, message, refs) { var _a25; if (schema.pattern || ((_a25 = schema.allOf) == null ? void 0 : _a25.some((x4) => x4.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 _a25; if (!refs.applyRegexFlags || !regex.flags) { return regex.source; } const flags = { i: regex.flags.includes("i"), // Case-insensitive m: regex.flags.includes("m"), // `^` and `$` matches adjacent to newline characters s: regex.flags.includes("s") // `.` matches newlines }; const source = flags.i ? regex.source.toLowerCase() : regex.source; let pattern = ""; let isEscaped = false; let inCharGroup = false; let inCharRange = false; for (let i4 = 0; i4 < source.length; i4++) { if (isEscaped) { pattern += source[i4]; isEscaped = false; continue; } if (flags.i) { if (inCharGroup) { if (source[i4].match(/[a-z]/)) { if (inCharRange) { pattern += source[i4]; pattern += `${source[i4 - 2]}-${source[i4]}`.toUpperCase(); inCharRange = false; } else if (source[i4 + 1] === "-" && ((_a25 = source[i4 + 2]) == null ? void 0 : _a25.match(/[a-z]/))) { pattern += source[i4]; inCharRange = true; } else { pattern += `${source[i4]}${source[i4].toUpperCase()}`; } continue; } } else if (source[i4].match(/[a-z]/)) { pattern += `[${source[i4]}${source[i4].toUpperCase()}]`; continue; } } if (flags.m) { if (source[i4] === "^") { pattern += `(^|(?<=[\r ]))`; continue; } else if (source[i4] === "$") { pattern += `($|(?=[\r ]))`; continue; } } if (flags.s && source[i4] === ".") { pattern += inCharGroup ? `${source[i4]}\r ` : `[${source[i4]}\r ]`; continue; } pattern += source[i4]; if (source[i4] === "\\") { isEscaped = true; } else if (inCharGroup && source[i4] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i4] === "[") { inCharGroup = true; } } try { new RegExp(pattern); } catch (e5) { 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 _a25, _b23, _c, _d, _e2, _f; const schema = { type: "object", additionalProperties: (_a25 = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] })) != null ? _a25 : refs.allowedAdditionalProperties }; if (((_b23 = def.keyType) == null ? void 0 : _b23._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) { const { type: _type, ...keyType } = parseStringDef(def.keyType._def, refs); return { ...schema, propertyNames: keyType }; } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) { return { ...schema, propertyNames: { enum: def.keyType._def.values } }; } else if (((_e2 = def.keyType) == null ? void 0 : _e2._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) { const { type: _type, ...keyType } = parseBrandedDef( def.keyType._def, refs ); return { ...schema, propertyNames: keyType }; } return schema; } function parseMapDef(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef(def, refs); } 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 object4 = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object4[object4[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object4[key]); const parsedTypes = Array.from( new Set(actualValues.map((values) => typeof values)) ); return { type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], enum: actualValues }; } function parseNeverDef() { return { not: parseAnyDef() }; } function parseNullDef() { return { type: "null" }; } var primitiveMappings = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null" }; function parseUnionDef(def, refs) { const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; if (options.every( (x4) => x4._def.typeName in primitiveMappings && (!x4._def.checks || !x4._def.checks.length) )) { const types = options.reduce((types2, x4) => { const type = primitiveMappings[x4._def.typeName]; return type && !types2.includes(type) ? [...types2, type] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x4) => x4._def.typeName === "ZodLiteral" && !x4.description)) { const types = options.reduce( (acc, x4) => { const type = typeof x4._def.value; switch (type) { case "string": case "number": case "boolean": return [...acc, type]; case "bigint": return [...acc, "integer"]; case "object": if (x4._def.value === null) return [...acc, "null"]; case "symbol": case "undefined": case "function": default: return acc; } }, [] ); if (types.length === options.length) { const uniqueTypes = types.filter((x4, i4, a3) => a3.indexOf(x4) === i4); return { type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], enum: options.reduce( (acc, x4) => { return acc.includes(x4._def.value) ? acc : [...acc, x4._def.value]; }, [] ) }; } } else if (options.every((x4) => x4._def.typeName === "ZodEnum")) { return { type: "string", enum: options.reduce( (acc, x4) => [ ...acc, ...x4._def.values.filter((x22) => !acc.includes(x22)) ], [] ) }; } return asAnyOf(def, refs); } var asAnyOf = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map( (x4, i4) => parseDef(x4._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", `${i4}`] }) ).filter( (x4) => !!x4 && (!refs.strictUnions || typeof x4 === "object" && Object.keys(x4).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 check2 of def.checks) { switch (check2.kind) { case "int": res.type = "integer"; break; case "min": if (check2.inclusive) { res.minimum = check2.value; } else { res.exclusiveMinimum = check2.value; } break; case "max": if (check2.inclusive) { res.maximum = check2.value; } else { res.exclusiveMaximum = check2.value; } break; case "multipleOf": res.multipleOf = check2.value; break; } } return res; } function parseObjectDef(def, refs) { const result = { type: "object", properties: {} }; const required2 = []; const shape = def.shape(); for (const propName in shape) { let propDef = shape[propName]; if (propDef === void 0 || propDef._def === void 0) { continue; } const propOptional = safeIsOptional(propDef); const parsedDef = parseDef(propDef._def, { ...refs, currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] }); if (parsedDef === void 0) { continue; } result.properties[propName] = parsedDef; if (!propOptional) { required2.push(propName); } } if (required2.length) { result.required = required2; } const additionalProperties = decideAdditionalProperties(def, refs); if (additionalProperties !== void 0) { result.additionalProperties = additionalProperties; } return result; } function decideAdditionalProperties(def, refs) { if (def.catchall._def.typeName !== "ZodNever") { return parseDef(def.catchall._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }); } switch (def.unknownKeys) { case "passthrough": return refs.allowedAdditionalProperties; case "strict": return refs.rejectedAdditionalProperties; case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; } } function safeIsOptional(schema) { try { return schema.isOptional(); } catch (e5) { return true; } } var parseOptionalDef = (def, refs) => { var _a25; if (refs.currentPath.toString() === ((_a25 = refs.propertyPath) == null ? void 0 : _a25.toString())) { return parseDef(def.innerType._def, refs); } const innerSchema = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "1"] }); return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef(); }; var parsePipelineDef = (def, refs) => { if (refs.pipeStrategy === "input") { return parseDef(def.in._def, refs); } else if (refs.pipeStrategy === "output") { return parseDef(def.out._def, refs); } const inputSchema = parseDef(def.in._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }); const outputSchema2 = parseDef(def.out._def, { ...refs, currentPath: [...refs.currentPath, "allOf", inputSchema ? "1" : "0"] }); return { allOf: [inputSchema, outputSchema2].filter( (schema) => schema !== void 0 ) }; }; 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( (x4, i4) => parseDef(x4._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i4}`] }) ).reduce( (acc, x4) => x4 === void 0 ? acc : [...acc, x4], [] ), additionalItems: parseDef(def.rest._def, { ...refs, currentPath: [...refs.currentPath, "additionalItems"] }) }; } else { return { type: "array", minItems: def.items.length, maxItems: def.items.length, items: def.items.map( (x4, i4) => parseDef(x4._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i4}`] }) ).reduce( (acc, x4) => x4 === void 0 ? acc : [...acc, x4], [] ) }; } } function parseUndefinedDef() { return { not: parseAnyDef() }; } function parseUnknownDef() { return parseAnyDef(); } var parseReadonlyDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; var selectParser = (def, typeName, refs) => { switch (typeName) { case ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs); case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def); case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs); case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def); case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef(); case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs); case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef(); case ZodFirstPartyTypeKind.ZodNull: return parseNullDef(); case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs); case ZodFirstPartyTypeKind.ZodUnion: case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs); case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs); case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs); case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs); case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def); case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def); case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def); case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs); case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs); case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs); case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs); case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def; case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs); case ZodFirstPartyTypeKind.ZodNaN: case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef(); case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs); case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef(); case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef(); case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs); case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs); case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs); case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs); case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs); case ZodFirstPartyTypeKind.ZodFunction: case ZodFirstPartyTypeKind.ZodVoid: case ZodFirstPartyTypeKind.ZodSymbol: return void 0; default: return /* @__PURE__ */ ((_2) => void 0)(typeName); } }; var getRelativePath = (pathA, pathB) => { let i4 = 0; for (; i4 < pathA.length && i4 < pathB.length; i4++) { if (pathA[i4] !== pathB[i4]) break; } return [(pathA.length - i4).toString(), ...pathB.slice(i4)].join("/"); }; function parseDef(def, refs, forceResolution = false) { var _a25; const seenItem = refs.seen.get(def); if (refs.override) { const overrideResult = (_a25 = refs.override) == null ? void 0 : _a25.call( refs, def, refs, seenItem, forceResolution ); if (overrideResult !== ignoreOverride) { return overrideResult; } } if (seenItem && !forceResolution) { const seenSchema = get$ref(seenItem, refs); if (seenSchema !== void 0) { return seenSchema; } } const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; refs.seen.set(def, newItem); const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; if (jsonSchema2) { addMeta(def, refs, jsonSchema2); } if (refs.postProcess) { const postProcessResult = refs.postProcess(jsonSchema2, def, refs); newItem.jsonSchema = jsonSchema2; return postProcessResult; } newItem.jsonSchema = jsonSchema2; return jsonSchema2; } var get$ref = (item, refs) => { switch (refs.$refStrategy) { case "root": return { $ref: item.path.join("/") }; case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) }; case "none": case "seen": { if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { console.warn( `Recursive reference detected at ${refs.currentPath.join( "/" )}! Defaulting to any` ); return parseAnyDef(); } return refs.$refStrategy === "seen" ? parseAnyDef() : void 0; } } }; var addMeta = (def, refs, jsonSchema2) => { if (def.description) { jsonSchema2.description = def.description; } return jsonSchema2; }; var getRefs = (options) => { const _options = getDefaultOptions(options); const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return { ..._options, currentPath, propertyPath: void 0, seen: new Map( Object.entries(_options.definitions).map(([name24, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name24], // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. jsonSchema: void 0 } ]) ) }; }; var zod3ToJsonSchema = (schema, options) => { var _a25; const refs = getRefs(options); let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce( (acc, [name34, schema2]) => { var _a34; return { ...acc, [name34]: (_a34 = parseDef( schema2._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name34] }, true )) != null ? _a34 : parseAnyDef() }; }, {} ) : void 0; const name24 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name; const main = (_a25 = parseDef( schema._def, name24 === void 0 ? refs : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name24] }, false )) != null ? _a25 : parseAnyDef(); const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; if (title !== void 0) { main.title = title; } const combined = name24 === void 0 ? definitions ? { ...main, [refs.definitionPath]: definitions } : main : { $ref: [ ...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name24 ].join("/"), [refs.definitionPath]: { ...definitions, [name24]: main } }; combined.$schema = "http://json-schema.org/draft-07/schema#"; return combined; }; var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema"); function lazySchema(createSchema) { let schema; return () => { if (schema == null) { schema = createSchema(); } return schema; }; } function jsonSchema(jsonSchema2, { validate } = {}) { return { [schemaSymbol]: true, _type: void 0, // should never be used directly get jsonSchema() { if (typeof jsonSchema2 === "function") { jsonSchema2 = jsonSchema2(); } return jsonSchema2; }, validate }; } function isSchema(value) { return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value; } function asSchema(schema) { return schema == null ? jsonSchema({ type: "object", properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema(); } function standardSchema(standardSchema2) { return jsonSchema( () => { if (!hasStandardJsonSchema(standardSchema2)) { throw new Error( `Standard schema vendor '${standardSchema2["~standard"].vendor}' does not support JSON Schema conversion.` ); } return addAdditionalPropertiesToJsonSchema( standardSchema2["~standard"].jsonSchema.input({ target: "draft-07" }) ); }, { validate: async (value) => { const result = await standardSchema2["~standard"].validate(value); return "value" in result ? { success: true, value: result.value } : { success: false, error: new TypeValidationError({ value, cause: result.issues }) }; } } ); } function hasStandardJsonSchema(schema) { return schema["~standard"].jsonSchema != null; } function zod3Schema(zodSchema2, options) { var _a25; const useReferences = (_a25 = options == null ? void 0 : options.useReferences) != null ? _a25 : false; return jsonSchema( // defer json schema creation to avoid unnecessary computation when only validation is needed () => zod3ToJsonSchema(zodSchema2, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => { const result = await zodSchema2.safeParseAsync(value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } function zod4Schema(zodSchema2, options) { var _a25; const useReferences = (_a25 = options == null ? void 0 : options.useReferences) != null ? _a25 : false; return jsonSchema( // defer json schema creation to avoid unnecessary computation when only validation is needed () => addAdditionalPropertiesToJsonSchema( toJSONSchema(zodSchema2, { target: "draft-7", io: "input", reused: useReferences ? "ref" : "inline" }) ), { validate: async (value) => { const result = await safeParseAsync2(zodSchema2, value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } function isZod4Schema(zodSchema2) { return "_zod" in zodSchema2; } function zodSchema(zodSchema2, options) { if (isZod4Schema(zodSchema2)) { return zod4Schema(zodSchema2, options); } else { return zod3Schema(zodSchema2, options); } } async function validateTypes({ value, schema, context }) { const result = await safeValidateTypes({ value, schema, context }); if (!result.success) { throw TypeValidationError.wrap({ value, cause: result.error, context }); } return result.value; } async function safeValidateTypes({ value, schema, context }) { const actualSchema = asSchema(schema); try { if (actualSchema.validate == null) { return { success: true, value, rawValue: value }; } const result = await actualSchema.validate(value); if (result.success) { return { success: true, value: result.value, rawValue: value }; } return { success: false, error: TypeValidationError.wrap({ value, cause: result.error, context }), rawValue: value }; } catch (error40) { return { success: false, error: TypeValidationError.wrap({ value, cause: error40, context }), rawValue: value }; } } async function parseJSON({ text: text2, schema }) { try { const value = secureJsonParse(text2); if (schema == null) { return value; } return await validateTypes({ value, schema }); } catch (error40) { if (JSONParseError.isInstance(error40) || TypeValidationError.isInstance(error40)) { throw error40; } throw new JSONParseError({ text: text2, cause: error40 }); } } async function safeParseJSON({ text: text2, schema }) { try { const value = secureJsonParse(text2); if (schema == null) { return { success: true, value, rawValue: value }; } return await safeValidateTypes({ value, schema }); } catch (error40) { return { success: false, error: JSONParseError.isInstance(error40) ? error40 : new JSONParseError({ text: text2, cause: error40 }), rawValue: void 0 }; } } function parseJsonEventStream({ stream, schema }) { return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough( new TransformStream({ async transform({ data }, controller) { if (data === "[DONE]") { return; } controller.enqueue(await safeParseJSON({ text: data, schema })); } }) ); } async function parseProviderOptions({ provider, providerOptions, schema }) { if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) { return void 0; } 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: url2, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => await postToApi({ url: url2, headers: { "Content-Type": "application/json", ...headers }, body: { content: JSON.stringify(body), values: body }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }); var postFormDataToApi = async ({ url: url2, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => await postToApi({ url: url2, headers, body: { content: formData, values: Object.fromEntries(formData.entries()) }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }); var postToApi = async ({ url: url2, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch2() }) => { try { const response = await fetch2(url2, { 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: url2, requestBodyValues: body.values }); } catch (error40) { if (isAbortError(error40) || APICallError.isInstance(error40)) { throw error40; } throw new APICallError({ message: "Failed to process error response", cause: error40, statusCode: response.status, url: url2, responseHeaders, requestBodyValues: body.values }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url: url2, requestBodyValues: body.values }); } catch (error40) { if (error40 instanceof Error) { if (isAbortError(error40) || APICallError.isInstance(error40)) { throw error40; } } throw new APICallError({ message: "Failed to process successful response", cause: error40, statusCode: response.status, url: url2, responseHeaders, requestBodyValues: body.values }); } } catch (error40) { throw handleFetchError({ error: error40, url: url2, requestBodyValues: body.values }); } }; function tool(tool2) { return tool2; } function createProviderDefinedToolFactory({ id, inputSchema }) { return ({ execute, outputSchema: outputSchema2, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({ type: "provider", isProviderExecuted: false, id, args, inputSchema, outputSchema: outputSchema2, execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable }); } function createProviderDefinedToolFactoryWithOutputSchema({ id, inputSchema, outputSchema: outputSchema2 }) { return ({ execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({ type: "provider", isProviderExecuted: false, id, args, inputSchema, outputSchema: outputSchema2, execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable }); } function createProviderExecutedToolFactory({ id, inputSchema, outputSchema: outputSchema2, supportsDeferredResults }) { return ({ onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({ type: "provider", isProviderExecuted: true, id, args, inputSchema, outputSchema: outputSchema2, onInputStart, onInputDelta, onInputAvailable, supportsDeferredResults }); } async function resolve(value) { if (typeof value === "function") { value = value(); } return Promise.resolve(value); } function resolveFullMediaType({ part }) { if (isFullMediaType(part.mediaType)) { return part.mediaType; } if (part.data.type === "data") { const detected = detectMediaType({ data: part.data.data, topLevelType: getTopLevelMediaType(part.mediaType) }); if (detected) { return detected; } throw new UnsupportedFunctionalityError({ functionality: `file of media type "${part.mediaType}" must specify subtype since it could not be auto-detected` }); } throw new UnsupportedFunctionalityError({ functionality: `file of media type "${part.mediaType}" must specify subtype since it is not passed as inline bytes` }); } function resolveProviderReference({ reference, provider }) { const id = reference[provider]; if (id != null) { return id; } throw new NoSuchProviderReferenceError({ provider, reference }); } var retryWithExponentialBackoff = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal, shouldRetry, getDelayInMs = ({ exponentialBackoffDelay }) => exponentialBackoffDelay, createRetryError = ({ message }) => new Error(message) }) => async (f2) => retryWithExponentialBackoffInternal(f2, { maxRetries, delayInMs: initialDelayInMs, backoffFactor, abortSignal, shouldRetry, getDelayInMs, createRetryError }); async function retryWithExponentialBackoffInternal(f2, { maxRetries, delayInMs, backoffFactor, abortSignal, shouldRetry, getDelayInMs, createRetryError }, errors = []) { try { return await f2(); } catch (error40) { if (isAbortError(error40)) { throw error40; } if (maxRetries === 0) { throw error40; } const errorMessage = getErrorMessage(error40); const newErrors = [...errors, error40]; const tryNumber = newErrors.length; if (tryNumber > maxRetries) { throw createRetryError({ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`, reason: "maxRetriesExceeded", errors: newErrors }); } if (await shouldRetry(error40) && tryNumber <= maxRetries) { await delay( getDelayInMs({ error: error40, exponentialBackoffDelay: delayInMs }), { abortSignal } ); return retryWithExponentialBackoffInternal( f2, { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor, abortSignal, shouldRetry, getDelayInMs, createRetryError }, newErrors ); } if (tryNumber === 1) { throw error40; } throw createRetryError({ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`, reason: "errorNotRetryable", errors: newErrors }); } } var textDecoder2 = new TextDecoder(); async function readResponseBodyAsText({ response, url: url2 }) { return textDecoder2.decode( await readResponseWithSizeLimit({ response, url: url2 }) ); } var createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url: url2, requestBodyValues }) => { const responseBody = await readResponseBodyAsText({ response, url: url2 }); const responseHeaders = extractResponseHeaders(response); if (responseBody.trim() === "") { return { responseHeaders, value: new APICallError({ message: response.statusText, url: url2, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } try { const parsedError = await parseJSON({ text: responseBody, schema: errorSchema }); return { responseHeaders, value: new APICallError({ message: errorToMessage(parsedError), url: url2, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, data: parsedError, isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError) }) }; } catch (e5) { return { responseHeaders, value: new APICallError({ message: response.statusText, url: url2, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } }; var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => { const responseHeaders = extractResponseHeaders(response); if (response.body == null) { throw new EmptyResponseBodyError({}); } return { responseHeaders, value: parseJsonEventStream({ stream: response.body, schema: chunkSchema }) }; }; var createJsonResponseHandler = (responseSchema) => async ({ response, url: url2, requestBodyValues }) => { const responseBody = await readResponseBodyAsText({ response, url: url2 }); 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: url2, requestBodyValues }); } return { responseHeaders, value: parsedResult.value, rawValue: parsedResult.rawValue }; }; var createBinaryResponseHandler = () => async ({ response, url: url2, requestBodyValues }) => { const responseHeaders = extractResponseHeaders(response); if (!response.body) { throw new APICallError({ message: "Response body is empty", url: url2, requestBodyValues, statusCode: response.status, responseHeaders, responseBody: void 0 }); } try { const buffer = await response.arrayBuffer(); return { responseHeaders, value: new Uint8Array(buffer) }; } catch (error40) { throw new APICallError({ message: "Failed to read response as array buffer", url: url2, requestBodyValues, statusCode: response.status, responseHeaders, responseBody: void 0, cause: error40 }); } }; function isJSONSerializable(value) { if (value === null || value === void 0) return true; const type = typeof value; if (type === "string" || type === "number" || type === "boolean") return true; if (type === "function" || type === "symbol" || type === "bigint") return false; if (Array.isArray(value)) { return value.every(isJSONSerializable); } if (Object.getPrototypeOf(value) === Object.prototype) { return Object.values(value).every( isJSONSerializable ); } return false; } function serializeModelOptions(options) { const serializableConfig = {}; for (const [key, value] of Object.entries(options.config)) { if (key === "headers") { const resolvedHeaders = resolveSync(value); if (isJSONSerializable(resolvedHeaders)) { serializableConfig[key] = resolvedHeaders; } } else if (isJSONSerializable(value)) { serializableConfig[key] = value; } } return { modelId: options.modelId, config: serializableConfig }; } function resolveSync(value) { let next = value; if (typeof value === "function") { next = value(); } if (next instanceof Promise) { throw new Error("Promise returned from resolveSync"); } return next; } var StreamingToolCallTracker = class { constructor(controller, options = {}) { this.toolCalls = []; var _a25, _b23; this.controller = controller; this._generateId = (_a25 = options.generateId) != null ? _a25 : generateId; this.typeValidation = (_b23 = options.typeValidation) != null ? _b23 : "none"; this.extractMetadata = options.extractMetadata; this.buildToolCallProviderMetadata = options.buildToolCallProviderMetadata; } /** * Process a tool call delta from a streaming response chunk. * Emits tool-input-start, tool-input-delta, tool-input-end, and tool-call * events as appropriate. */ processDelta(toolCallDelta) { var _a25; const index = (_a25 = toolCallDelta.index) != null ? _a25 : this.toolCalls.length; if (this.toolCalls[index] == null) { this.processNewToolCall(index, toolCallDelta); } else { this.processExistingToolCall(index, toolCallDelta); } } /** * Finalize any unfinished tool calls. Should be called during the stream's * flush handler to ensure all tool calls are properly completed. */ flush() { for (const toolCall of this.toolCalls) { if (!toolCall.hasFinished) { this.finishToolCall(toolCall); } } } processNewToolCall(index, toolCallDelta) { var _a25, _b23, _c; if (this.typeValidation === "required") { if (toolCallDelta.type !== "function") { throw new InvalidResponseDataError({ data: toolCallDelta, message: `Expected 'function' type.` }); } } else if (this.typeValidation === "if-present") { if (toolCallDelta.type != null && toolCallDelta.type !== "function") { throw new InvalidResponseDataError({ data: toolCallDelta, message: `Expected 'function' type.` }); } } if (toolCallDelta.id == null) { throw new InvalidResponseDataError({ data: toolCallDelta, message: `Expected 'id' to be a string.` }); } if (((_a25 = toolCallDelta.function) == null ? void 0 : _a25.name) == null) { throw new InvalidResponseDataError({ data: toolCallDelta, message: `Expected 'function.name' to be a string.` }); } this.controller.enqueue({ type: "tool-input-start", id: toolCallDelta.id, toolName: toolCallDelta.function.name }); const metadata = (_b23 = this.extractMetadata) == null ? void 0 : _b23.call(this, toolCallDelta); this.toolCalls[index] = { id: toolCallDelta.id, type: "function", function: { name: toolCallDelta.function.name, arguments: (_c = toolCallDelta.function.arguments) != null ? _c : "" }, hasFinished: false, metadata }; const toolCall = this.toolCalls[index]; if (toolCall.function.arguments.length > 0) { this.controller.enqueue({ type: "tool-input-delta", id: toolCall.id, delta: toolCall.function.arguments }); } } processExistingToolCall(index, toolCallDelta) { var _a25; const toolCall = this.toolCalls[index]; if (toolCall.hasFinished) { return; } if (((_a25 = toolCallDelta.function) == null ? void 0 : _a25.arguments) != null) { toolCall.function.arguments += toolCallDelta.function.arguments; this.controller.enqueue({ type: "tool-input-delta", id: toolCall.id, delta: toolCallDelta.function.arguments }); } } finishToolCall(toolCall) { var _a25, _b23; this.controller.enqueue({ type: "tool-input-end", id: toolCall.id }); const providerMetadata = (_a25 = this.buildToolCallProviderMetadata) == null ? void 0 : _a25.call( this, toolCall.metadata ); this.controller.enqueue({ type: "tool-call", toolCallId: (_b23 = toolCall.id) != null ? _b23 : this._generateId(), toolName: toolCall.function.name, input: toolCall.function.arguments, ...providerMetadata ? { providerMetadata } : {} }); toolCall.hasFinished = true; } }; var TRANSCRIPTION_STREAM_START_FRAME_TYPE = "transcription-stream.start"; var TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE = "transcription-stream.audio-done"; function parseTranscriptionStreamPart(text2) { let value; try { value = secureJsonParse(text2); } catch (e5) { return void 0; } if (value == null || typeof value !== "object" || Array.isArray(value)) { return void 0; } const part = value; switch (part.type) { case "stream-start": return Array.isArray(part.warnings) && part.warnings.every(isWarning) ? part : void 0; case "transcript-delta": return isString(part.delta) && isOptional(part.id, isString) && isOptional(part.providerMetadata, isPlainObject2) ? part : void 0; case "transcript-partial": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isPlainObject2) ? part : void 0; case "transcript-final": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.endSecond, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isPlainObject2) ? part : void 0; case "finish": return isString(part.text) && Array.isArray(part.segments) && part.segments.every(isSegment) && isOptional(part.language, isString) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.providerMetadata, isPlainObject2) ? part : void 0; case "response-metadata": { if (!(isOptional(part.modelId, isString) && isOptional(part.headers, isPlainObject2))) { return void 0; } const timestamp = part.timestamp; if (timestamp == null) { return { ...part, timestamp: void 0 }; } if (typeof timestamp !== "string") { return void 0; } const revived = new Date(timestamp); return Number.isNaN(revived.getTime()) ? void 0 : { ...part, timestamp: revived }; } case "raw": return "rawValue" in part ? part : void 0; case "error": return "error" in part ? part : void 0; default: return void 0; } } function isString(value) { return typeof value === "string"; } function isNumber(value) { return typeof value === "number"; } function isOptional(value, check2) { return value === void 0 || check2(value); } function isPlainObject2(value) { return typeof value === "object" && value != null && !Array.isArray(value); } function isWarning(value) { return isPlainObject2(value) && isString(value.type); } function isSegment(value) { return isPlainObject2(value) && isString(value.text) && isNumber(value.startSecond) && isNumber(value.endSecond); } function validateBaseURL(baseURL) { if ((baseURL == null ? void 0 : baseURL.trim()) === "") { throw new InvalidArgumentError({ argument: "baseURL", message: "baseURL must be a non-empty string." }); } return baseURL; } function withoutTrailingSlash(url2) { return url2 == null ? void 0 : url2.replace(/\/$/, ""); } function isExecutableTool(tool2) { return tool2 != null && typeof tool2.execute === "function"; } function isAsyncIterable(obj) { return obj != null && typeof obj[Symbol.asyncIterator] === "function"; } async function* executeTool({ tool: tool2, input, options }) { const result = tool2.execute(input, options); if (isAsyncIterable(result)) { let lastOutput; for await (const output of result) { lastOutput = output; yield { type: "preliminary", output }; } yield { type: "final", output: lastOutput }; } else { yield { type: "final", output: await result }; } } // node_modules/@ai-sdk/gateway/dist/index.js var import_oidc = __toESM(require_dist(), 1); var import_oidc2 = __toESM(require_dist(), 1); var GATEWAY_REALTIME_SUBPROTOCOL = "ai-gateway-realtime.v1"; var GATEWAY_TRANSCRIPTION_SUBPROTOCOL = "ai-gateway-transcription.v1"; var GATEWAY_AUTH_SUBPROTOCOL_PREFIX = "ai-gateway-auth."; var GATEWAY_TEAM_SUBPROTOCOL_PREFIX = "ai-gateway-team."; function getGatewayRealtimeProtocols(token2, options) { return buildGatewayProtocols(GATEWAY_REALTIME_SUBPROTOCOL, token2, options); } function getGatewayTranscriptionProtocols(token2, options) { return buildGatewayProtocols( GATEWAY_TRANSCRIPTION_SUBPROTOCOL, token2, options ); } function buildGatewayProtocols(marker113, token2, options) { const protocols = [marker113, `${GATEWAY_AUTH_SUBPROTOCOL_PREFIX}${token2}`]; if (options == null ? void 0 : options.teamIdOrSlug) { protocols.push( `${GATEWAY_TEAM_SUBPROTOCOL_PREFIX}${encodeSubprotocolValue(options.teamIdOrSlug)}` ); } return protocols; } function encodeSubprotocolValue(value) { const bytes = new TextEncoder().encode(value); let binary = ""; for (const byte of bytes) { binary += String.fromCharCode(byte); } return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/u, ""); } var marker17 = "vercel.ai.gateway.error"; var symbol17 = Symbol.for(marker17); var _a17; var _b17; var GatewayError = class _GatewayError extends (_b17 = Error, _a17 = symbol17, _b17) { constructor({ message, statusCode = 500, cause, generationId, isRetryable = statusCode != null && (statusCode === 408 || // request timeout statusCode === 409 || // conflict statusCode === 429 || // too many requests statusCode >= 500) // server error }) { super(generationId ? `${message} [${generationId}]` : message); this[_a17] = true; this.statusCode = statusCode; this.cause = cause; this.generationId = generationId; this.isRetryable = isRetryable; } /** * Checks if the given error is a Gateway Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is a Gateway Error, false otherwise. */ static isInstance(error40) { return _GatewayError.hasMarker(error40); } static hasMarker(error40) { return typeof error40 === "object" && error40 !== null && symbol17 in error40 && error40[symbol17] === true; } }; var name16 = "GatewayAuthenticationError"; var marker22 = `vercel.ai.gateway.error.${name16}`; var symbol23 = Symbol.for(marker22); var _a22; var _b22; var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b22 = GatewayError, _a22 = symbol23, _b22) { constructor({ message = "Authentication failed", statusCode = 401, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a22] = true; this.name = name16; this.type = "authentication_error"; } static isInstance(error40) { return GatewayError.hasMarker(error40) && symbol23 in error40; } /** * Creates a contextual error message when authentication fails */ static createContextualError({ apiKeyProvided, oidcTokenProvided, statusCode = 401, cause, generationId }) { let contextualMessage; if (apiKeyProvided) { contextualMessage = `AI Gateway authentication failed: Invalid API key or token. Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys Provide an API key or Vercel access token via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`; } else if (oidcTokenProvided) { contextualMessage = `AI Gateway authentication failed: Invalid OIDC token. Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token. Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys or pass a Vercel access token via the 'apiKey' option.`; } else { contextualMessage = `AI Gateway authentication failed: No authentication provided. Option 1 - API key: Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable. Option 2 - Vercel access token: Pass a Vercel personal access token or Vercel app access token via the 'apiKey' option. Option 3 - OIDC token: Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`; } return new _GatewayAuthenticationError({ message: contextualMessage, statusCode, cause, generationId }); } }; var name22 = "GatewayInvalidRequestError"; var marker32 = `vercel.ai.gateway.error.${name22}`; var symbol32 = Symbol.for(marker32); var _a32; var _b32; var GatewayInvalidRequestError = class extends (_b32 = GatewayError, _a32 = symbol32, _b32) { constructor({ message = "Invalid request", statusCode = 400, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a32] = true; this.name = name22; this.type = "invalid_request_error"; } static isInstance(error40) { return GatewayError.hasMarker(error40) && symbol32 in error40; } }; var name32 = "GatewayRateLimitError"; var marker42 = `vercel.ai.gateway.error.${name32}`; var symbol42 = Symbol.for(marker42); var _a42; var _b42; var GatewayRateLimitError = class extends (_b42 = GatewayError, _a42 = symbol42, _b42) { constructor({ message = "Rate limit exceeded", statusCode = 429, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a42] = true; this.name = name32; this.type = "rate_limit_exceeded"; } static isInstance(error40) { return GatewayError.hasMarker(error40) && symbol42 in error40; } }; var name42 = "GatewayModelNotFoundError"; var marker52 = `vercel.ai.gateway.error.${name42}`; var symbol52 = Symbol.for(marker52); var modelNotFoundParamSchema = lazySchema( () => zodSchema( external_exports.object({ modelId: external_exports.string() }) ) ); var _a52; var _b52; var GatewayModelNotFoundError = class extends (_b52 = GatewayError, _a52 = symbol52, _b52) { constructor({ message = "Model not found", statusCode = 404, modelId, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a52] = true; this.name = name42; this.type = "model_not_found"; this.modelId = modelId; } static isInstance(error40) { return GatewayError.hasMarker(error40) && symbol52 in error40; } }; var name52 = "GatewayInternalServerError"; var marker62 = `vercel.ai.gateway.error.${name52}`; var symbol62 = Symbol.for(marker62); var _a62; var _b62; var GatewayInternalServerError = class extends (_b62 = GatewayError, _a62 = symbol62, _b62) { constructor({ message = "Internal server error", statusCode = 500, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a62] = true; this.name = name52; this.type = "internal_server_error"; } static isInstance(error40) { return GatewayError.hasMarker(error40) && symbol62 in error40; } }; var name62 = "GatewayFailedDependencyError"; var marker72 = `vercel.ai.gateway.error.${name62}`; var symbol72 = Symbol.for(marker72); var _a72; var _b72; var GatewayFailedDependencyError = class extends (_b72 = GatewayError, _a72 = symbol72, _b72) { constructor({ message = "Failed dependency", statusCode = 424, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a72] = true; this.name = name62; this.type = "failed_dependency"; } static isInstance(error40) { return GatewayError.hasMarker(error40) && symbol72 in error40; } }; var name72 = "GatewayForbiddenError"; var marker82 = `vercel.ai.gateway.error.${name72}`; var symbol82 = Symbol.for(marker82); var forbiddenParamSchema = lazySchema( () => zodSchema( external_exports.object({ ruleId: external_exports.string() }) ) ); var _a82; var _b82; var GatewayForbiddenError = class extends (_b82 = GatewayError, _a82 = symbol82, _b82) { constructor({ message = "Forbidden", statusCode = 403, cause, generationId, ruleId } = {}) { super({ message, statusCode, cause, generationId }); this[_a82] = true; this.name = name72; this.type = "forbidden"; this.ruleId = ruleId; } static isInstance(error40) { return GatewayError.hasMarker(error40) && symbol82 in error40; } }; var name82 = "GatewayResponseError"; var marker92 = `vercel.ai.gateway.error.${name82}`; var symbol92 = Symbol.for(marker92); var _a92; var _b92; var GatewayResponseError = class extends (_b92 = GatewayError, _a92 = symbol92, _b92) { constructor({ message = "Invalid response from Gateway", statusCode = 502, response, validationError, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a92] = true; this.name = name82; this.type = "response_error"; this.response = response; this.validationError = validationError; } static isInstance(error40) { return GatewayError.hasMarker(error40) && symbol92 in error40; } }; async function createGatewayErrorFromResponse({ response, statusCode, defaultMessage = "Gateway request failed", cause, authMethod }) { var _a113; const parseResult = await safeValidateTypes({ value: response, schema: gatewayErrorResponseSchema }); if (!parseResult.success) { const rawGenerationId = typeof response === "object" && response !== null && "generationId" in response ? response.generationId : void 0; return new GatewayResponseError({ message: `Invalid error response format: ${defaultMessage}`, statusCode, response, validationError: parseResult.error, cause, generationId: rawGenerationId }); } const validatedResponse = parseResult.value; const errorType = validatedResponse.error.type; const message = validatedResponse.error.message; const generationId = (_a113 = validatedResponse.generationId) != null ? _a113 : void 0; switch (errorType) { case "authentication_error": return GatewayAuthenticationError.createContextualError({ apiKeyProvided: authMethod === "api-key", oidcTokenProvided: authMethod === "oidc", statusCode, cause, generationId }); case "invalid_request_error": return new GatewayInvalidRequestError({ message, statusCode, cause, generationId }); case "rate_limit_exceeded": return new GatewayRateLimitError({ message, statusCode, cause, generationId }); case "model_not_found": { const modelResult = await safeValidateTypes({ value: validatedResponse.error.param, schema: modelNotFoundParamSchema }); return new GatewayModelNotFoundError({ message, statusCode, modelId: modelResult.success ? modelResult.value.modelId : void 0, cause, generationId }); } case "internal_server_error": return new GatewayInternalServerError({ message, statusCode, cause, generationId }); case "failed_dependency": return new GatewayFailedDependencyError({ message, statusCode, cause, generationId }); case "forbidden": { const ruleResult = await safeValidateTypes({ value: validatedResponse.error.param, schema: forbiddenParamSchema }); return new GatewayForbiddenError({ message, statusCode, cause, generationId, ruleId: ruleResult.success ? ruleResult.value.ruleId : void 0 }); } default: return new GatewayInternalServerError({ message, statusCode, cause, generationId }); } } var gatewayErrorResponseSchema = lazySchema( () => zodSchema( external_exports.object({ error: external_exports.object({ message: external_exports.string(), type: external_exports.string().nullish(), param: external_exports.unknown().nullish(), code: external_exports.union([external_exports.string(), external_exports.number()]).nullish() }), generationId: external_exports.string().nullish() }) ) ); function extractApiCallResponse(error40) { if (error40.data !== void 0) { return error40.data; } if (error40.responseBody != null) { try { return secureJsonParse(error40.responseBody); } catch (e5) { return error40.responseBody; } } return {}; } var name92 = "GatewayTimeoutError"; var marker102 = `vercel.ai.gateway.error.${name92}`; var symbol102 = Symbol.for(marker102); var _a102; var _b102; var GatewayTimeoutError = class _GatewayTimeoutError extends (_b102 = GatewayError, _a102 = symbol102, _b102) { constructor({ message = "Request timed out", statusCode = 408, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a102] = true; this.name = name92; this.type = "timeout_error"; } static isInstance(error40) { return GatewayError.hasMarker(error40) && symbol102 in error40; } /** * Creates a helpful timeout error message with troubleshooting guidance */ static createTimeoutError({ originalMessage, statusCode = 408, cause, generationId }) { const message = `Gateway request timed out: ${originalMessage} This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`; return new _GatewayTimeoutError({ message, statusCode, cause, generationId }); } }; function isTimeoutError(error40) { if (!(error40 instanceof Error)) { return false; } const errorCode = error40.code; if (typeof errorCode === "string") { const undiciTimeoutCodes = [ "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "UND_ERR_CONNECT_TIMEOUT" ]; return undiciTimeoutCodes.includes(errorCode); } return false; } async function asGatewayError(error40, authMethod) { var _a113; if (GatewayError.isInstance(error40)) { return error40; } if (isTimeoutError(error40)) { return GatewayTimeoutError.createTimeoutError({ originalMessage: error40 instanceof Error ? error40.message : "Unknown error", cause: error40 }); } if (APICallError.isInstance(error40)) { if (error40.cause && isTimeoutError(error40.cause)) { return GatewayTimeoutError.createTimeoutError({ originalMessage: error40.message, cause: error40 }); } return await createGatewayErrorFromResponse({ response: extractApiCallResponse(error40), statusCode: (_a113 = error40.statusCode) != null ? _a113 : 500, defaultMessage: "Gateway request failed", cause: error40, authMethod }); } return await createGatewayErrorFromResponse({ response: {}, statusCode: 500, defaultMessage: error40 instanceof Error ? `Gateway request failed: ${error40.message}` : "Unknown Gateway error", cause: error40, authMethod }); } var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method"; var VERCEL_AI_GATEWAY_TEAM_HEADER = "x-vercel-ai-gateway-team"; async function parseAuthMethod(headers) { const result = await safeValidateTypes({ value: headers[GATEWAY_AUTH_METHOD_HEADER], schema: gatewayAuthMethodSchema }); return result.success ? result.value : void 0; } var gatewayAuthMethodSchema = lazySchema( () => zodSchema(external_exports.union([external_exports.literal("api-key"), external_exports.literal("oidc")])) ); var KNOWN_MODEL_TYPES = [ "embedding", "image", "language", "realtime", "reranking", "speech", "transcription", "video" ]; var GatewayFetchMetadata = class { constructor(config2) { this.config = config2; } async getAvailableModels() { try { const { value } = await getFromApi({ url: `${this.config.baseURL}/config`, validateUrl: false, headers: this.config.headers ? await resolve(this.config.headers) : void 0, successfulResponseHandler: createJsonResponseHandler( gatewayAvailableModelsResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error40) { throw await asGatewayError(error40); } } async getCredits() { try { const baseUrl = new URL(this.config.baseURL); const { value } = await getFromApi({ url: `${baseUrl.origin}/v1/credits`, validateUrl: false, headers: this.config.headers ? await resolve(this.config.headers) : void 0, successfulResponseHandler: createJsonResponseHandler( gatewayCreditsResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error40) { throw await asGatewayError(error40); } } }; var gatewayAvailableModelsResponseSchema = lazySchema( () => zodSchema( external_exports.object({ models: external_exports.array( external_exports.object({ id: external_exports.string(), name: external_exports.string(), description: external_exports.string().nullish(), pricing: external_exports.object({ input: external_exports.string(), output: external_exports.string(), input_cache_read: external_exports.string().nullish(), input_cache_write: external_exports.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: external_exports.object({ specificationVersion: external_exports.literal("v4"), provider: external_exports.string(), modelId: external_exports.string() }), modelType: external_exports.string().nullish() }) ).transform( (models) => models.filter( (m3) => m3.modelType == null || KNOWN_MODEL_TYPES.includes(m3.modelType) ) ) }) ) ); var gatewayCreditsResponseSchema = lazySchema( () => zodSchema( external_exports.object({ balance: external_exports.string(), total_used: external_exports.string() }).transform(({ balance, total_used }) => ({ balance, totalUsed: total_used })) ) ); var GatewaySpendReport = class { constructor(config2) { this.config = config2; } async getSpendReport(params) { try { const baseUrl = new URL(this.config.baseURL); const searchParams = new URLSearchParams(); searchParams.set("start_date", params.startDate); searchParams.set("end_date", params.endDate); if (params.groupBy) { searchParams.set("group_by", params.groupBy); } if (params.datePart) { searchParams.set("date_part", params.datePart); } if (params.userId) { searchParams.set("user_id", params.userId); } if (params.model) { searchParams.set("model", params.model); } if (params.provider) { searchParams.set("provider", params.provider); } if (params.credentialType) { searchParams.set("credential_type", params.credentialType); } if (params.tags && params.tags.length > 0) { searchParams.set("tags", params.tags.join(",")); } const { value } = await getFromApi({ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`, validateUrl: false, headers: this.config.headers ? await resolve(this.config.headers) : void 0, successfulResponseHandler: createJsonResponseHandler( gatewaySpendReportResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error40) { throw await asGatewayError(error40); } } }; var gatewaySpendReportResponseSchema = lazySchema( () => zodSchema( external_exports.object({ results: external_exports.array( external_exports.object({ day: external_exports.string().optional(), hour: external_exports.string().optional(), user: external_exports.string().optional(), model: external_exports.string().optional(), tag: external_exports.string().optional(), provider: external_exports.string().optional(), credential_type: external_exports.enum(["byok", "system"]).optional(), total_cost: external_exports.number(), market_cost: external_exports.number().optional(), input_tokens: external_exports.number().optional(), output_tokens: external_exports.number().optional(), cached_input_tokens: external_exports.number().optional(), cache_creation_input_tokens: external_exports.number().optional(), reasoning_tokens: external_exports.number().optional(), request_count: external_exports.number().optional() }).transform( ({ credential_type, total_cost, market_cost, input_tokens, output_tokens, cached_input_tokens, cache_creation_input_tokens, reasoning_tokens, request_count, ...rest }) => ({ ...rest, ...credential_type !== void 0 ? { credentialType: credential_type } : {}, totalCost: total_cost, ...market_cost !== void 0 ? { marketCost: market_cost } : {}, ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {}, ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {}, ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {}, ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {}, ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {}, ...request_count !== void 0 ? { requestCount: request_count } : {} }) ) ) }) ) ); var GatewayGenerationInfoFetcher = class { constructor(config2) { this.config = config2; } async getGenerationInfo(params) { try { const baseUrl = new URL(this.config.baseURL); const { value } = await getFromApi({ url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`, validateUrl: false, headers: this.config.headers ? await resolve(this.config.headers) : void 0, successfulResponseHandler: createJsonResponseHandler( gatewayGenerationInfoResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error40) { throw await asGatewayError(error40); } } }; var gatewayGenerationInfoResponseSchema = lazySchema( () => zodSchema( external_exports.object({ data: external_exports.object({ id: external_exports.string(), total_cost: external_exports.number(), upstream_inference_cost: external_exports.number(), usage: external_exports.number(), created_at: external_exports.string(), model: external_exports.string(), is_byok: external_exports.boolean(), provider_name: external_exports.string(), streamed: external_exports.boolean(), finish_reason: external_exports.string(), latency: external_exports.number(), generation_time: external_exports.number(), native_tokens_prompt: external_exports.number(), native_tokens_completion: external_exports.number(), native_tokens_reasoning: external_exports.number(), native_tokens_cached: external_exports.number(), native_tokens_cache_creation: external_exports.number(), billable_web_search_calls: external_exports.number() }).transform( ({ total_cost, upstream_inference_cost, created_at, is_byok, provider_name, finish_reason, generation_time, native_tokens_prompt, native_tokens_completion, native_tokens_reasoning, native_tokens_cached, native_tokens_cache_creation, billable_web_search_calls, ...rest }) => ({ ...rest, totalCost: total_cost, upstreamInferenceCost: upstream_inference_cost, createdAt: created_at, isByok: is_byok, providerName: provider_name, finishReason: finish_reason, generationTime: generation_time, promptTokens: native_tokens_prompt, completionTokens: native_tokens_completion, reasoningTokens: native_tokens_reasoning, cachedTokens: native_tokens_cached, cacheCreationTokens: native_tokens_cache_creation, billableWebSearchCalls: billable_web_search_calls }) ) }).transform(({ data }) => data) ) ); var GatewayLanguageModel = class _GatewayLanguageModel { constructor(modelId, config2) { this.modelId = modelId; this.config = config2; this.specificationVersion = "v4"; this.supportedUrls = { "*/*": [/.*/] }; } static [WORKFLOW_SERIALIZE](model) { return serializeModelOptions({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE](options) { return new _GatewayLanguageModel(options.modelId, options.config); } get provider() { return this.config.provider; } async getArgs(options) { const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options; return { args: this.maybeEncodeFileParts(optionsWithoutSignal), warnings: [] }; } async doGenerate(options) { const { args, warnings } = await this.getArgs(options); const { abortSignal } = options; const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0; try { const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, false), await resolve(this.config.o11yHeaders) ), body: args, successfulResponseHandler: createJsonResponseHandler(external_exports.any()), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { ...responseBody, request: { body: args }, response: { headers: responseHeaders, body: rawResponse }, warnings }; } catch (error40) { throw await asGatewayError( error40, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}) ); } } async doStream(options) { const { args, warnings } = await this.getArgs(options); const { abortSignal } = options; const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0; try { const { value: response, responseHeaders } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, true), await resolve(this.config.o11yHeaders) ), body: args, successfulResponseHandler: createEventSourceResponseHandler(external_exports.any()), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { stream: response.pipeThrough( new TransformStream({ start(controller) { if (warnings.length > 0) { controller.enqueue({ type: "stream-start", warnings }); } }, transform(chunk, controller) { if (chunk.success) { const streamPart = chunk.value; if (streamPart.type === "raw" && !options.includeRawChunks) { return; } if (streamPart.type === "response-metadata" && streamPart.timestamp && typeof streamPart.timestamp === "string") { streamPart.timestamp = new Date(streamPart.timestamp); } controller.enqueue(streamPart); } else { controller.error( chunk.error ); } } }) ), request: { body: args }, response: { headers: responseHeaders } }; } catch (error40) { throw await asGatewayError( error40, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}) ); } } /** * Encodes inline `Uint8Array` file data to a base64 string in place. * @param options - The options to encode. * @returns The options with the file data encoded. */ maybeEncodeFileParts(options) { for (const message of options.prompt) { if (!Array.isArray(message.content)) { continue; } for (const part of message.content) { if (part.type === "file" || part.type === "reasoning-file") { part.data = maybeBase64EncodeFileData(part.data); } else if (part.type === "tool-result" && part.output.type === "content") { for (const contentPart of part.output.value) { if (contentPart.type === "file") { contentPart.data = maybeBase64EncodeFileData(contentPart.data); } } } } } return options; } getUrl() { return `${this.config.baseURL}/language-model`; } getModelConfigHeaders(modelId, streaming) { return { "ai-language-model-specification-version": "4", "ai-language-model-id": modelId, "ai-language-model-streaming": String(streaming) }; } }; function maybeBase64EncodeFileData(data) { if (data.type === "data") { const bytes = data.data; if (bytes instanceof Uint8Array) { return { ...data, data: Buffer.from(bytes).toString("base64") }; } } return data; } var GatewayEmbeddingModel = class _GatewayEmbeddingModel { constructor(modelId, config2) { this.modelId = modelId; this.config = config2; this.specificationVersion = "v4"; this.maxEmbeddingsPerCall = 2048; this.supportsParallelCalls = true; } static [WORKFLOW_SERIALIZE](model) { return serializeModelOptions({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE](options) { return new _GatewayEmbeddingModel(options.modelId, options.config); } get provider() { return this.config.provider; } async doEmbed({ values, headers, abortSignal, providerOptions }) { var _a113, _b112; const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0; try { const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders) ), body: { values, ...providerOptions ? { providerOptions } : {} }, successfulResponseHandler: createJsonResponseHandler( gatewayEmbeddingResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { embeddings: responseBody.embeddings, usage: (_a113 = responseBody.usage) != null ? _a113 : void 0, providerMetadata: responseBody.providerMetadata, response: { headers: responseHeaders, body: rawValue }, warnings: (_b112 = responseBody.warnings) != null ? _b112 : [] }; } catch (error40) { throw await asGatewayError( error40, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}) ); } } getUrl() { return `${this.config.baseURL}/embedding-model`; } getModelConfigHeaders() { return { "ai-embedding-model-specification-version": "4", "ai-model-id": this.modelId }; } }; var gatewayEmbeddingWarningSchema = external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("unsupported"), feature: external_exports.string(), details: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("compatibility"), feature: external_exports.string(), details: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("deprecated"), setting: external_exports.string(), message: external_exports.string() }), external_exports.object({ type: external_exports.literal("other"), message: external_exports.string() }) ]); var gatewayEmbeddingResponseSchema = lazySchema( () => zodSchema( external_exports.object({ embeddings: external_exports.array(external_exports.array(external_exports.number())), usage: external_exports.object({ tokens: external_exports.number() }).nullish(), warnings: external_exports.array(gatewayEmbeddingWarningSchema).optional(), providerMetadata: external_exports.record(external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown())).optional() }) ) ); var GatewayImageModel = class _GatewayImageModel { constructor(modelId, config2) { this.modelId = modelId; this.config = config2; this.specificationVersion = "v4"; this.maxImagesPerCall = Number.MAX_SAFE_INTEGER; } static [WORKFLOW_SERIALIZE](model) { return serializeModelOptions({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE](options) { return new _GatewayImageModel(options.modelId, options.config); } get provider() { return this.config.provider; } async doGenerate({ prompt, n: n5, size, aspectRatio, seed, files, mask, providerOptions, headers, abortSignal }) { var _a113, _b112, _c, _d; const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0; try { const { responseHeaders, value: responseBody } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders) ), body: { prompt, n: n5, ...size && { size }, ...aspectRatio && { aspectRatio }, ...seed && { seed }, ...providerOptions && { providerOptions }, ...files && { files: files.map((file2) => maybeEncodeImageFile(file2)) }, ...mask && { mask: maybeEncodeImageFile(mask) } }, successfulResponseHandler: createJsonResponseHandler( gatewayImageResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { images: responseBody.images, // Always base64 strings from server warnings: (_a113 = responseBody.warnings) != null ? _a113 : [], providerMetadata: responseBody.providerMetadata, response: { timestamp: /* @__PURE__ */ new Date(), modelId: this.modelId, headers: responseHeaders }, ...responseBody.usage != null && { usage: { inputTokens: (_b112 = responseBody.usage.inputTokens) != null ? _b112 : void 0, outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0, totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0 } } }; } catch (error40) { throw await asGatewayError( error40, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}) ); } } getUrl() { return `${this.config.baseURL}/image-model`; } getModelConfigHeaders() { return { "ai-image-model-specification-version": "4", "ai-model-id": this.modelId }; } }; function maybeEncodeImageFile(file2) { if (file2.type === "file" && file2.data instanceof Uint8Array) { return { ...file2, data: convertUint8ArrayToBase64(file2.data) }; } return file2; } var providerMetadataEntrySchema = external_exports.object({ images: external_exports.array(external_exports.unknown()).optional() }).catchall(external_exports.unknown()); var gatewayImageWarningSchema = external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("unsupported"), feature: external_exports.string(), details: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("compatibility"), feature: external_exports.string(), details: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("deprecated"), setting: external_exports.string(), message: external_exports.string() }), external_exports.object({ type: external_exports.literal("other"), message: external_exports.string() }) ]); var gatewayImageUsageSchema = external_exports.object({ inputTokens: external_exports.number().nullish(), outputTokens: external_exports.number().nullish(), totalTokens: external_exports.number().nullish() }); var gatewayImageResponseSchema = external_exports.object({ images: external_exports.array(external_exports.string()), // Always base64 strings over the wire warnings: external_exports.array(gatewayImageWarningSchema).optional(), providerMetadata: external_exports.record(external_exports.string(), providerMetadataEntrySchema).optional(), usage: gatewayImageUsageSchema.optional() }); var GatewayVideoModel = class { constructor(modelId, config2) { this.modelId = modelId; this.config = config2; this.specificationVersion = "v4"; this.maxVideosPerCall = Number.MAX_SAFE_INTEGER; } get provider() { return this.config.provider; } async doGenerate({ prompt, n: n5, aspectRatio, resolution, duration: duration3, fps, seed, generateAudio, image, frameImages, inputReferences, providerOptions, headers, abortSignal }) { var _a113; const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0; try { const { responseHeaders, value: responseBody } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders), { accept: "text/event-stream" } ), body: { prompt, n: n5, ...aspectRatio && { aspectRatio }, ...resolution && { resolution }, ...duration3 && { duration: duration3 }, ...fps && { fps }, ...seed && { seed }, ...generateAudio !== void 0 && { generateAudio }, ...providerOptions && { providerOptions }, ...image && { image: maybeEncodeVideoFile(image) }, ...frameImages && { frameImages: frameImages.map((frame) => ({ ...frame, image: maybeEncodeVideoFile(frame.image) })) }, ...inputReferences && { inputReferences: inputReferences.map( (reference) => maybeEncodeVideoFile(reference) ) } }, successfulResponseHandler: async ({ response, url: url2, requestBodyValues }) => { if (response.body == null) { throw new APICallError({ message: "SSE response body is empty", url: url2, requestBodyValues, statusCode: response.status }); } const eventStream = 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: url2, requestBodyValues, statusCode: response.status }); } if (!parseResult.success) { throw new APICallError({ message: "Failed to parse video SSE event", cause: parseResult.error, url: url2, requestBodyValues, statusCode: response.status }); } const event = parseResult.value; if (event.type === "error") { throw new APICallError({ message: event.message, statusCode: event.statusCode, url: url2, 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: external_exports.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { videos: responseBody.videos, warnings: (_a113 = responseBody.warnings) != null ? _a113 : [], providerMetadata: responseBody.providerMetadata, response: { timestamp: /* @__PURE__ */ new Date(), modelId: this.modelId, headers: responseHeaders } }; } catch (error40) { throw await asGatewayError( error40, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}) ); } } getUrl() { return `${this.config.baseURL}/video-model`; } getModelConfigHeaders() { return { "ai-video-model-specification-version": "4", "ai-model-id": this.modelId }; } }; function maybeEncodeVideoFile(file2) { if (file2.type === "file" && file2.data instanceof Uint8Array) { return { ...file2, data: convertUint8ArrayToBase64(file2.data) }; } return file2; } var providerMetadataEntrySchema2 = external_exports.object({ videos: external_exports.array(external_exports.unknown()).optional() }).catchall(external_exports.unknown()); var gatewayVideoDataSchema = external_exports.union([ external_exports.object({ type: external_exports.literal("url"), url: external_exports.string(), mediaType: external_exports.string() }), external_exports.object({ type: external_exports.literal("base64"), data: external_exports.string(), mediaType: external_exports.string() }) ]); var gatewayVideoWarningSchema = external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("unsupported"), feature: external_exports.string(), details: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("compatibility"), feature: external_exports.string(), details: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("deprecated"), setting: external_exports.string(), message: external_exports.string() }), external_exports.object({ type: external_exports.literal("other"), message: external_exports.string() }) ]); var gatewayVideoEventSchema = external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("result"), videos: external_exports.array(gatewayVideoDataSchema), warnings: external_exports.array(gatewayVideoWarningSchema).optional(), providerMetadata: external_exports.record(external_exports.string(), providerMetadataEntrySchema2).optional() }), external_exports.object({ type: external_exports.literal("error"), message: external_exports.string(), errorType: external_exports.string(), statusCode: external_exports.number(), param: external_exports.unknown().nullable() }) ]); var GatewayRerankingModel = class { constructor(modelId, config2) { this.modelId = modelId; this.config = config2; this.specificationVersion = "v4"; } get provider() { return this.config.provider; } async doRerank({ documents, query, topN, headers, abortSignal, providerOptions }) { var _a113; const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0; try { const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders) ), body: { documents, query, ...topN != null ? { topN } : {}, ...providerOptions ? { providerOptions } : {} }, successfulResponseHandler: createJsonResponseHandler( gatewayRerankingResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { ranking: responseBody.ranking, providerMetadata: responseBody.providerMetadata, response: { headers: responseHeaders, body: rawValue }, warnings: (_a113 = responseBody.warnings) != null ? _a113 : [] }; } catch (error40) { throw await asGatewayError( error40, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}) ); } } getUrl() { return `${this.config.baseURL}/reranking-model`; } getModelConfigHeaders() { return { "ai-reranking-model-specification-version": "4", "ai-model-id": this.modelId }; } }; var gatewayRerankingWarningSchema = external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("unsupported"), feature: external_exports.string(), details: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("compatibility"), feature: external_exports.string(), details: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("deprecated"), setting: external_exports.string(), message: external_exports.string() }), external_exports.object({ type: external_exports.literal("other"), message: external_exports.string() }) ]); var gatewayRerankingResponseSchema = lazySchema( () => zodSchema( external_exports.object({ ranking: external_exports.array( external_exports.object({ index: external_exports.number(), relevanceScore: external_exports.number() }) ), warnings: external_exports.array(gatewayRerankingWarningSchema).optional(), providerMetadata: external_exports.record(external_exports.string(), external_exports.record(external_exports.string(), external_exports.unknown())).optional() }) ) ); var GatewaySpeechModel = class { constructor(modelId, config2) { this.modelId = modelId; this.config = config2; this.specificationVersion = "v4"; } get provider() { return this.config.provider; } async doGenerate({ text: text2, voice, outputFormat, instructions, speed, language, providerOptions, headers, abortSignal }) { var _a113; const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0; try { const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders) ), body: { text: text2, ...voice && { voice }, ...outputFormat && { outputFormat }, ...instructions && { instructions }, ...speed != null && { speed }, ...language && { language }, ...providerOptions && { providerOptions } }, successfulResponseHandler: createJsonResponseHandler( gatewaySpeechResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { audio: responseBody.audio, warnings: (_a113 = responseBody.warnings) != null ? _a113 : [], providerMetadata: responseBody.providerMetadata, response: { timestamp: /* @__PURE__ */ new Date(), modelId: this.modelId, headers: responseHeaders, body: rawValue } }; } catch (error40) { throw await asGatewayError( error40, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}) ); } } getUrl() { return `${this.config.baseURL}/speech-model`; } getModelConfigHeaders() { return { "ai-speech-model-specification-version": "4", "ai-model-id": this.modelId }; } }; var providerMetadataEntrySchema3 = external_exports.object({}).catchall(external_exports.unknown()); var gatewaySpeechWarningSchema = external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("unsupported"), feature: external_exports.string(), details: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("compatibility"), feature: external_exports.string(), details: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("deprecated"), setting: external_exports.string(), message: external_exports.string() }), external_exports.object({ type: external_exports.literal("other"), message: external_exports.string() }) ]); var gatewaySpeechResponseSchema = external_exports.object({ audio: external_exports.string(), warnings: external_exports.array(gatewaySpeechWarningSchema).optional(), providerMetadata: external_exports.record(external_exports.string(), providerMetadataEntrySchema3).optional() }); var GatewayTranscriptionModel = class { constructor(modelId, config2) { this.modelId = modelId; this.config = config2; this.specificationVersion = "v4"; } get provider() { return this.config.provider; } async doGenerate({ audio, mediaType, providerOptions, headers, abortSignal }) { var _a113, _b112, _c, _d; const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0; try { const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders) ), body: { audio: audio instanceof Uint8Array ? convertUint8ArrayToBase64(audio) : audio, mediaType, ...providerOptions && { providerOptions } }, successfulResponseHandler: createJsonResponseHandler( gatewayTranscriptionResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { text: responseBody.text, segments: (_a113 = responseBody.segments) != null ? _a113 : [], language: (_b112 = responseBody.language) != null ? _b112 : void 0, durationInSeconds: (_c = responseBody.durationInSeconds) != null ? _c : void 0, warnings: (_d = responseBody.warnings) != null ? _d : [], providerMetadata: responseBody.providerMetadata, response: { timestamp: /* @__PURE__ */ new Date(), modelId: this.modelId, headers: responseHeaders, body: rawValue } }; } catch (error40) { throw await asGatewayError( error40, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}) ); } } async doStream(options) { var _a113, _b112, _c, _d, _e2; const currentDate = (_c = (_b112 = (_a113 = this.config._internal) == null ? void 0 : _a113.currentDate) == null ? void 0 : _b112.call(_a113)) != null ? _c : /* @__PURE__ */ new Date(); const headers = combineHeaders( await resolve((_d = this.config.headers) != null ? _d : {}), (_e2 = options.headers) != null ? _e2 : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders) ); const authMethod = await parseAuthMethod(headers); const startFrame = { type: TRANSCRIPTION_STREAM_START_FRAME_TYPE, inputAudioFormat: options.inputAudioFormat, ...options.providerOptions != null && { providerOptions: options.providerOptions }, ...options.includeRawChunks != null && { includeRawChunks: options.includeRawChunks } }; return { stream: createGatewayTranscriptionStream({ webSocket: this.config.webSocket, url: toGatewayTranscriptionUrl(this.config.baseURL, this.modelId), protocols: getProtocolsFromHeaders(headers), headers, startFrame, audio: options.audio, abortSignal: options.abortSignal, authMethod }), request: { body: startFrame }, response: { timestamp: currentDate, modelId: this.modelId } }; } getUrl() { return `${this.config.baseURL}/transcription-model`; } getModelConfigHeaders() { return { "ai-transcription-model-specification-version": "4", "ai-model-id": this.modelId }; } }; function toGatewayTranscriptionUrl(baseURL, modelId) { const url2 = new URL(`${baseURL.replace(/^http/, "ws")}/transcription-model`); url2.searchParams.set("ai-model-id", modelId); return url2.toString(); } function getProtocolsFromHeaders(headers) { const normalizedHeaders = normalizeHeaders(headers); const authorization = normalizedHeaders.authorization; const token2 = (authorization == null ? void 0 : authorization.startsWith("Bearer ")) ? authorization.slice("Bearer ".length) : void 0; return token2 == null ? [GATEWAY_TRANSCRIPTION_SUBPROTOCOL] : getGatewayTranscriptionProtocols(token2, { teamIdOrSlug: normalizedHeaders[VERCEL_AI_GATEWAY_TEAM_HEADER] }); } var MAX_AUDIO_FRAME_BYTES = 64 * 1024; function createGatewayTranscriptionStream({ webSocket, url: url2, protocols, headers, startFrame, audio, abortSignal, authMethod }) { let finished = false; let cleanup = () => { }; return new ReadableStream({ start: (controller) => { let audioReader; let hasServerErrorPart = false; let lastServerError; let audioStopped = false; let connection; cleanup = (closeCode) => { if (audioReader != null) { void audioReader.cancel().catch(() => { }); } else { void audio.cancel().catch(() => { }); } connection == null ? void 0 : connection.close(closeCode); }; const stopAudio = () => { audioStopped = true; if (audioReader != null) { void audioReader.cancel().catch(() => { }); audioReader = void 0; } else { void audio.cancel().catch(() => { }); } }; const finishWithError = (error40) => { if (finished) return; finished = true; cleanup(); void errorControllerWithGatewayError(controller, error40, authMethod); }; const sendAudio = async (socket) => { const reader = audio.getReader(); audioReader = reader; try { while (true) { const { done, value } = await reader.read(); if (done || finished) break; const bytes = typeof value === "string" ? convertBase64ToUint8Array(value) : value; for (let offset = 0; offset < bytes.length; offset += MAX_AUDIO_FRAME_BYTES) { if (finished) break; socket.send( bytes.subarray(offset, offset + MAX_AUDIO_FRAME_BYTES) ); await waitForWebSocketBufferDrain(socket); } } } finally { reader.releaseLock(); if (audioReader === reader) { audioReader = void 0; } } if (!finished && !audioStopped) { socket.send( JSON.stringify({ type: TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE }) ); } }; connection = connectToWebSocket({ url: url2, protocols, headers, webSocket, abortSignal, onAbort: (reason) => { if (finished) return; finished = true; cleanup(); controller.error(reason); }, onProcessingError: finishWithError, onOpen: (socket) => { socket.send(JSON.stringify(startFrame)); void sendAudio(socket).catch(finishWithError); }, // Server frames are envelope-serialized stream parts; the codec // handles parsing, unknown-part skipping, and timestamp revival. onMessageText: (text2) => { if (finished) return; const part = parseTranscriptionStreamPart(text2); if (part == null) return; if (part.type === "finish") { finished = true; controller.enqueue(part); controller.close(); cleanup(1e3); return; } if (part.type === "error") { hasServerErrorPart = true; lastServerError = part.error; stopAudio(); } controller.enqueue(part); }, onSocketError: () => { finishWithError( new Error("Connection error on AI Gateway transcription stream") ); }, onClose: () => { if (hasServerErrorPart) { if (finished) return; void createErrorFromServerErrorPart( lastServerError, authMethod ).then(finishWithError); return; } finishWithError( new Error( "AI Gateway transcription stream closed before a finish part was received" ) ); } }); }, cancel: () => { if (finished) return; finished = true; cleanup(); } }); } var providerMetadataEntrySchema4 = external_exports.object({}).catchall(external_exports.unknown()); var gatewayTranscriptionWarningSchema = external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("unsupported"), feature: external_exports.string(), details: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("compatibility"), feature: external_exports.string(), details: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("deprecated"), setting: external_exports.string(), message: external_exports.string() }), external_exports.object({ type: external_exports.literal("other"), message: external_exports.string() }) ]); var gatewayTranscriptionResponseSchema = external_exports.object({ text: external_exports.string(), segments: external_exports.array( external_exports.object({ text: external_exports.string(), startSecond: external_exports.number(), endSecond: external_exports.number() }) ).optional(), language: external_exports.string().nullish(), durationInSeconds: external_exports.number().nullish(), warnings: external_exports.array(gatewayTranscriptionWarningSchema).optional(), providerMetadata: external_exports.record(external_exports.string(), providerMetadataEntrySchema4).optional() }); async function errorControllerWithGatewayError(controller, error40, authMethod) { controller.error(await asGatewayError(error40, authMethod)); } function getServerErrorMessage(error40) { if (error40 != null && typeof error40 === "object" && "message" in error40 && typeof error40.message === "string") { return error40.message; } return getErrorMessage(error40); } var SERVER_ERROR_STATUS_CODES = { authentication_error: 401, failed_dependency: 424, forbidden: 403, internal_server_error: 500, invalid_request_error: 400, model_not_found: 404, rate_limit_exceeded: 429 }; async function createErrorFromServerErrorPart(error40, authMethod) { if (typeof error40 === "object" && error40 != null && "message" in error40 && typeof error40.message === "string" && "type" in error40 && typeof error40.type === "string" && error40.type in SERVER_ERROR_STATUS_CODES) { return createGatewayErrorFromResponse({ response: { error: { message: error40.message, type: error40.type } }, statusCode: SERVER_ERROR_STATUS_CODES[error40.type], authMethod }); } return new Error( `AI Gateway transcription stream failed: ${getServerErrorMessage(error40)}` ); } var GatewayRealtimeModel = class { constructor(modelId, config2) { this.specificationVersion = "v4"; this.modelId = modelId; this.provider = config2.provider; this.config = config2; } /** * Mints a single-use, short-lived client secret (`vcst_`) the browser uses to * open the realtime WebSocket without ever holding the long-lived Gateway * credential. The customer's server calls this (via * `gateway.experimental_realtime.getToken`) and hands the returned token to * the browser, which connects with it through the `ai-gateway-auth.` * subprotocol. `expiresAfterSeconds` is forwarded to the mint endpoint; * `sessionConfig` is intentionally unused here — it is applied later via the * normalized `session-update` event. */ async doCreateClientSecret(options) { const secret = await this.config.createClientSecret({ modelId: this.modelId, ...(options == null ? void 0 : options.expiresAfterSeconds) != null && { expiresAfterSeconds: options.expiresAfterSeconds } }); return { token: secret.token, url: toGatewayRealtimeUrl(this.config.baseURL, this.modelId), ...secret.expiresAt != null && { expiresAt: secret.expiresAt } }; } getWebSocketConfig(options) { return { url: options.url, protocols: getGatewayRealtimeProtocols(options.token, { teamIdOrSlug: this.config.teamIdOrSlug }) }; } parseServerEvent(raw) { return raw; } serializeClientEvent(event) { return event; } buildSessionConfig(config2) { return config2; } }; function toGatewayRealtimeUrl(baseURL, modelId) { const url2 = new URL(`${baseURL.replace(/^http/, "ws")}/realtime-model`); url2.searchParams.set("ai-model-id", modelId); return url2.toString(); } var exaSearchInputSchema = lazySchema( () => zodSchema( external_exports.object({ query: external_exports.string().describe("Natural-language web search query. This is required."), type: external_exports.enum(["auto", "fast", "instant"]).optional().describe( "Search method. Use auto for the default balance of speed and quality." ), num_results: external_exports.number().optional().describe("Maximum number of results to return (1-100, default: 10)."), category: external_exports.enum([ "company", "people", "research paper", "news", "personal site", "financial report" ]).optional().describe("Optional content category to focus results."), user_location: external_exports.string().optional().describe("Two-letter ISO country code such as 'US'."), include_domains: external_exports.array(external_exports.string()).optional().describe("Only return results from these domains."), exclude_domains: external_exports.array(external_exports.string()).optional().describe("Exclude results from these domains."), start_published_date: external_exports.string().optional().describe("Only return links published after this ISO 8601 date."), end_published_date: external_exports.string().optional().describe("Only return links published before this ISO 8601 date."), contents: external_exports.object({ text: external_exports.union([ external_exports.boolean(), external_exports.object({ max_characters: external_exports.number().optional(), include_html_tags: external_exports.boolean().optional(), verbosity: external_exports.enum(["compact", "standard", "full"]).optional(), include_sections: external_exports.array( external_exports.enum([ "header", "navigation", "banner", "body", "sidebar", "footer", "metadata" ]) ).optional(), exclude_sections: external_exports.array( external_exports.enum([ "header", "navigation", "banner", "body", "sidebar", "footer", "metadata" ]) ).optional() }) ]).optional(), highlights: external_exports.union([ external_exports.boolean(), external_exports.object({ query: external_exports.string().optional(), max_characters: external_exports.number().optional() }) ]).optional(), max_age_hours: external_exports.number().optional(), livecrawl_timeout: external_exports.number().optional(), subpages: external_exports.number().optional(), subpage_target: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional(), extras: external_exports.object({ links: external_exports.number().optional(), image_links: external_exports.number().optional() }).optional() }).optional().describe("Controls extracted page content and freshness.") }) ) ); var exaSearchOutputSchema = lazySchema( () => zodSchema( external_exports.union([ external_exports.object({ requestId: external_exports.string(), searchType: external_exports.string().optional(), resolvedSearchType: external_exports.string().optional(), results: external_exports.array( external_exports.object({ title: external_exports.string(), url: external_exports.string(), id: external_exports.string(), publishedDate: external_exports.string().nullable().optional(), author: external_exports.string().nullable().optional(), image: external_exports.string().nullable().optional(), favicon: external_exports.string().nullable().optional(), text: external_exports.string().optional(), highlights: external_exports.array(external_exports.string()).optional(), highlightScores: external_exports.array(external_exports.number()).optional(), summary: external_exports.string().optional(), subpages: external_exports.array(external_exports.any()).optional(), extras: external_exports.object({ links: external_exports.array(external_exports.string()).optional(), imageLinks: external_exports.array(external_exports.string()).optional() }).optional() }) ), costDollars: external_exports.object({ total: external_exports.number().optional(), search: external_exports.record(external_exports.string(), external_exports.number()).optional() }).optional() }), external_exports.object({ error: external_exports.enum([ "api_error", "rate_limit", "timeout", "invalid_input", "configuration_error", "execution_error", "unknown" ]), statusCode: external_exports.number().optional(), message: external_exports.string() }) ]) ) ); var exaSearchToolFactory = createProviderExecutedToolFactory({ id: "gateway.exa_search", inputSchema: exaSearchInputSchema, outputSchema: exaSearchOutputSchema }); var exaSearch = (config2 = {}) => exaSearchToolFactory(config2); var parallelSearchInputSchema = lazySchema( () => zodSchema( external_exports.object({ objective: external_exports.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: external_exports.array(external_exports.string()).optional().describe( "Optional search queries to supplement the objective. Maximum 200 characters per query." ), mode: external_exports.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: external_exports.number().optional().describe( "Maximum number of results to return (1-20). Defaults to 10 if not specified." ), source_policy: external_exports.object({ include_domains: external_exports.array(external_exports.string()).optional().describe( "Limit results to these domains. Use plain domain names only \u2014 e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)." ), exclude_domains: external_exports.array(external_exports.string()).optional().describe( "Exclude results from these domains. Use plain domain names only \u2014 e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)." ), after_date: external_exports.string().optional().describe( "Only include results published after this date. Use an ISO 8601 calendar date formatted YYYY-MM-DD (e.g. 2025-01-01); do not include a time." ) }).optional().describe( "Source policy for controlling which domains to include/exclude and freshness." ), excerpts: external_exports.object({ max_chars_per_result: external_exports.number().optional().describe("Maximum characters per result."), max_chars_total: external_exports.number().optional().describe("Maximum total characters across all results.") }).optional().describe("Excerpt configuration for controlling result length."), fetch_policy: external_exports.object({ max_age_seconds: external_exports.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 = lazySchema( () => zodSchema( external_exports.union([ // Success response external_exports.object({ searchId: external_exports.string(), results: external_exports.array( external_exports.object({ url: external_exports.string(), title: external_exports.string(), excerpt: external_exports.string(), publishDate: external_exports.string().nullable().optional(), relevanceScore: external_exports.number().optional() }) ) }), // Error response external_exports.object({ error: external_exports.enum([ "api_error", "rate_limit", "timeout", "invalid_input", "configuration_error", "unknown" ]), statusCode: external_exports.number().optional(), message: external_exports.string() }) ]) ) ); var parallelSearchToolFactory = createProviderExecutedToolFactory({ id: "gateway.parallel_search", inputSchema: parallelSearchInputSchema, outputSchema: parallelSearchOutputSchema }); var parallelSearch = (config2 = {}) => parallelSearchToolFactory(config2); var perplexitySearchInputSchema = lazySchema( () => zodSchema( external_exports.object({ query: external_exports.union([external_exports.string(), external_exports.array(external_exports.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: external_exports.number().optional().describe( "Maximum number of search results to return (1-20, default: 10)" ), max_tokens_per_page: external_exports.number().optional().describe( "Maximum number of tokens to extract per search result page (256-2048, default: 2048)" ), max_tokens: external_exports.number().optional().describe( "Maximum total tokens across all search results (default: 25000, max: 1000000)" ), country: external_exports.string().optional().describe( "Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')" ), search_domain_filter: external_exports.array(external_exports.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: external_exports.array(external_exports.string()).optional().describe( "List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']" ), search_after_date: external_exports.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: external_exports.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: external_exports.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: external_exports.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: external_exports.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 = lazySchema( () => zodSchema( external_exports.union([ // Success response external_exports.object({ results: external_exports.array( external_exports.object({ title: external_exports.string(), url: external_exports.string(), snippet: external_exports.string(), date: external_exports.string().optional(), lastUpdated: external_exports.string().optional() }) ), id: external_exports.string() }), // Error response external_exports.object({ error: external_exports.enum([ "api_error", "rate_limit", "timeout", "invalid_input", "unknown" ]), statusCode: external_exports.number().optional(), message: external_exports.string() }) ]) ) ); var perplexitySearchToolFactory = createProviderExecutedToolFactory({ id: "gateway.perplexity_search", inputSchema: perplexitySearchInputSchema, outputSchema: perplexitySearchOutputSchema }); var perplexitySearch = (config2 = {}) => perplexitySearchToolFactory(config2); var gatewayTools = { /** * Search the web using Exa for current information and token-efficient * excerpts optimized for agent workflows. * * Supports search type, category, domain, date, location, and content * extraction controls. */ exaSearch, /** * Search the web using Parallel AI's Search API for LLM-optimized excerpts. * * Takes a natural language objective and returns relevant excerpts, * replacing multiple keyword searches with a single call for broad * or complex queries. Supports different search types for depth vs * breadth tradeoffs. */ parallelSearch, /** * Search the web using Perplexity's Search API for real-time information, * news, research papers, and articles. * * Provides ranked search results with advanced filtering options including * domain, language, date range, and recency filters. */ perplexitySearch }; async function getVercelRequestId() { var _a113; return (_a113 = (0, import_oidc.getContext)().headers) == null ? void 0 : _a113["x-vercel-id"]; } var VERSION2 = true ? "4.0.23" : "0.0.0-test"; var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1"; var gatewayClientSecretResponseSchema = external_exports.object({ token: external_exports.string(), expiresAt: external_exports.number().nullish() }); function createGateway(options = {}) { var _a113, _b112; let pendingMetadata = null; let metadataCache = null; const cacheRefreshMillis = (_a113 = options.metadataCacheRefreshMillis) != null ? _a113 : 1e3 * 60 * 5; let lastFetchTime = 0; const baseURL = (_b112 = withoutTrailingSlash(options.baseURL)) != null ? _b112 : "https://ai-gateway.vercel.sh/v4/ai"; const createAuthHeaders = (auth) => withUserAgentSuffix( { Authorization: `Bearer ${auth.token}`, "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION, [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod, ...options.teamIdOrSlug != null ? { [VERCEL_AI_GATEWAY_TEAM_HEADER]: options.teamIdOrSlug } : {}, ...options.headers }, `ai-sdk/gateway/${VERSION2}` ); const getHeaders = async () => { try { return createAuthHeaders(await getGatewayAuthToken(options)); } catch (error40) { throw GatewayAuthenticationError.createContextualError({ apiKeyProvided: false, oidcTokenProvided: false, statusCode: 401, cause: error40 }); } }; const getRealtimeAuthToken = async () => { try { return await getGatewayAuthToken(options); } catch (error40) { throw GatewayAuthenticationError.createContextualError({ apiKeyProvided: false, oidcTokenProvided: false, statusCode: 401, cause: error40 }); } }; const mintClientSecret = async (params) => { assertGatewayClientSecretServerEnvironment(); const auth = await getRealtimeAuthToken(); const headers = createAuthHeaders(auth); const url2 = new URL("/v1/realtime/client-secrets", baseURL).toString(); try { const { value } = await postJsonToApi({ url: url2, headers, body: { model: params.modelId, ...params.routeKind != null && { routeKind: params.routeKind }, ...params.expiresAfterSeconds != null && { expiresIn: params.expiresAfterSeconds } }, successfulResponseHandler: createJsonResponseHandler( gatewayClientSecretResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports.any(), errorToMessage: (data) => data }), fetch: options.fetch }); return { token: value.token, ...value.expiresAt != null && { expiresAt: value.expiresAt } }; } catch (error40) { throw await asGatewayError(error40, await parseAuthMethod(headers)); } }; const createO11yHeaders = () => { const deploymentId = loadOptionalSetting({ settingValue: void 0, environmentVariableName: "VERCEL_DEPLOYMENT_ID" }); const environment = loadOptionalSetting({ settingValue: void 0, environmentVariableName: "VERCEL_ENV" }); const region = loadOptionalSetting({ settingValue: void 0, environmentVariableName: "VERCEL_REGION" }); const projectId = loadOptionalSetting({ settingValue: void 0, environmentVariableName: "VERCEL_PROJECT_ID" }); return async () => { const requestId = await getVercelRequestId(); return { ...deploymentId && { "ai-o11y-deployment-id": deploymentId }, ...environment && { "ai-o11y-environment": environment }, ...region && { "ai-o11y-region": region }, ...requestId && { "ai-o11y-request-id": requestId }, ...projectId && { "ai-o11y-project-id": projectId } }; }; }; const createLanguageModel = (modelId) => { return new GatewayLanguageModel(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; const getAvailableModels = async () => { var _a123, _b122, _c; const now2 = (_c = (_b122 = (_a123 = options._internal) == null ? void 0 : _a123.currentDate) == null ? void 0 : _b122.call(_a123).getTime()) != null ? _c : Date.now(); if (!pendingMetadata || now2 - lastFetchTime > cacheRefreshMillis) { lastFetchTime = now2; pendingMetadata = new GatewayFetchMetadata({ baseURL, headers: getHeaders, fetch: options.fetch }).getAvailableModels().then((metadata) => { metadataCache = metadata; return metadata; }).catch(async (error40) => { throw await asGatewayError( error40, await parseAuthMethod(await getHeaders()) ); }); } return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata; }; const getCredits = async () => { return new GatewayFetchMetadata({ baseURL, headers: getHeaders, fetch: options.fetch }).getCredits().catch(async (error40) => { throw await asGatewayError( error40, await parseAuthMethod(await getHeaders()) ); }); }; const getSpendReport = async (params) => { return new GatewaySpendReport({ baseURL, headers: getHeaders, fetch: options.fetch }).getSpendReport(params).catch(async (error40) => { throw await asGatewayError( error40, await parseAuthMethod(await getHeaders()) ); }); }; const getGenerationInfo = async (params) => { return new GatewayGenerationInfoFetcher({ baseURL, headers: getHeaders, fetch: options.fetch }).getGenerationInfo(params).catch(async (error40) => { throw await asGatewayError( error40, await parseAuthMethod(await getHeaders()) ); }); }; const provider = function(modelId) { if (new.target) { throw new Error( "The Gateway Provider model function cannot be called with the new keyword." ); } return createLanguageModel(modelId); }; provider.specificationVersion = "v4"; provider.getAvailableModels = getAvailableModels; provider.getCredits = getCredits; provider.getSpendReport = getSpendReport; provider.getGenerationInfo = getGenerationInfo; provider.imageModel = (modelId) => { return new GatewayImageModel(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; provider.languageModel = createLanguageModel; const createEmbeddingModel = (modelId) => { return new GatewayEmbeddingModel(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; provider.embeddingModel = createEmbeddingModel; provider.textEmbeddingModel = createEmbeddingModel; provider.videoModel = (modelId) => { return new GatewayVideoModel(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; const createRerankingModel = (modelId) => { return new GatewayRerankingModel(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; provider.rerankingModel = createRerankingModel; provider.reranking = createRerankingModel; const createSpeechModel = (modelId) => { return new GatewaySpeechModel(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; provider.speechModel = createSpeechModel; provider.speech = createSpeechModel; const createTranscriptionModel = (modelId) => { return new GatewayTranscriptionModel(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders(), webSocket: options.webSocket }); }; provider.transcriptionModel = createTranscriptionModel; provider.transcription = createTranscriptionModel; provider.experimental_transcription = Object.assign( (modelId) => createTranscriptionModel(modelId), { getToken: async (tokenOptions) => { const secret = await mintClientSecret({ modelId: tokenOptions.model, routeKind: "transcription", ...tokenOptions.expiresAfterSeconds != null && { expiresAfterSeconds: tokenOptions.expiresAfterSeconds } }); return { token: secret.token, url: toGatewayTranscriptionUrl(baseURL, tokenOptions.model), ...secret.expiresAt != null && { expiresAt: secret.expiresAt } }; } } ); const createRealtimeModel = (modelId) => new GatewayRealtimeModel(modelId, { provider: "gateway.realtime", baseURL, teamIdOrSlug: options.teamIdOrSlug, createClientSecret: mintClientSecret }); provider.experimental_realtime = Object.assign( (modelId) => createRealtimeModel(modelId), { getToken: async (tokenOptions) => { const { model: modelId, ...secretOptions } = tokenOptions; const model = createRealtimeModel(modelId); const secret = await model.doCreateClientSecret(secretOptions); return { token: secret.token, url: secret.url, ...secret.expiresAt != null && { expiresAt: secret.expiresAt } }; } } ); provider.chat = provider.languageModel; provider.embedding = provider.embeddingModel; provider.image = provider.imageModel; provider.video = provider.videoModel; provider.tools = gatewayTools; return provider; } var gateway = createGateway(); async function getGatewayAuthToken(options) { const apiKey = loadOptionalSetting({ settingValue: options.apiKey, environmentVariableName: "AI_GATEWAY_API_KEY" }); if (apiKey) { return { token: apiKey, authMethod: "api-key" }; } const oidcToken = await (0, import_oidc2.getVercelOidcToken)(); return { token: oidcToken, authMethod: "oidc" }; } function assertGatewayClientSecretServerEnvironment() { if (typeof globalThis.window !== "undefined") { throw new Error( "AI Gateway client secrets must be minted server-side: minting needs your Gateway credential, which must never reach the browser. Call gateway.experimental_realtime.getToken() or gateway.experimental_transcription.getToken() from your server and pass the returned token to the client." ); } } // node_modules/ai/dist/index.js var __defProp2 = Object.defineProperty; var __export2 = (target, all) => { for (var name222 in all) __defProp2(target, name222, { get: all[name222], enumerable: true }); }; var name17 = "AI_InvalidArgumentError"; var marker18 = `vercel.ai.error.${name17}`; var symbol18 = Symbol.for(marker18); var _a18; var InvalidArgumentError2 = class extends AISDKError { constructor({ parameter, value, message }) { super({ name: name17, message: `Invalid argument for parameter ${parameter}: ${message}` }); this[_a18] = true; this.parameter = parameter; this.value = value; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker18); } }; _a18 = symbol18; var name23 = "AI_InvalidStreamPartError"; var marker23 = `vercel.ai.error.${name23}`; var symbol24 = Symbol.for(marker23); var _a23; _a23 = symbol24; var name33 = "AI_InvalidToolApprovalError"; var marker33 = `vercel.ai.error.${name33}`; var symbol33 = Symbol.for(marker33); var _a33; var InvalidToolApprovalError = class extends AISDKError { constructor({ approvalId }) { super({ name: name33, message: `Tool approval response references unknown approvalId: "${approvalId}". No matching tool-approval-request found in message history.` }); this[_a33] = true; this.approvalId = approvalId; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker33); } }; _a33 = symbol33; var name43 = "AI_InvalidToolApprovalSignatureError"; var marker43 = `vercel.ai.error.${name43}`; var symbol43 = Symbol.for(marker43); var _a43; var InvalidToolApprovalSignatureError = class extends AISDKError { constructor({ approvalId, toolCallId, reason }) { super({ name: name43, message: `Tool approval signature verification failed for approval "${approvalId}" (tool call "${toolCallId}"): ${reason}` }); this[_a43] = true; this.approvalId = approvalId; this.toolCallId = toolCallId; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker43); } }; _a43 = symbol43; var name53 = "AI_InvalidToolInputError"; var marker53 = `vercel.ai.error.${name53}`; var symbol53 = Symbol.for(marker53); var _a53; var InvalidToolInputError = class extends AISDKError { constructor({ toolInput, toolName, cause, message = `Invalid input for tool ${toolName}: ${getErrorMessage(cause)}` }) { super({ name: name53, message, cause }); this[_a53] = true; this.toolInput = toolInput; this.toolName = toolName; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker53); } }; _a53 = symbol53; var name63 = "AI_ToolCallNotFoundForApprovalError"; var marker63 = `vercel.ai.error.${name63}`; var symbol63 = Symbol.for(marker63); var _a63; var ToolCallNotFoundForApprovalError = class extends AISDKError { constructor({ toolCallId, approvalId }) { super({ name: name63, message: `Tool call "${toolCallId}" not found for approval request "${approvalId}".` }); this[_a63] = true; this.toolCallId = toolCallId; this.approvalId = approvalId; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker63); } }; _a63 = symbol63; var name73 = "AI_MissingToolResultsError"; var marker73 = `vercel.ai.error.${name73}`; var symbol73 = Symbol.for(marker73); var _a73; var MissingToolResultsError = class extends AISDKError { constructor({ toolCallIds }) { super({ name: name73, message: `Tool result${toolCallIds.length > 1 ? "s are" : " is"} missing for tool call${toolCallIds.length > 1 ? "s" : ""} ${toolCallIds.join( ", " )}.` }); this[_a73] = true; this.toolCallIds = toolCallIds; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker73); } }; _a73 = symbol73; var name83 = "AI_NoImageGeneratedError"; var marker83 = `vercel.ai.error.${name83}`; var symbol83 = Symbol.for(marker83); var _a83; _a83 = symbol83; var name93 = "AI_NoObjectGeneratedError"; var marker93 = `vercel.ai.error.${name93}`; var symbol93 = Symbol.for(marker93); var _a93; var NoObjectGeneratedError = class extends AISDKError { constructor({ message = "No object generated.", cause, text: text2, response, usage, finishReason }) { super({ name: name93, message, cause }); this[_a93] = true; this.text = text2; this.response = response; this.usage = usage; this.finishReason = finishReason; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker93); } }; _a93 = symbol93; var name102 = "AI_NoOutputGeneratedError"; var marker103 = `vercel.ai.error.${name102}`; var symbol103 = Symbol.for(marker103); var _a103; var NoOutputGeneratedError = class extends AISDKError { // used in isInstance constructor({ message = "No output generated.", cause } = {}) { super({ name: name102, message, cause }); this[_a103] = true; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker103); } }; _a103 = symbol103; var name112 = "AI_NoSpeechGeneratedError"; var marker112 = `vercel.ai.error.${name112}`; var symbol112 = Symbol.for(marker112); var _a112; _a112 = symbol112; var name122 = "AI_NoTranscriptGeneratedError"; var marker122 = `vercel.ai.error.${name122}`; var symbol122 = Symbol.for(marker122); var _a122; _a122 = symbol122; var name132 = "AI_NoVideoGeneratedError"; var marker132 = `vercel.ai.error.${name132}`; var symbol132 = Symbol.for(marker132); var _a132; _a132 = symbol132; var name142 = "AI_NoSuchToolError"; var marker142 = `vercel.ai.error.${name142}`; var symbol142 = Symbol.for(marker142); var _a142; var NoSuchToolError = class extends AISDKError { constructor({ toolName, availableTools = void 0, message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? "No tools are available." : `Available tools: ${availableTools.join(", ")}.`}` }) { super({ name: name142, message }); this[_a142] = true; this.toolName = toolName; this.availableTools = availableTools; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker142); } }; _a142 = symbol142; var name152 = "AI_ToolCallRepairError"; var marker152 = `vercel.ai.error.${name152}`; var symbol152 = Symbol.for(marker152); var _a152; var ToolCallRepairError = class extends AISDKError { constructor({ cause, originalError, message = `Error repairing tool call: ${getErrorMessage(cause)}` }) { super({ name: name152, message, cause }); this[_a152] = true; this.originalError = originalError; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker152); } }; _a152 = symbol152; var UnsupportedModelVersionError = class extends AISDKError { constructor(options) { super({ name: "AI_UnsupportedModelVersionError", message: `Unsupported model version ${options.version} for provider "${options.provider}" and model "${options.modelId}". AI SDK 5 only supports models that implement specification version "v2".` }); this.version = options.version; this.provider = options.provider; this.modelId = options.modelId; } }; var name162 = "AI_UIMessageStreamError"; var marker162 = `vercel.ai.error.${name162}`; var symbol162 = Symbol.for(marker162); var _a162; _a162 = symbol162; var name172 = "AI_InvalidDataContentError"; var marker172 = `vercel.ai.error.${name172}`; var symbol172 = Symbol.for(marker172); var _a172; var InvalidDataContentError = class extends AISDKError { constructor({ content, cause, message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.` }) { super({ name: name172, message, cause }); this[_a172] = true; this.content = content; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker172); } }; _a172 = symbol172; var name18 = "AI_InvalidMessageRoleError"; var marker182 = `vercel.ai.error.${name18}`; var symbol182 = Symbol.for(marker182); var _a182; var InvalidMessageRoleError = class extends AISDKError { constructor({ role, message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".` }) { super({ name: name18, message }); this[_a182] = true; this.role = role; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker182); } }; _a182 = symbol182; var name19 = "AI_MessageConversionError"; var marker19 = `vercel.ai.error.${name19}`; var symbol19 = Symbol.for(marker19); var _a19; _a19 = symbol19; var name20 = "AI_RetryError"; var marker20 = `vercel.ai.error.${name20}`; var symbol20 = Symbol.for(marker20); var _a20; var RetryError = class extends AISDKError { constructor({ message, reason, errors }) { super({ name: name20, message }); this[_a20] = true; this.reason = reason; this.errors = errors; this.lastError = errors[errors.length - 1]; } static isInstance(error40) { return AISDKError.hasMarker(error40, marker20); } }; _a20 = symbol20; function formatWarning({ warning, provider, model }) { const scope = provider != null && model != null ? ` (${provider} / ${model})` : ""; const prefix = `AI SDK Warning${scope}:`; 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 "deprecated": { return `${prefix} Deprecated: "${warning.setting}". ${warning.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 = (options) => { if (options.warnings.length === 0) { return; } const logger = globalThis.AI_SDK_LOG_WARNINGS; if (logger === false) { return; } if (typeof logger === "function") { logger(options); return; } if (!hasLoggedBefore) { hasLoggedBefore = true; console.info(FIRST_WARNING_INFO_MESSAGE); } for (const warning of options.warnings) { const message = formatWarning({ warning, provider: options.provider, model: options.model }); if (typeof process !== "undefined" && typeof process.emitWarning === "function") { process.emitWarning(message, { type: warning.type === "deprecated" ? "DeprecationWarning" : "Warning" }); } else { console.warn(message); } } }; 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 asEmbeddingModelV3(model) { if (model.specificationVersion === "v3") { return model; } logV2CompatibilityWarning({ provider: model.provider, modelId: model.modelId }); return new Proxy(model, { get(target, prop) { if (prop === "specificationVersion") return "v3"; return target[prop]; } }); } function asEmbeddingModelV4(model) { if (model.specificationVersion === "v4") { return model; } const v3Model = model.specificationVersion === "v2" ? asEmbeddingModelV3(model) : model; return new Proxy(v3Model, { get(target, prop) { if (prop === "specificationVersion") return "v4"; return target[prop]; } }); } function asImageModelV3(model) { if (model.specificationVersion === "v3") { return model; } logV2CompatibilityWarning({ provider: model.provider, modelId: model.modelId }); return new Proxy(model, { get(target, prop) { if (prop === "specificationVersion") return "v3"; return target[prop]; } }); } function asImageModelV4(model) { if (model.specificationVersion === "v4") { return model; } const v3Model = model.specificationVersion === "v2" ? asImageModelV3(model) : model; return new Proxy(v3Model, { get(target, prop) { if (prop === "specificationVersion") return "v4"; return target[prop]; } }); } function asLanguageModelV3(model) { if (model.specificationVersion === "v3") { 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: finishReason === "unknown" ? "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 asLanguageModelV4(model) { if (model.specificationVersion === "v4") { return model; } const v3Model = model.specificationVersion === "v2" ? asLanguageModelV3(model) : model; return new Proxy(v3Model, { get(target, prop) { if (prop === "specificationVersion") return "v4"; return target[prop]; } }); } function asRerankingModelV4(model) { if (model.specificationVersion === "v4") { return model; } return new Proxy(model, { get(target, prop) { if (prop === "specificationVersion") return "v4"; return target[prop]; } }); } function asSpeechModelV3(model) { if (model.specificationVersion === "v3") { return model; } logV2CompatibilityWarning({ provider: model.provider, modelId: model.modelId }); return new Proxy(model, { get(target, prop) { if (prop === "specificationVersion") return "v3"; return target[prop]; } }); } function asSpeechModelV4(model) { if (model.specificationVersion === "v4") { return model; } const v3Model = model.specificationVersion === "v2" ? asSpeechModelV3(model) : model; return new Proxy(v3Model, { get(target, prop) { if (prop === "specificationVersion") return "v4"; return target[prop]; } }); } function asTranscriptionModelV3(model) { if (model.specificationVersion === "v3") { return model; } logV2CompatibilityWarning({ provider: model.provider, modelId: model.modelId }); return new Proxy(model, { get(target, prop) { if (prop === "specificationVersion") return "v3"; return target[prop]; } }); } function asTranscriptionModelV4(model) { if (model.specificationVersion === "v4") { return model; } const v3Model = model.specificationVersion === "v2" ? asTranscriptionModelV3(model) : model; return new Proxy(v3Model, { get(target, prop) { if (prop === "specificationVersion") return "v4"; return target[prop]; } }); } function asProviderV3(provider) { if ("specificationVersion" in provider && provider.specificationVersion === "v3") { return provider; } const v2Provider = provider; return { specificationVersion: "v3", languageModel: (modelId) => asLanguageModelV3(v2Provider.languageModel(modelId)), embeddingModel: (modelId) => asEmbeddingModelV3(v2Provider.textEmbeddingModel(modelId)), imageModel: (modelId) => asImageModelV3(v2Provider.imageModel(modelId)), transcriptionModel: v2Provider.transcriptionModel ? (modelId) => asTranscriptionModelV3(v2Provider.transcriptionModel(modelId)) : void 0, speechModel: v2Provider.speechModel ? (modelId) => asSpeechModelV3(v2Provider.speechModel(modelId)) : void 0, rerankingModel: void 0 // v2 providers don't have reranking models }; } function asProviderV4(provider) { if ("specificationVersion" in provider && provider.specificationVersion === "v4") { return provider; } const v3Provider = !("specificationVersion" in provider) || provider.specificationVersion !== "v3" ? asProviderV3(provider) : provider; return { specificationVersion: "v4", languageModel: (modelId) => asLanguageModelV4(v3Provider.languageModel(modelId)), embeddingModel: (modelId) => asEmbeddingModelV4(v3Provider.embeddingModel(modelId)), imageModel: (modelId) => asImageModelV4(v3Provider.imageModel(modelId)), transcriptionModel: v3Provider.transcriptionModel ? (modelId) => asTranscriptionModelV4(v3Provider.transcriptionModel(modelId)) : void 0, speechModel: v3Provider.speechModel ? (modelId) => asSpeechModelV4(v3Provider.speechModel(modelId)) : void 0, rerankingModel: v3Provider.rerankingModel ? (modelId) => asRerankingModelV4(v3Provider.rerankingModel(modelId)) : void 0 }; } function resolveLanguageModel(model) { if (typeof model === "string") { return getGlobalProvider().languageModel(model); } if (!["v4", "v3", "v2"].includes(model.specificationVersion)) { const unsupportedModel = model; throw new UnsupportedModelVersionError({ version: unsupportedModel.specificationVersion, provider: unsupportedModel.provider, modelId: unsupportedModel.modelId }); } return asLanguageModelV4(model); } function getGlobalProvider() { var _a222; const provider = (_a222 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a222 : gateway; return asProviderV4(provider); } function cloneModelMessages(messages) { return messages.map((message) => cloneValue(message)); } function cloneValue(value) { if (value instanceof URL) { return new URL(value.href); } if (Array.isArray(value)) { return value.map((item) => cloneValue(item)); } if (value instanceof Uint8Array) { return new Uint8Array(value); } if (value instanceof ArrayBuffer) { return value.slice(0); } if (value instanceof Date) { return new Date(value); } if (value != null && typeof value === "object") { return Object.fromEntries( Object.entries(value).map(([key, value2]) => [key, cloneValue(value2)]) ); } return value; } var VERSION3 = true ? "7.0.31" : "0.0.0-test"; var download = async ({ url: url2, maxBytes, abortSignal }) => { var _a222; const urlText = url2.toString(); try { const headers = withUserAgentSuffix( {}, `ai-sdk/${VERSION3}`, getRuntimeEnvironmentUserAgent() ); const response = await fetchWithValidatedRedirects({ url: urlText, headers, abortSignal }); if (!response.ok) { await cancelResponseBody(response); throw new DownloadError({ url: urlText, statusCode: response.status, statusText: response.statusText }); } const data = await readResponseWithSizeLimit({ response, url: urlText, maxBytes: maxBytes != null ? maxBytes : DEFAULT_MAX_DOWNLOAD_SIZE }); return { data, mediaType: (_a222 = response.headers.get("content-type")) != null ? _a222 : void 0 }; } catch (error40) { if (DownloadError.isInstance(error40)) { throw error40; } throw new DownloadError({ url: urlText, cause: error40 }); } }; var createDefaultDownloadFunction = (download2 = download) => (requestedDownloads) => Promise.all( requestedDownloads.map( async (requestedDownload) => requestedDownload.isUrlSupportedByModel ? null : await download2(requestedDownload) ) ); function splitDataUrl(dataUrl) { try { const [header, base64Content] = dataUrl.split(","); return { mediaType: header.split(";")[0].split(":")[1], base64Content }; } catch (e5) { return { mediaType: void 0, base64Content: void 0 }; } } function isTaggedFileData(value) { if (typeof value !== "object" || value === null) return false; const type = value.type; return type === "data" || type === "url" || type === "reference" || type === "text"; } function convertUrlToFilePartData(url2) { if (url2.protocol === "data:") { const { mediaType, base64Content } = splitDataUrl(url2.toString()); if (mediaType == null || base64Content == null) { throw new InvalidDataContentError({ content: url2, message: `Invalid data URL format in content ${url2.toString()}` }); } return { data: { type: "data", data: base64Content }, mediaType }; } return { data: { type: "url", url: url2 }, mediaType: void 0 }; } function convertInlineDataToFilePartData(content) { if (content instanceof Uint8Array) { return { data: { type: "data", data: content }, mediaType: void 0 }; } if (content instanceof ArrayBuffer) { return { data: { type: "data", data: new Uint8Array(content) }, mediaType: void 0 }; } if (isBuffer(content)) { return { data: { type: "data", data: new Uint8Array(content) }, mediaType: void 0 }; } return { data: { type: "data", data: content }, mediaType: void 0 }; } function convertToLanguageModelV4FilePart(content) { if (isTaggedFileData(content)) { switch (content.type) { case "data": if (typeof content.data === "string" && content.data.startsWith("data:")) { throw new InvalidDataContentError({ content: content.data, message: 'Data URLs are not valid inline data. Pass them as { type: "url", url } instead.' }); } return convertInlineDataToFilePartData(content.data); case "url": return convertUrlToFilePartData(content.url); case "reference": return { data: { type: "reference", reference: content.reference }, mediaType: void 0 }; case "text": return { data: { type: "text", text: content.text }, mediaType: void 0 }; } } if (content instanceof URL) { return convertUrlToFilePartData(content); } if (typeof content === "string") { try { return convertUrlToFilePartData(new URL(content)); } catch (e5) { return convertInlineDataToFilePartData(content); } } if (isProviderReference(content)) { return { data: { type: "reference", reference: content }, mediaType: void 0 }; } return convertInlineDataToFilePartData(content); } async function convertToLanguageModelPrompt({ prompt, supportedUrls, download: download2 = createDefaultDownloadFunction(), // `provider` is only needed here to convert legacy tool output types via `mapToolResultOutput`. // TODO: remove in v8 when "file-id" and "image-file-id" types are removed provider }) { const downloadedAssets = await downloadAssets( prompt.messages, download2, supportedUrls ); const approvalIdToToolCallId = /* @__PURE__ */ new Map(); for (const message of prompt.messages) { if (message.role === "assistant" && Array.isArray(message.content)) { for (const part of message.content) { if (part.type === "tool-approval-request" && "approvalId" in part && "toolCallId" in part) { approvalIdToToolCallId.set( part.approvalId, part.toolCallId ); } } } } const approvedToolCallIds = /* @__PURE__ */ new Set(); for (const message of prompt.messages) { if (message.role === "tool") { for (const part of message.content) { if (part.type === "tool-approval-response") { const toolCallId = approvalIdToToolCallId.get(part.approvalId); if (toolCallId) { approvedToolCallIds.add(toolCallId); } } } } } const messages = [ ...prompt.instructions != null ? typeof prompt.instructions === "string" ? [{ role: "system", content: prompt.instructions }] : asArray(prompt.instructions).map((message) => ({ role: "system", content: message.content, providerOptions: message.providerOptions })) : [], ...prompt.messages.map( (message) => convertToLanguageModelMessage({ message, downloadedAssets, provider }) ) ]; const combinedMessages = []; for (const message of messages) { if (message.role !== "tool") { combinedMessages.push(message); continue; } const lastCombinedMessage = combinedMessages.at(-1); if ((lastCombinedMessage == null ? 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 (content.type === "tool-call" && !content.providerExecuted) { toolCallIds.add(content.toolCallId); } } break; } case "tool": { for (const content of message.content) { if (content.type === "tool-result") { 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( // Filter out empty tool messages (e.g. if they only contained // tool-approval-response parts that were removed). // This prevents sending invalid empty messages to the provider. // Note: provider-executed tool-approval-response parts are preserved. (message) => message.role !== "tool" || message.content.length > 0 ); } function convertToLanguageModelMessage({ message, downloadedAssets, // `provider` is only needed here to convert legacy tool output types via `mapToolResultOutput`. // TODO: remove in v8 when "file-id" and "image-file-id" types are removed provider }) { const warnings = []; const role = message.role; switch (role) { case "system": { return { role: "system", content: message.content, providerOptions: message.providerOptions }; } case "user": { if (typeof message.content === "string") { return { role: "user", content: [{ type: "text", text: message.content }], providerOptions: message.providerOptions }; } const converted = { role: "user", content: message.content.map((part) => { if (part.type === "image") { warnings.push({ type: "deprecated", setting: '"image" content part', message: `The "image" content part type is deprecated. Use a "file" part with mediaType: 'image' (or a more specific image/* subtype) instead.` }); } return convertImagePartToFilePart(part); }).map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""), providerOptions: message.providerOptions }; if (warnings.length > 0) { logWarnings({ warnings }); } return converted; } case "assistant": { if (typeof message.content === "string") { return { role: "assistant", content: [{ type: "text", text: message.content }], providerOptions: message.providerOptions }; } const converted = { role: "assistant", content: message.content.filter( // remove empty text parts (no text, and no provider options): (part) => part.type !== "text" || part.text !== "" || part.providerOptions != null ).filter( (part) => part.type !== "tool-approval-request" ).map((part) => { const providerOptions = part.providerOptions; switch (part.type) { case "custom": { return { type: "custom", kind: part.kind, providerOptions }; } case "file": { const { data, mediaType } = convertToLanguageModelV4FilePart( part.data ); return { type: "file", data, filename: part.filename, mediaType: mediaType != null ? mediaType : part.mediaType, providerOptions }; } case "reasoning": { return { type: "reasoning", text: part.text, providerOptions }; } case "reasoning-file": { const { data, mediaType } = convertToLanguageModelV4FilePart( part.data ); if (data.type !== "data" && data.type !== "url") { throw new Error( `Unsupported reasoning-file data type: ${data.type}` ); } return { type: "reasoning-file", data, mediaType: mediaType != null ? mediaType : part.mediaType, 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({ output: part.output, provider, warnings, downloadedAssets }), providerOptions }; } } }), providerOptions: message.providerOptions }; if (warnings.length > 0) { logWarnings({ warnings }); } return converted; } case "tool": { const converted = { role: "tool", content: message.content.filter( // Only include tool-approval-response for provider-executed tools (part) => part.type !== "tool-approval-response" || part.providerExecuted ).map((part) => { switch (part.type) { case "tool-result": { return { type: "tool-result", toolCallId: part.toolCallId, toolName: part.toolName, output: mapToolResultOutput({ output: part.output, provider, warnings, downloadedAssets }), providerOptions: part.providerOptions }; } case "tool-approval-response": { return { type: "tool-approval-response", approvalId: part.approvalId, approved: part.approved, reason: part.reason }; } } }), providerOptions: message.providerOptions }; if (warnings.length > 0) { logWarnings({ warnings }); } return converted; } default: { const _exhaustiveCheck = role; throw new InvalidMessageRoleError({ role: _exhaustiveCheck }); } } } function convertImagePartToFilePart(part) { var _a222; if (part.type !== "image") { return part; } return { type: "file", data: part.image, mediaType: (_a222 = part.mediaType) != null ? _a222 : "image", providerOptions: part.providerOptions }; } async function downloadAssets(messages, download2, supportedUrls) { const downloadableFiles = []; for (const message of messages) { if (message.role === "user" && Array.isArray(message.content)) { for (const part of message.content) { const filePart = convertImagePartToFilePart(part); if (filePart.type === "file") { downloadableFiles.push(filePart); } } } if (message.role === "tool") { for (const part of message.content) { if (part.type !== "tool-result") { continue; } if (part.output.type !== "content") { continue; } for (const contentPart of part.output.value) { if (contentPart.type === "file") { downloadableFiles.push(contentPart); } } } } if (message.role === "assistant" && Array.isArray(message.content)) { for (const part of message.content) { if (part.type !== "tool-result") { continue; } if (part.output.type !== "content") { continue; } for (const contentPart of part.output.value) { if (contentPart.type === "file") { downloadableFiles.push(contentPart); } } } } } const plannedDownloads = downloadableFiles.map((part) => { const mediaType = part.mediaType; const { data } = convertToLanguageModelV4FilePart(part.data); return { mediaType, data }; }).filter((part) => part.data.type === "url").map((part) => ({ url: part.data.url, isUrlSupportedByModel: part.mediaType != null && isUrlSupported({ url: part.data.url.toString(), mediaType: part.mediaType, supportedUrls }) })); const downloadedFiles = await download2(plannedDownloads); return Object.fromEntries( downloadedFiles.map( (file2, index) => file2 == null ? null : [ plannedDownloads[index].url.toString(), { data: file2.data, mediaType: file2.mediaType } ] ).filter((file2) => file2 != null) ); } function convertPartToLanguageModelPart(part, downloadedAssets) { if (part.type === "text") { return { type: "text", text: part.text, providerOptions: part.providerOptions }; } const { data: normalizedData, mediaType: dataUrlMediaType } = convertToLanguageModelV4FilePart(part.data); let mediaType = dataUrlMediaType != null ? dataUrlMediaType : part.mediaType; let data = normalizedData; if (data.type === "url") { const downloadedFile = downloadedAssets[data.url.toString()]; if (downloadedFile) { data = { type: "data", data: downloadedFile.data }; if (downloadedFile.mediaType != null && (mediaType == null || !isFullMediaType(mediaType))) { mediaType = downloadedFile.mediaType; } } } if (data.type === "data" && (data.data instanceof Uint8Array || typeof data.data === "string")) { const imageMediaType = detectMediaType({ data: data.data, topLevelType: "image" }); if (imageMediaType != null) { mediaType = imageMediaType; } } if (mediaType == null) { throw new Error(`Media type is missing for file part`); } return { type: "file", mediaType, filename: part.filename, data, providerOptions: part.providerOptions }; } function mapToolResultOutput({ output, // `provider` is only needed here to convert legacy "file-id" and "image-file-id" types to provider references, in case they are using string ID values. // TODO: remove in v8 when "file-id" and "image-file-id" types are removed provider, warnings = [], downloadedAssets }) { if (output.type !== "content") { return output; } return { type: "content", value: output.value.map((item) => { var _a222; switch (item.type) { case "file": { const convertedPart = convertPartToLanguageModelPart( item, downloadedAssets ); if (convertedPart.type !== "file") { throw new Error( "Expected tool result file content to convert to file." ); } return convertedPart; } case "file-data": { warnings.push({ type: "deprecated", setting: '"tool-result" content of type "file-data"', message: `The "file-data" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'data', data } instead.` }); return { type: "file", data: { type: "data", data: item.data }, filename: item.filename, mediaType: item.mediaType, providerOptions: item.providerOptions }; } case "file-url": { const mediaType = (_a222 = item.mediaType) != null ? _a222 : getMediaTypeFromUrl(item.url); let message = `The "file-url" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'url', url } instead.`; if (!item.mediaType) { const inferenceSuffix = mediaType === "application/octet-stream" ? `Unable to infer media type from URL. Defaulting to 'application/octet-stream'.` : `Inferred media type '${mediaType}' from URL.`; message = `The "file-url" tool result content part with URL "${item.url}" is missing a "mediaType". ${inferenceSuffix} ${message}`; } warnings.push({ type: "deprecated", setting: '"tool-result" content of type "file-url"', message }); return { type: "file", data: { type: "url", url: new URL(item.url) }, mediaType, providerOptions: item.providerOptions }; } case "file-id": { warnings.push({ type: "deprecated", setting: '"tool-result" content of type "file-id"', message: `The "file-id" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'reference', reference } instead.` }); return { type: "file", data: { type: "reference", reference: convertFileIdToProviderReference({ fileId: item.fileId, provider }) }, mediaType: "application", providerOptions: item.providerOptions }; } case "file-reference": { warnings.push({ type: "deprecated", setting: '"tool-result" content of type "file-reference"', message: `The "file-reference" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'reference', reference } instead.` }); return { type: "file", data: { type: "reference", reference: item.providerReference }, mediaType: "application", providerOptions: item.providerOptions }; } case "image-data": { warnings.push({ type: "deprecated", setting: '"tool-result" content of type "image-data"', message: `The "image-data" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'data', data } instead.` }); return { type: "file", data: { type: "data", data: item.data }, mediaType: item.mediaType, providerOptions: item.providerOptions }; } case "image-url": { warnings.push({ type: "deprecated", setting: '"tool-result" content of type "image-url"', message: `The "image-url" type for tool result content is deprecated. Use the "file" type with mediaType 'image' (or a specific image/* subtype) and { type: 'url', url } instead.` }); return { type: "file", data: { type: "url", url: new URL(item.url) }, mediaType: "image", providerOptions: item.providerOptions }; } case "image-file-id": { warnings.push({ type: "deprecated", setting: '"tool-result" content of type "image-file-id"', message: `The "image-file-id" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'reference', reference } instead.` }); return { type: "file", data: { type: "reference", reference: convertFileIdToProviderReference({ fileId: item.fileId, provider }) }, mediaType: "image", providerOptions: item.providerOptions }; } case "image-file-reference": { warnings.push({ type: "deprecated", setting: '"tool-result" content of type "image-file-reference"', message: `The "image-file-reference" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'reference', reference } instead.` }); return { type: "file", data: { type: "reference", reference: item.providerReference }, mediaType: "image", providerOptions: item.providerOptions }; } default: return item; } }) }; } function convertFileIdToProviderReference({ fileId, provider }) { if (typeof fileId === "object") { return fileId; } if (provider == null) { throw new Error( "Cannot convert string fileId to provider reference without a provider ID. Use a Record fileId or switch to the file-reference type." ); } return { [provider]: fileId }; } var URL_EXTENSION_TO_MEDIA_TYPE = { jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", gif: "image/gif", webp: "image/webp", svg: "image/svg+xml", avif: "image/avif", heic: "image/heic", bmp: "image/bmp", tiff: "image/tiff", tif: "image/tiff", pdf: "application/pdf", mp4: "video/mp4", webm: "video/webm", mp3: "audio/mpeg", wav: "audio/wav", ogg: "audio/ogg" }; function getMediaTypeFromUrl(url2, fallbackMediaType = "application/octet-stream") { var _a222; try { const pathname = new URL(url2).pathname; const fileExtension2 = (_a222 = pathname.split(".").pop()) == null ? void 0 : _a222.toLowerCase(); if (fileExtension2 && Object.hasOwn(URL_EXTENSION_TO_MEDIA_TYPE, fileExtension2)) { return URL_EXTENSION_TO_MEDIA_TYPE[fileExtension2]; } } catch (e5) { } return fallbackMediaType; } async function createToolModelOutput({ toolCallId, input, output, tool: tool2, errorMode }) { if (errorMode === "text") { return { type: "error-text", value: getErrorMessage(output) }; } else if (errorMode === "json") { return { type: "error-json", value: toJSONValue(output) }; } if (tool2 == null ? void 0 : tool2.toModelOutput) { return await tool2.toModelOutput({ toolCallId, input, output }); } return typeof output === "string" ? { type: "text", value: output } : { type: "json", value: toJSONValue(output) }; } function toJSONValue(value) { return value === void 0 ? null : value; } function prepareLanguageModelCallOptions({ maxOutputTokens, temperature, topP, topK, presencePenalty, frequencyPenalty, seed, stopSequences, reasoning }) { if (maxOutputTokens != null) { if (!Number.isInteger(maxOutputTokens)) { throw new InvalidArgumentError2({ parameter: "maxOutputTokens", value: maxOutputTokens, message: "maxOutputTokens must be an integer" }); } if (maxOutputTokens < 1) { throw new InvalidArgumentError2({ parameter: "maxOutputTokens", value: maxOutputTokens, message: "maxOutputTokens must be >= 1" }); } } if (temperature != null) { if (typeof temperature !== "number") { throw new InvalidArgumentError2({ parameter: "temperature", value: temperature, message: "temperature must be a number" }); } } if (topP != null) { if (typeof topP !== "number") { throw new InvalidArgumentError2({ parameter: "topP", value: topP, message: "topP must be a number" }); } } if (topK != null) { if (typeof topK !== "number") { throw new InvalidArgumentError2({ parameter: "topK", value: topK, message: "topK must be a number" }); } } if (presencePenalty != null) { if (typeof presencePenalty !== "number") { throw new InvalidArgumentError2({ parameter: "presencePenalty", value: presencePenalty, message: "presencePenalty must be a number" }); } } if (frequencyPenalty != null) { if (typeof frequencyPenalty !== "number") { throw new InvalidArgumentError2({ parameter: "frequencyPenalty", value: frequencyPenalty, message: "frequencyPenalty must be a number" }); } } if (seed != null) { if (!Number.isInteger(seed)) { throw new InvalidArgumentError2({ parameter: "seed", value: seed, message: "seed must be an integer" }); } } return { maxOutputTokens, temperature, topP, topK, presencePenalty, frequencyPenalty, stopSequences, seed, reasoning }; } function prepareToolChoice({ toolChoice }) { return toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : { type: "tool", toolName: toolChoice.toolName }; } function isNonEmptyObject(object22) { return object22 != null && Object.keys(object22).length > 0; } async function prepareTools({ tools: tools2, toolOrder, toolsContext = {}, experimental_sandbox: sandbox }) { if (!isNonEmptyObject(tools2)) { return void 0; } const languageModelTools = []; for (const [name222, tool2] of orderToolEntries({ tools: tools2, toolOrder })) { const toolType = tool2.type; switch (toolType) { case void 0: case "dynamic": case "function": { const description = resolveToolDescription({ tool: tool2, toolName: name222, toolsContext, experimental_sandbox: sandbox }); const providerOptions = tool2.providerOptions; const inputExamples = tool2.inputExamples; const strict = tool2.strict; languageModelTools.push({ type: "function", name: name222, inputSchema: await asSchema(tool2.inputSchema).jsonSchema, ...description != null ? { description } : {}, ...inputExamples != null ? { inputExamples } : {}, ...providerOptions != null ? { providerOptions } : {}, ...strict != null ? { strict } : {} }); break; } case "provider": { languageModelTools.push({ type: "provider", name: name222, id: tool2.id, args: tool2.args }); break; } default: { const exhaustiveCheck = toolType; throw new Error(`Unsupported tool type: ${exhaustiveCheck}`); } } } return languageModelTools; } function orderToolEntries({ tools: tools2, toolOrder }) { if (toolOrder == null) { return Object.entries(tools2); } const toolEntries = Object.entries(tools2); const orderedTools = toolEntries.filter(([name222]) => toolOrder.includes(name222)).sort( ([nameA], [nameB]) => toolOrder.indexOf(nameA) - toolOrder.indexOf(nameB) ); const unorderedTools = toolEntries.filter(([name222]) => !toolOrder.includes(name222)).sort(([nameA], [nameB]) => nameA < nameB ? -1 : nameA > nameB ? 1 : 0); return [...orderedTools, ...unorderedTools]; } function resolveToolDescription({ tool: tool2, toolName, toolsContext, experimental_sandbox: sandbox }) { return tool2.description === void 0 ? void 0 : typeof tool2.description === "string" ? tool2.description : tool2.description({ context: toolsContext[toolName], experimental_sandbox: sandbox }); } function getTotalTimeoutMs(timeout) { if (timeout == null) { return void 0; } if (typeof timeout === "number") { return timeout; } return timeout.totalMs; } function getStepTimeoutMs(timeout) { if (timeout == null || typeof timeout === "number") { return void 0; } return timeout.stepMs; } function getToolTimeoutMs(timeout, toolName) { var _a222, _b19; if (timeout == null || typeof timeout === "number") { return void 0; } return (_b19 = (_a222 = timeout.tools) == null ? void 0 : _a222[`${toolName}Ms`]) != null ? _b19 : timeout.toolMs; } var jsonValueSchema = external_exports.lazy( () => external_exports.union([ external_exports.null(), external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.record(external_exports.string(), jsonValueSchema.optional()), external_exports.array(jsonValueSchema) ]) ); var providerMetadataSchema = external_exports.record( external_exports.string(), external_exports.record(external_exports.string(), jsonValueSchema.optional()) ); var fileInlineDataSchema = external_exports.union([ external_exports.string(), external_exports.instanceof(Uint8Array), external_exports.instanceof(ArrayBuffer), external_exports.custom(isBuffer, { message: "Must be a Buffer" }) ]); var providerReferenceSchema = external_exports.record(external_exports.string(), external_exports.string()); var textPartSchema = external_exports.object({ type: external_exports.literal("text"), text: external_exports.string(), providerOptions: providerMetadataSchema.optional() }); var imagePartSchema = external_exports.object({ type: external_exports.literal("image"), image: external_exports.union([ fileInlineDataSchema, external_exports.instanceof(URL), providerReferenceSchema ]), mediaType: external_exports.string().optional(), providerOptions: providerMetadataSchema.optional() }); var taggedFileDataSchema = external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("data"), data: fileInlineDataSchema }), external_exports.object({ type: external_exports.literal("url"), url: external_exports.instanceof(URL) }), external_exports.object({ type: external_exports.literal("reference"), reference: providerReferenceSchema }), external_exports.object({ type: external_exports.literal("text"), text: external_exports.string() }) ]); var taggedReasoningFileDataSchema = external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("data"), data: fileInlineDataSchema }), external_exports.object({ type: external_exports.literal("url"), url: external_exports.instanceof(URL) }) ]); var filePartSchema = external_exports.object({ type: external_exports.literal("file"), data: external_exports.union([ taggedFileDataSchema, fileInlineDataSchema, external_exports.instanceof(URL), providerReferenceSchema ]), filename: external_exports.string().optional(), mediaType: external_exports.string(), providerOptions: providerMetadataSchema.optional() }); var reasoningPartSchema = external_exports.object({ type: external_exports.literal("reasoning"), text: external_exports.string(), providerOptions: providerMetadataSchema.optional() }); var customPartSchema = external_exports.object({ type: external_exports.literal("custom"), kind: external_exports.string().transform((value) => value), providerOptions: providerMetadataSchema.optional() }); var reasoningFilePartSchema = external_exports.object({ type: external_exports.literal("reasoning-file"), data: external_exports.union([ taggedReasoningFileDataSchema, fileInlineDataSchema, external_exports.instanceof(URL) ]), mediaType: external_exports.string(), providerOptions: providerMetadataSchema.optional() }); var toolCallPartSchema = external_exports.object({ type: external_exports.literal("tool-call"), toolCallId: external_exports.string(), toolName: external_exports.string(), input: external_exports.unknown(), providerOptions: providerMetadataSchema.optional(), providerExecuted: external_exports.boolean().optional() }); var outputSchema = external_exports.discriminatedUnion( "type", [ external_exports.object({ type: external_exports.literal("text"), value: external_exports.string(), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("json"), value: jsonValueSchema, providerOptions: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("execution-denied"), reason: external_exports.string().optional(), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("error-text"), value: external_exports.string(), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("error-json"), value: jsonValueSchema, providerOptions: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("content"), value: external_exports.array( external_exports.union([ external_exports.object({ type: external_exports.literal("text"), text: external_exports.string(), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("file"), data: taggedFileDataSchema, mediaType: external_exports.string(), filename: external_exports.string().optional(), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ // Deprecated. type: external_exports.literal("file-data"), data: external_exports.string(), mediaType: external_exports.string(), filename: external_exports.string().optional(), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ // Deprecated. type: external_exports.literal("file-url"), url: external_exports.string(), mediaType: external_exports.string().optional(), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ // Deprecated. type: external_exports.literal("file-id"), fileId: external_exports.union([external_exports.string(), external_exports.record(external_exports.string(), external_exports.string())]), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ // Deprecated. type: external_exports.literal("file-reference"), providerReference: external_exports.record(external_exports.string(), external_exports.string()), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ // Deprecated. type: external_exports.literal("image-data"), data: external_exports.string(), mediaType: external_exports.string(), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ // Deprecated. type: external_exports.literal("image-url"), url: external_exports.string(), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ // Deprecated. type: external_exports.literal("image-file-id"), fileId: external_exports.union([external_exports.string(), external_exports.record(external_exports.string(), external_exports.string())]), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ // Deprecated. type: external_exports.literal("image-file-reference"), providerReference: external_exports.record(external_exports.string(), external_exports.string()), providerOptions: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("custom"), providerOptions: providerMetadataSchema.optional() }) ]) ) }) ] ); var toolResultPartSchema = external_exports.object({ type: external_exports.literal("tool-result"), toolCallId: external_exports.string(), toolName: external_exports.string(), output: outputSchema, providerOptions: providerMetadataSchema.optional() }); var toolApprovalRequestSchema = external_exports.object({ type: external_exports.literal("tool-approval-request"), approvalId: external_exports.string(), toolCallId: external_exports.string() }); var toolApprovalResponseSchema = external_exports.object({ type: external_exports.literal("tool-approval-response"), approvalId: external_exports.string(), approved: external_exports.boolean(), reason: external_exports.string().optional() }); var systemModelMessageSchema = external_exports.object( { role: external_exports.literal("system"), content: external_exports.string(), providerOptions: providerMetadataSchema.optional() } ); var userModelMessageSchema = external_exports.object({ role: external_exports.literal("user"), content: external_exports.union([ external_exports.string(), external_exports.array(external_exports.union([textPartSchema, imagePartSchema, filePartSchema])) ]), providerOptions: providerMetadataSchema.optional() }); var assistantModelMessageSchema = external_exports.object({ role: external_exports.literal("assistant"), content: external_exports.union([ external_exports.string(), external_exports.array( external_exports.union([ textPartSchema, customPartSchema, filePartSchema, reasoningPartSchema, reasoningFilePartSchema, toolCallPartSchema, toolResultPartSchema, toolApprovalRequestSchema ]) ) ]), providerOptions: providerMetadataSchema.optional() }); var toolModelMessageSchema = external_exports.object({ role: external_exports.literal("tool"), content: external_exports.array(external_exports.union([toolResultPartSchema, toolApprovalResponseSchema])), providerOptions: providerMetadataSchema.optional() }); var modelMessageSchema = external_exports.union([ systemModelMessageSchema, userModelMessageSchema, assistantModelMessageSchema, toolModelMessageSchema ]); async function standardizePrompt({ allowSystemInMessages = false, system, instructions = system, prompt, messages }) { if (prompt == null && messages == null) { throw new InvalidPromptError({ prompt, message: "prompt or messages must be defined" }); } if (prompt != null && messages != null) { throw new InvalidPromptError({ prompt, message: "prompt and messages cannot be defined at the same time" }); } if (typeof instructions !== "string" && !asArray(instructions).every((message) => message.role === "system")) { throw new InvalidPromptError({ prompt, message: "instructions must be a string, SystemModelMessage, or array of SystemModelMessage" }); } if (prompt != null && typeof prompt === "string") { messages = [{ role: "user", content: prompt }]; } else if (prompt != null && Array.isArray(prompt)) { messages = prompt; } else if (messages == null) { throw new InvalidPromptError({ prompt, message: "prompt or messages must be defined" }); } if (messages.length === 0) { throw new InvalidPromptError({ prompt, message: "messages must not be empty" }); } if (!allowSystemInMessages && messages.some((message) => message.role === "system")) { throw new InvalidPromptError({ prompt, message: "System messages are not allowed in the prompt or messages fields. Use the instructions option instead." }); } const validationResult = await safeValidateTypes({ value: messages, schema: external_exports.array(modelMessageSchema) }); if (!validationResult.success) { throw new InvalidPromptError({ prompt, message: "The messages do not match the ModelMessage[] schema.", cause: validationResult.error }); } return { messages, instructions }; } function wrapGatewayError(error40) { if (!GatewayAuthenticationError.isInstance(error40)) return error40; const isProductionEnv = (process == null ? 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 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 }; } function addLanguageModelUsage(usage1, usage2) { var _a222, _b19, _c, _d, _e2, _f, _g, _h, _i2, _j; return { inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens), inputTokenDetails: { noCacheTokens: addTokenCounts( (_a222 = usage1.inputTokenDetails) == null ? void 0 : _a222.noCacheTokens, (_b19 = usage2.inputTokenDetails) == null ? void 0 : _b19.noCacheTokens ), cacheReadTokens: addTokenCounts( (_c = usage1.inputTokenDetails) == null ? void 0 : _c.cacheReadTokens, (_d = usage2.inputTokenDetails) == null ? void 0 : _d.cacheReadTokens ), cacheWriteTokens: addTokenCounts( (_e2 = usage1.inputTokenDetails) == null ? void 0 : _e2.cacheWriteTokens, (_f = usage2.inputTokenDetails) == null ? void 0 : _f.cacheWriteTokens ) }, outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens), outputTokenDetails: { textTokens: addTokenCounts( (_g = usage1.outputTokenDetails) == null ? void 0 : _g.textTokens, (_h = usage2.outputTokenDetails) == null ? void 0 : _h.textTokens ), reasoningTokens: addTokenCounts( (_i2 = usage1.outputTokenDetails) == null ? void 0 : _i2.reasoningTokens, (_j = usage2.outputTokenDetails) == null ? void 0 : _j.reasoningTokens ) }, totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens) }; } function addTokenCounts(tokenCount1, tokenCount2) { return tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 != null ? tokenCount1 : 0) + (tokenCount2 != null ? tokenCount2 : 0); } function getOwn(obj, key) { return obj != null && Object.hasOwn(obj, key) ? obj[key] : void 0; } function mergeAbortSignals(...signals) { const validSignals = filterNullable(...signals).map( (signal) => signal instanceof AbortSignal ? signal : AbortSignal.timeout(signal) ); return validSignals.length === 0 ? void 0 : validSignals.length === 1 ? validSignals[0] : AbortSignal.any(validSignals); } function mergeObjects(base, overrides) { if (base === void 0 && overrides === void 0) { return void 0; } if (base === void 0) { return overrides; } if (overrides === void 0) { return base; } const result = { ...base }; for (const key in overrides) { if (key === "__proto__" || key === "constructor" || key === "prototype") { continue; } if (Object.prototype.hasOwnProperty.call(overrides, key)) { const overridesValue = overrides[key]; if (overridesValue === void 0) continue; const baseValue = key in base ? base[key] : void 0; const isSourceObject = overridesValue !== null && typeof overridesValue === "object" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp); const isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === "object" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp); if (isSourceObject && isTargetObject) { result[key] = mergeObjects( baseValue, overridesValue ); } else { result[key] = overridesValue; } } } return result; } function now() { var _a222, _b19; return (_b19 = (_a222 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a222.now()) != null ? _b19 : Date.now(); } async function notify(options) { await Promise.all( asArray(options.callbacks).map(async (callback) => { try { await (callback == null ? void 0 : callback(options.event)); } catch (e5) { } }) ); } function getRetryDelayInMs({ error: error40, exponentialBackoffDelay }) { const headers = APICallError.isInstance(error40) ? error40.responseHeaders : APICallError.isInstance(error40.cause) ? error40.cause.responseHeaders : void 0; if (!headers) return exponentialBackoffDelay; let ms2; const retryAfterMs = headers["retry-after-ms"]; if (retryAfterMs) { const timeoutMs = parseFloat(retryAfterMs); if (!Number.isNaN(timeoutMs)) { ms2 = timeoutMs; } } const retryAfter = headers["retry-after"]; if (retryAfter && ms2 === void 0) { const timeoutSeconds = parseFloat(retryAfter); if (!Number.isNaN(timeoutSeconds)) { ms2 = timeoutSeconds * 1e3; } else { ms2 = Date.parse(retryAfter) - Date.now(); } } if (ms2 != null && !Number.isNaN(ms2) && 0 <= ms2 && (ms2 < 60 * 1e3 || ms2 < exponentialBackoffDelay)) { return ms2; } return exponentialBackoffDelay; } var retryWithExponentialBackoffRespectingRetryHeaders = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal } = {}) => retryWithExponentialBackoff({ maxRetries, initialDelayInMs, backoffFactor, abortSignal, shouldRetry: (error40) => error40 instanceof Error && (APICallError.isInstance(error40) && error40.isRetryable === true || GatewayError.isInstance(error40) && error40.isRetryable === true), getDelayInMs: ({ error: error40, exponentialBackoffDelay }) => getRetryDelayInMs({ error: error40, exponentialBackoffDelay }), createRetryError: ({ message, reason, errors }) => new RetryError({ message, reason, errors }) }); function prepareRetries({ maxRetries, abortSignal }) { if (maxRetries != null) { if (!Number.isInteger(maxRetries)) { throw new InvalidArgumentError2({ parameter: "maxRetries", value: maxRetries, message: "maxRetries must be an integer" }); } if (maxRetries < 0) { throw new InvalidArgumentError2({ parameter: "maxRetries", value: maxRetries, message: "maxRetries must be >= 0" }); } } const maxRetriesResult = maxRetries != null ? maxRetries : 2; return { maxRetries: maxRetriesResult, retry: retryWithExponentialBackoffRespectingRetryHeaders({ maxRetries: maxRetriesResult, abortSignal }) }; } function setAbortTimeout({ abortController, label, timeoutMs }) { if (abortController == null || timeoutMs == null) { return void 0; } return setTimeout( () => abortController.abort( new DOMException( `${label} timeout of ${timeoutMs}ms exceeded`, "TimeoutError" ) ), timeoutMs ); } function calculateTokensPerSecond({ tokens, durationMs }) { const tokenRate = 1e3 * (tokens != null ? tokens : 0) / (durationMs != null ? durationMs : 0); return Number.isFinite(tokenRate) ? tokenRate : 0; } function collectToolApprovals({ messages }) { const lastMessage = messages.at(-1); if ((lastMessage == null ? void 0 : lastMessage.role) != "tool") { return { approvedToolApprovals: [], deniedToolApprovals: [] }; } const toolCallsByToolCallId = /* @__PURE__ */ Object.create(null); for (const message of messages) { if (message.role === "assistant" && typeof message.content !== "string") { const content = message.content; for (const part of content) { if (part.type === "tool-call") { toolCallsByToolCallId[part.toolCallId] = part; } } } } const toolApprovalRequestsByApprovalId = /* @__PURE__ */ Object.create(null); for (const message of messages) { if (message.role === "assistant" && typeof message.content !== "string") { const content = message.content; for (const part of content) { if (part.type === "tool-approval-request") { toolApprovalRequestsByApprovalId[part.approvalId] = part; } } } } const toolResults = /* @__PURE__ */ Object.create(null); for (const part of lastMessage.content) { if (part.type === "tool-result") { toolResults[part.toolCallId] = part; } } const approvedToolApprovals = []; const deniedToolApprovals = []; const approvalResponses = lastMessage.content.filter( (part) => part.type === "tool-approval-response" ); for (const approvalResponse of approvalResponses) { const approvalRequest = toolApprovalRequestsByApprovalId[approvalResponse.approvalId]; if (approvalRequest == null) { throw new InvalidToolApprovalError({ approvalId: approvalResponse.approvalId }); } const existingToolResult = toolResults[approvalRequest.toolCallId]; if (existingToolResult != null && (approvalResponse.approved || existingToolResult.output.type !== "execution-denied")) { continue; } const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId]; if (toolCall == null) { throw new ToolCallNotFoundForApprovalError({ toolCallId: approvalRequest.toolCallId, approvalId: approvalRequest.approvalId }); } const approval = { approvalRequest, approvalResponse, toolCall, ...existingToolResult != null ? { existingToolResult } : {} }; if (approvalResponse.approved) { approvedToolApprovals.push(approval); } else { deniedToolApprovals.push(approval); } } return { approvedToolApprovals, deniedToolApprovals }; } async function validateToolContext({ toolName, context, contextSchema }) { if (contextSchema == null) { return context; } return await validateTypes({ value: context, schema: contextSchema, context: { field: "tool context", entityName: toolName } }); } async function executeToolCall({ toolCall, tools: tools2, toolsContext, callId, messages, abortSignal, timeout, experimental_sandbox: sandbox, onPreliminaryToolResult, onToolExecutionStart, onToolExecutionEnd, executeToolInTelemetryContext = async ({ execute }) => await execute(), runInTracingChannelSpan = async ({ execute }) => await execute() }) { const { toolName, toolCallId, input } = toolCall; const tool2 = getOwn(tools2, toolName); if (!isExecutableTool(tool2)) { return void 0; } const context = await validateToolContext({ toolName, context: getOwn(toolsContext, toolName), contextSchema: tool2.contextSchema }); const toolExecutionContext = { toolCall, messages, toolContext: context }; const baseCallbackEvent = { callId, ...toolExecutionContext }; return await runInTracingChannelSpan({ type: "executeTool", event: baseCallbackEvent, execute: async () => { let output; await notify({ event: baseCallbackEvent, callbacks: onToolExecutionStart }); const toolTimeoutMs = getToolTimeoutMs(timeout, toolName); const toolAbortSignal = mergeAbortSignals(abortSignal, toolTimeoutMs); let toolExecutionMs = 0; try { await executeToolInTelemetryContext({ callId, toolCallId, ...toolExecutionContext, execute: async () => { const startTime = now(); try { const stream = executeTool({ tool: tool2, input, options: { toolCallId, messages, abortSignal: toolAbortSignal, context, experimental_sandbox: sandbox } }); for await (const part of stream) { if (part.type === "preliminary") { onPreliminaryToolResult == null ? void 0 : onPreliminaryToolResult({ ...toolCall, type: "tool-result", output: part.output, preliminary: true }); } else { output = part.output; } } } finally { toolExecutionMs = now() - startTime; } } }); } catch (error40) { const toolError = { type: "tool-error", toolCallId, toolName, input, error: error40, dynamic: tool2.type === "dynamic", ...toolCall.providerMetadata != null ? { providerMetadata: toolCall.providerMetadata } : {}, ...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {} }; await notify({ event: { ...baseCallbackEvent, toolOutput: toolError, toolExecutionMs }, callbacks: onToolExecutionEnd }); return { output: toolError, toolExecutionMs }; } const toolResult = { type: "tool-result", toolCallId, toolName, input, output, dynamic: tool2.type === "dynamic", ...toolCall.providerMetadata != null ? { providerMetadata: toolCall.providerMetadata } : {}, ...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {} }; await notify({ event: { ...baseCallbackEvent, toolOutput: toolResult, toolExecutionMs }, callbacks: onToolExecutionEnd }); return { output: toolResult, toolExecutionMs }; } }); } function filterActiveTools({ tools: tools2, activeTools }) { if (tools2 == null || activeTools == null) { return tools2; } return Object.fromEntries( Object.entries(tools2).filter(([name222]) => activeTools.includes(name222)) ); } 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; } // lazy conversion with caching to avoid unnecessary conversion overhead: get base64() { if (this.base64Data == null) { this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData); } return this.base64Data; } // lazy conversion with caching to avoid unnecessary conversion overhead: get uint8Array() { if (this.uint8ArrayData == null) { this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data); } return this.uint8ArrayData; } }; var output_exports = {}; __export2(output_exports, { array: () => array2, choice: () => choice, json: () => json2, object: () => object2, text: () => text }); function fixJson(input) { const stack = ["ROOT"]; let lastValidIndex = -1; let literalStart = null; let unicodeEscapeDigits = 0; function isHexDigit(char) { return char >= "0" && char <= "9" || char >= "A" && char <= "F" || char >= "a" && char <= "f"; } function processValueStart(char, i4, swapState) { { switch (char) { case '"': { lastValidIndex = i4; stack.pop(); stack.push(swapState); stack.push("INSIDE_STRING"); break; } case "f": case "t": case "n": { lastValidIndex = i4; literalStart = i4; 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 = i4; stack.pop(); stack.push(swapState); stack.push("INSIDE_NUMBER"); break; } case "{": { lastValidIndex = i4; stack.pop(); stack.push(swapState); stack.push("INSIDE_OBJECT_START"); break; } case "[": { lastValidIndex = i4; stack.pop(); stack.push(swapState); stack.push("INSIDE_ARRAY_START"); break; } } } } function processAfterObjectValue(char, i4) { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_OBJECT_AFTER_COMMA"); break; } case "}": { lastValidIndex = i4; stack.pop(); break; } } } function processAfterArrayValue(char, i4) { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_ARRAY_AFTER_COMMA"); break; } case "]": { lastValidIndex = i4; stack.pop(); break; } } } for (let i4 = 0; i4 < input.length; i4++) { const char = input[i4]; const currentState = stack[stack.length - 1]; switch (currentState) { case "ROOT": processValueStart(char, i4, "FINISH"); break; case "INSIDE_OBJECT_START": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_KEY"); break; } case "}": { lastValidIndex = i4; 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, i4, "INSIDE_OBJECT_AFTER_VALUE"); break; } case "INSIDE_OBJECT_AFTER_VALUE": { processAfterObjectValue(char, i4); break; } case "INSIDE_STRING": { switch (char) { case '"': { stack.pop(); lastValidIndex = i4; break; } case "\\": { stack.push("INSIDE_STRING_ESCAPE"); break; } default: { lastValidIndex = i4; } } break; } case "INSIDE_ARRAY_START": { switch (char) { case "]": { lastValidIndex = i4; stack.pop(); break; } default: { lastValidIndex = i4; processValueStart(char, i4, "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 = i4; stack.pop(); break; } default: { lastValidIndex = i4; break; } } break; } case "INSIDE_ARRAY_AFTER_COMMA": { processValueStart(char, i4, "INSIDE_ARRAY_AFTER_VALUE"); break; } case "INSIDE_STRING_ESCAPE": { stack.pop(); if (char === "u") { unicodeEscapeDigits = 0; stack.push("INSIDE_STRING_UNICODE_ESCAPE"); } else { lastValidIndex = i4; } break; } case "INSIDE_STRING_UNICODE_ESCAPE": { if (isHexDigit(char)) { unicodeEscapeDigits++; if (unicodeEscapeDigits === 4) { stack.pop(); lastValidIndex = i4; } } 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 = i4; break; } case "e": case "E": case "-": case ".": { break; } case ",": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i4); } if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i4); } break; } case "}": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i4); } break; } case "]": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i4); } break; } default: { stack.pop(); break; } } break; } case "INSIDE_LITERAL": { const partialLiteral = input.substring(literalStart, i4 + 1); if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) { stack.pop(); if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i4); } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i4); } } else { lastValidIndex = i4; } break; } } } let result = input.slice(0, lastValidIndex + 1); for (let i4 = stack.length - 1; i4 >= 0; i4--) { const state = stack[i4]; 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 (jsonText === void 0) { return { value: void 0, state: "undefined-input" }; } let result = await safeParseJSON({ text: jsonText }); if (result.success) { return { value: result.value, state: "successful-parse" }; } result = await safeParseJSON({ text: fixJson(jsonText) }); if (result.success) { return { value: result.value, state: "repaired-parse" }; } return { value: void 0, state: "failed-parse" }; } var text = () => ({ name: "text", responseFormat: Promise.resolve({ type: "text" }), async parseCompleteOutput({ text: text2 }) { return text2; }, async parsePartialOutput({ text: text2 }) { return { partial: text2 }; }, createElementStreamTransform() { return void 0; } }); var object2 = ({ schema: inputSchema, name: name222, description }) => { const schema = asSchema(inputSchema); return { name: "object", responseFormat: resolve(schema.jsonSchema).then((jsonSchema2) => ({ type: "json", schema: jsonSchema2, ...name222 != null && { name: name222 }, ...description != null && { description } })), async parseCompleteOutput({ text: text2 }, context) { const parseResult = await safeParseJSON({ text: text2 }); if (!parseResult.success) { throw new NoObjectGeneratedError({ message: "No object generated: could not parse the response.", cause: parseResult.error, text: text2, response: context.response, usage: context.usage, finishReason: context.finishReason }); } const validationResult = await safeValidateTypes({ value: parseResult.value, schema }); if (!validationResult.success) { throw new NoObjectGeneratedError({ message: "No object generated: response did not match schema.", cause: validationResult.error, text: text2, response: context.response, usage: context.usage, finishReason: context.finishReason }); } return validationResult.value; }, async parsePartialOutput({ text: text2 }) { const result = await parsePartialJson(text2); switch (result.state) { case "failed-parse": case "undefined-input": { return void 0; } case "repaired-parse": case "successful-parse": { return { // Note: currently no validation of partial results: partial: result.value }; } } }, createElementStreamTransform() { return void 0; } }; }; var array2 = ({ element: inputElementSchema, name: name222, description }) => { const elementSchema = asSchema(inputElementSchema); return { name: "array", // JSON schema that describes an array of elements: responseFormat: resolve(elementSchema.jsonSchema).then((jsonSchema2) => { const { $schema: _$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 }, ...name222 != null && { name: name222 }, ...description != null && { description } }; }), async parseCompleteOutput({ text: text2 }, context) { const parseResult = await safeParseJSON({ text: text2 }); if (!parseResult.success) { throw new NoObjectGeneratedError({ message: "No object generated: could not parse the response.", cause: parseResult.error, text: text2, response: context.response, usage: context.usage, finishReason: context.finishReason }); } const outerValue = parseResult.value; if (outerValue == null || typeof outerValue !== "object" || !("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: context.response, usage: context.usage, finishReason: context.finishReason }); } const validatedElements = []; 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: context.response, usage: context.usage, finishReason: context.finishReason }); } validatedElements.push(validationResult.value); } return validatedElements; }, async parsePartialOutput({ text: text2 }) { const result = await parsePartialJson(text2); switch (result.state) { case "failed-parse": case "undefined-input": { return void 0; } case "repaired-parse": case "successful-parse": { const outerValue = result.value; if (outerValue == null || typeof outerValue !== "object" || !("elements" in outerValue) || !Array.isArray(outerValue.elements)) { return void 0; } const rawElements = result.state === "repaired-parse" && 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 (partialOutput != null) { for (; publishedElements < partialOutput.length; publishedElements++) { controller.enqueue(partialOutput[publishedElements]); } } } }); } }; }; var choice = ({ options: choiceOptions, name: name222, description }) => { return { name: "choice", // JSON schema that describes an enumeration: 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 }, ...name222 != null && { name: name222 }, ...description != null && { description } }), async parseCompleteOutput({ text: text2 }, context) { const parseResult = await safeParseJSON({ text: text2 }); if (!parseResult.success) { throw new NoObjectGeneratedError({ message: "No object generated: could not parse the response.", cause: parseResult.error, text: text2, response: context.response, usage: context.usage, finishReason: context.finishReason }); } const outerValue = parseResult.value; if (outerValue == null || typeof outerValue !== "object" || !("result" in outerValue) || typeof outerValue.result !== "string" || !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: context.response, usage: context.usage, finishReason: context.finishReason }); } return outerValue.result; }, async parsePartialOutput({ text: text2 }) { const result = await parsePartialJson(text2); switch (result.state) { case "failed-parse": case "undefined-input": { return void 0; } case "repaired-parse": case "successful-parse": { const outerValue = result.value; if (outerValue == null || typeof outerValue !== "object" || !("result" in outerValue) || typeof outerValue.result !== "string") { return void 0; } const potentialMatches = choiceOptions.filter( (choiceOption) => choiceOption.startsWith(outerValue.result) ); if (result.state === "successful-parse") { return potentialMatches.includes(outerValue.result) ? { partial: outerValue.result } : void 0; } else { return potentialMatches.length === 1 ? { partial: potentialMatches[0] } : void 0; } } } }, createElementStreamTransform() { return void 0; } }; }; var json2 = ({ name: name222, description } = {}) => { return { name: "json", responseFormat: Promise.resolve({ type: "json", ...name222 != null && { name: name222 }, ...description != null && { description } }), async parseCompleteOutput({ text: text2 }, context) { const parseResult = await safeParseJSON({ text: text2 }); if (!parseResult.success) { throw new NoObjectGeneratedError({ message: "No object generated: could not parse the response.", cause: parseResult.error, text: text2, response: context.response, usage: context.usage, finishReason: context.finishReason }); } return parseResult.value; }, async parsePartialOutput({ text: text2 }) { const result = await parsePartialJson(text2); switch (result.state) { case "failed-parse": case "undefined-input": { return void 0; } case "repaired-parse": case "successful-parse": { return result.value === void 0 ? void 0 : { partial: result.value }; } } }, createElementStreamTransform() { return void 0; } }; }; async function parseToolCall({ toolCall, tools: tools2, repairToolCall, refineToolInput, messages, instructions }) { try { if (tools2 == null) { if (toolCall.providerExecuted && toolCall.dynamic) { return await refineParsedToolCallInput({ toolCall: await parseProviderExecutedDynamicToolCall(toolCall), refineToolInput }); } throw new NoSuchToolError({ toolName: toolCall.toolName }); } try { return await refineParsedToolCallInput({ toolCall: await doParseToolCall({ toolCall, tools: tools2 }), refineToolInput }); } catch (error40) { if (repairToolCall == null || !(NoSuchToolError.isInstance(error40) || InvalidToolInputError.isInstance(error40))) { throw error40; } let repairedToolCall = null; try { repairedToolCall = await repairToolCall({ toolCall, tools: tools2, inputSchema: async ({ toolName }) => { var _a222; const inputSchema = (_a222 = getOwn(tools2, toolName)) == null ? void 0 : _a222.inputSchema; return await asSchema(inputSchema).jsonSchema; }, instructions, system: instructions, messages, error: error40 }); } catch (repairError) { throw new ToolCallRepairError({ cause: repairError, originalError: error40 }); } if (repairedToolCall == null) { throw error40; } return await refineParsedToolCallInput({ toolCall: await doParseToolCall({ toolCall: repairedToolCall, tools: tools2 }), refineToolInput }); } } catch (error40) { const parsedInput = await safeParseJSON({ text: toolCall.input }); const input = parsedInput.success ? parsedInput.value : toolCall.input; const tool2 = getOwn(tools2, toolCall.toolName); return { type: "tool-call", toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, input, dynamic: true, invalid: true, error: error40, title: tool2 == null ? void 0 : tool2.title, providerExecuted: toolCall.providerExecuted, providerMetadata: toolCall.providerMetadata, ...(tool2 == null ? void 0 : tool2.metadata) != null ? { toolMetadata: tool2.metadata } : {} }; } } async function refineParsedToolCallInput({ toolCall, refineToolInput }) { const refine2 = getOwn(refineToolInput, toolCall.toolName); if (refine2 == null) { return toolCall; } return { ...toolCall, input: await refine2(toolCall.input) }; } async function parseProviderExecutedDynamicToolCall(toolCall) { const parseResult = toolCall.input.trim() === "" ? { success: true, value: {} } : await safeParseJSON({ text: toolCall.input }); if (parseResult.success === false) { 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: tools2 }) { const toolName = toolCall.toolName; const tool2 = getOwn(tools2, toolName); if (tool2 == null) { if (toolCall.providerExecuted && toolCall.dynamic) { return await parseProviderExecutedDynamicToolCall(toolCall); } throw new NoSuchToolError({ toolName: toolCall.toolName, availableTools: Object.keys(tools2) }); } const schema = asSchema(tool2.inputSchema); const parseResult = toolCall.input.trim() === "" ? await safeValidateTypes({ value: {}, schema }) : await safeParseJSON({ text: toolCall.input, schema }); if (parseResult.success === false) { throw new InvalidToolInputError({ toolName, toolInput: toolCall.input, cause: parseResult.error }); } return tool2.type === "dynamic" ? { type: "tool-call", toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, input: parseResult.value, providerExecuted: toolCall.providerExecuted, providerMetadata: toolCall.providerMetadata, ...tool2.metadata != null ? { toolMetadata: tool2.metadata } : {}, dynamic: true, title: tool2.title } : { type: "tool-call", toolCallId: toolCall.toolCallId, toolName, input: parseResult.value, providerExecuted: toolCall.providerExecuted, providerMetadata: toolCall.providerMetadata, ...tool2.metadata != null ? { toolMetadata: tool2.metadata } : {}, title: tool2.title }; } function unwrapReasoningFileData(data) { if (typeof data === "object" && data !== null && "type" in data) { return data.type === "data" ? data.data : data.url; } return data; } function convertFromReasoningOutputs(parts) { return parts.map((part) => { if (part.type === "reasoning") { return { type: "reasoning", text: part.text, ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {} }; } return { type: "reasoning-file", data: part.file.base64, mediaType: part.file.mediaType, ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {} }; }); } function convertToReasoningOutputs(parts) { return parts.map((part) => { if (part.type === "reasoning") { return { type: "reasoning", text: part.text, ...part.providerOptions != null ? { providerMetadata: part.providerOptions } : {} }; } const rawData = unwrapReasoningFileData(part.data); const fileData = rawData instanceof ArrayBuffer ? new Uint8Array(rawData) : rawData instanceof URL ? rawData.toString() : rawData; return { type: "reasoning-file", file: new DefaultGeneratedFile({ data: fileData, mediaType: part.mediaType }), ...part.providerOptions != null ? { providerMetadata: part.providerOptions } : {} }; }); } async function resolveToolApproval({ tools: tools2, toolCall, toolApproval, messages, toolsContext, runtimeContext }) { if (toolApproval != null && typeof toolApproval === "function") { return normalizeToolApprovalStatus( await toolApproval({ toolCall, tools: tools2, toolsContext, messages, runtimeContext }) ); } const toolName = toolCall.toolName; const tool2 = getOwn(tools2, toolName); const input = toolCall.input; const userDefinedToolApprovalStatus = getOwn(toolApproval, toolName); if (userDefinedToolApprovalStatus != null) { const approvalStatus = typeof userDefinedToolApprovalStatus === "function" ? await userDefinedToolApprovalStatus(input, { toolCallId: toolCall.toolCallId, messages, toolContext: await validateToolContext({ toolName, context: getOwn(toolsContext, toolName), contextSchema: tool2 == null ? void 0 : tool2.contextSchema }), runtimeContext }) : userDefinedToolApprovalStatus; return normalizeToolApprovalStatus(approvalStatus); } if ((tool2 == null ? void 0 : tool2.needsApproval) == null) { return { type: "not-applicable" }; } const needsApproval = typeof tool2.needsApproval === "function" ? await tool2.needsApproval(input, { toolCallId: toolCall.toolCallId, messages, context: await validateToolContext({ toolName, context: getOwn(toolsContext, toolName), contextSchema: tool2 == null ? void 0 : tool2.contextSchema }) }) : tool2.needsApproval; return needsApproval ? { type: "user-approval" } : { type: "not-applicable" }; } function normalizeToolApprovalStatus(status) { return status === void 0 ? { type: "not-applicable" } : typeof status === "string" ? { type: status } : status; } function mergeCallbacks(...callbacks) { return async (event) => { await Promise.allSettled( callbacks.map(async (callback) => { await (callback == null ? void 0 : callback(event)); }) ); }; } var AI_SDK_TELEMETRY_TRACING_CHANNEL = "ai:telemetry"; function isNodeRuntime() { var _a222; return typeof process !== "undefined" && ((_a222 = process.release) == null ? void 0 : _a222.name) === "node"; } var diagnosticsChannelPromise; async function loadDiagnosticsChannel() { if (!isNodeRuntime()) { return void 0; } if (diagnosticsChannelPromise == null) { diagnosticsChannelPromise = Promise.resolve( loadBuiltinModule("node:diagnostics_channel") ); } return diagnosticsChannelPromise; } function loadBuiltinModule(id) { var _a222; const processWithBuiltins = globalThis.process; try { return (_a222 = processWithBuiltins == null ? void 0 : processWithBuiltins.getBuiltinModule) == null ? void 0 : _a222.call(processWithBuiltins, id); } catch (e5) { return void 0; } } async function runWithTracingChannelSpan(message, execute) { var _a222; const diagnosticsChannel = await loadDiagnosticsChannel(); const tracingChannel = (_a222 = diagnosticsChannel == null ? void 0 : diagnosticsChannel.tracingChannel) == null ? void 0 : _a222.call( diagnosticsChannel, AI_SDK_TELEMETRY_TRACING_CHANNEL ); if (tracingChannel == null || tracingChannel.hasSubscribers === false) { return await execute(); } let executePromise; let executionResult; let executionError; let hasExecutionResult = false; let hasExecutionError = false; const tracedExecute = () => { try { executePromise = Promise.resolve(execute()); } catch (error40) { executePromise = Promise.reject(error40); } executePromise = executePromise.then( (result) => { executionResult = result; hasExecutionResult = true; return result; }, (error40) => { executionError = error40; hasExecutionError = true; throw error40; } ); return executePromise; }; try { return await tracingChannel.tracePromise(tracedExecute, message); } catch (e5) { if (hasExecutionError) { throw executionError; } if (hasExecutionResult) { return executionResult; } if (executePromise != null) { return await executePromise; } return await execute(); } } function openTelemetryChannelSpanContext({ message, completion }) { var _a222; if (!isNodeRuntime()) { return void 0; } const diagnosticsChannel = loadBuiltinModule( "node:diagnostics_channel" ); const asyncHooks = loadBuiltinModule("node:async_hooks"); const tracingChannel = (_a222 = diagnosticsChannel == null ? void 0 : diagnosticsChannel.tracingChannel) == null ? void 0 : _a222.call( diagnosticsChannel, AI_SDK_TELEMETRY_TRACING_CHANNEL ); if (tracingChannel == null || tracingChannel.hasSubscribers === false || asyncHooks == null) { Promise.resolve(completion).catch(() => { }); return void 0; } const context = message; let asyncResource; let asyncEndPublished = false; const safePublish = (publish) => { try { publish(); } catch (e5) { } }; const publishAsyncEnd = ({ result, error: error40 }) => { if (asyncEndPublished) { return; } asyncEndPublished = true; if (error40 !== void 0) { context.error = error40; safePublish(() => tracingChannel.error.publish(context)); } if (result !== void 0) { context.result = result; } safePublish(() => tracingChannel.asyncEnd.publish(context)); }; safePublish(() => { tracingChannel.start.runStores(context, () => { asyncResource = new asyncHooks.AsyncResource("ai.telemetry"); }); }); safePublish(() => tracingChannel.end.publish(context)); void Promise.resolve(completion).then( (result) => publishAsyncEnd({ result }), (error40) => publishAsyncEnd({ error: error40 }) ); return { run: (execute) => asyncResource == null ? execute() : asyncResource.runInAsyncScope(execute) }; } function getGlobalTelemetryIntegrations() { var _a222; return (_a222 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a222 : []; } function augmentEvent(event, telemetry) { return Object.assign( Object.create(Object.getPrototypeOf(event)), event, telemetry ); } function createTelemetryDispatcher({ telemetry }) { if ((telemetry == null ? void 0 : telemetry.isEnabled) === false) { return {}; } const localIntegrations = telemetry == null ? void 0 : telemetry.integrations; const integrations = localIntegrations != null ? asArray(localIntegrations) : getGlobalTelemetryIntegrations(); const telemetryMetadata = { recordInputs: telemetry == null ? void 0 : telemetry.recordInputs, recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs, functionId: telemetry == null ? void 0 : telemetry.functionId }; const mergeTelemetryCallback = (key) => { const integrationCallbacks = integrations.map((integration) => { var _a222; return (_a222 = integration[key]) == null ? void 0 : _a222.bind(integration); }).filter(Boolean).map( (callback) => (event) => callback(augmentEvent(event, telemetryMetadata)) ); const mergedIntegrationCallback = mergeCallbacks(...integrationCallbacks); return async (event) => { await mergedIntegrationCallback(event); }; }; const executeLanguageModelCallWrappers = integrations.map((integration) => { var _a222; return (_a222 = integration.executeLanguageModelCall) == null ? void 0 : _a222.bind(integration); }).filter(Boolean); const executeToolWrappers = integrations.map((integration) => { var _a222; return (_a222 = integration.executeTool) == null ? void 0 : _a222.bind(integration); }).filter(Boolean); return { runInTracingChannelSpan: async ({ type, event, execute }) => await runWithTracingChannelSpan( { type, event: augmentEvent(event, telemetryMetadata) }, execute ), startTracingChannelContext: ({ type, event, completion }) => openTelemetryChannelSpanContext({ message: { type, event: augmentEvent(event, telemetryMetadata) }, completion }), onStart: mergeTelemetryCallback("onStart"), onStepStart: mergeTelemetryCallback("onStepStart"), onLanguageModelCallStart: mergeTelemetryCallback( "onLanguageModelCallStart" ), onLanguageModelCallEnd: mergeTelemetryCallback("onLanguageModelCallEnd"), onToolExecutionStart: mergeTelemetryCallback("onToolExecutionStart"), onToolExecutionEnd: mergeTelemetryCallback("onToolExecutionEnd"), // Fan out step-end events to both the new `onStepEnd` callback and the // deprecated `onStepFinish` callback so integrations that still implement // only `onStepFinish` keep receiving step-end events during the deprecation // window. onStepEnd: mergeCallbacks( mergeTelemetryCallback("onStepEnd"), mergeTelemetryCallback("onStepFinish") ), onObjectStepStart: mergeTelemetryCallback("onObjectStepStart"), onObjectStepEnd: mergeTelemetryCallback("onObjectStepEnd"), onEmbedStart: mergeTelemetryCallback("onEmbedStart"), onEmbedEnd: mergeTelemetryCallback("onEmbedEnd"), onRerankStart: mergeTelemetryCallback("onRerankStart"), onRerankEnd: mergeTelemetryCallback("onRerankEnd"), onEnd: mergeTelemetryCallback("onEnd"), onAbort: mergeTelemetryCallback("onAbort"), onError: mergeTelemetryCallback("onError"), /** * Runs provider calls inside integration-specific context so * auto-instrumented provider requests can be associated with model work. */ executeLanguageModelCall: async ({ execute, ...event }) => { const augmentedEvent = augmentEvent(event, telemetryMetadata); let wrappedExecute = execute; for (const executeWrapper of executeLanguageModelCallWrappers) { const innerExecute = wrappedExecute; wrappedExecute = () => executeWrapper({ ...augmentedEvent, execute: innerExecute }); } return await runWithTracingChannelSpan( { type: "languageModelCall", event: augmentedEvent }, wrappedExecute ); }, /** * Composes all `executeTool` wrappers around the original tool execution. * Each wrapper receives an `execute` function that calls the next wrapper in * the chain, so integrations can establish nested telemetry context before * delegating to the underlying tool. */ executeTool: async ({ execute, ...event }) => { const augmentedEvent = augmentEvent(event, telemetryMetadata); let wrappedExecute = execute; for (const executeWrapper of executeToolWrappers) { const innerExecute = wrappedExecute; wrappedExecute = () => executeWrapper({ ...augmentedEvent, execute: innerExecute }); } return await wrappedExecute(); } }; } function asReasoningText(reasoningParts) { const reasoningText = reasoningParts.map((part) => "text" in part ? part.text : "").join(""); return reasoningText.length > 0 ? reasoningText : void 0; } var DefaultStepResult = class { constructor({ callId, stepNumber, provider, modelId, runtimeContext, toolsContext, content, finishReason, rawFinishReason, usage, performance, warnings, request, response, providerMetadata }) { this.callId = callId; this.stepNumber = stepNumber; this.model = { provider, modelId }; this.runtimeContext = runtimeContext; this.toolsContext = toolsContext; this.content = content; this.finishReason = finishReason; this.rawFinishReason = rawFinishReason; this.usage = usage; this.performance = performance; this.warnings = warnings; this.request = request; this.response = response; this.providerMetadata = providerMetadata; } get text() { return this.content.filter((part) => part.type === "text").map((part) => part.text).join(""); } get reasoning() { return convertFromReasoningOutputs( this.content.filter( (part) => part.type === "reasoning" || part.type === "reasoning-file" ) ); } get reasoningText() { return asReasoningText(this.reasoning); } get files() { return this.content.filter((part) => part.type === "file").map((part) => part.file); } get sources() { return this.content.filter((part) => part.type === "source"); } get toolCalls() { return this.content.filter((part) => part.type === "tool-call"); } get staticToolCalls() { return this.toolCalls.filter( (toolCall) => toolCall.dynamic !== true ); } get dynamicToolCalls() { return this.toolCalls.filter( (toolCall) => toolCall.dynamic === true ); } get toolResults() { return this.content.filter((part) => part.type === "tool-result"); } get staticToolResults() { return this.toolResults.filter( (toolResult) => toolResult.dynamic !== true ); } get dynamicToolResults() { return this.toolResults.filter( (toolResult) => toolResult.dynamic === true ); } }; function filterIncludedContext({ context, includeContext }) { if (context == null) { return {}; } return Object.fromEntries( Object.entries(context).filter( ([key]) => (includeContext == null ? void 0 : includeContext[key]) === true ) ); } function restrictStepResult({ step, includeRuntimeContext, includeToolsContext }) { return new DefaultStepResult({ callId: step.callId, stepNumber: step.stepNumber, provider: step.model.provider, modelId: step.model.modelId, runtimeContext: filterIncludedContext({ context: step.runtimeContext, includeContext: includeRuntimeContext }), toolsContext: filterToolsContext({ toolsContext: step.toolsContext, includeToolsContext }), content: step.content, finishReason: step.finishReason, rawFinishReason: step.rawFinishReason, usage: step.usage, performance: step.performance, warnings: step.warnings, request: step.request, response: step.response, providerMetadata: step.providerMetadata }); } function filterToolsContext({ toolsContext, includeToolsContext }) { if (includeToolsContext == null) { return {}; } return Object.fromEntries( Object.entries(toolsContext).map(([toolName, toolContext]) => [ toolName, filterToolContext({ toolName, toolContext, includeToolsContext }) ]) ); } function filterToolContext({ toolName, toolContext, includeToolsContext }) { const includeToolContext = includeToolsContext == null ? void 0 : includeToolsContext[toolName]; return filterIncludedContext({ context: toolContext, includeContext: includeToolContext }); } function createRestrictedTelemetryDispatcher({ telemetry, includeRuntimeContext, includeToolsContext }) { const telemetryDispatcher = createTelemetryDispatcher({ telemetry }); return { ...telemetryDispatcher, onStart: (event) => { var _a222; return (_a222 = telemetryDispatcher.onStart) == null ? void 0 : _a222.call(telemetryDispatcher, { ...event, runtimeContext: filterIncludedContext({ context: event.runtimeContext, includeContext: includeRuntimeContext }), toolsContext: filterToolsContext({ toolsContext: event.toolsContext, includeToolsContext }) }); }, onStepStart: (event) => { var _a222; return (_a222 = telemetryDispatcher.onStepStart) == null ? void 0 : _a222.call(telemetryDispatcher, { ...event, runtimeContext: filterIncludedContext({ context: event.runtimeContext, includeContext: includeRuntimeContext }), steps: event.steps.map( (step) => restrictStepResult({ step, includeRuntimeContext, includeToolsContext }) ), toolsContext: filterToolsContext({ toolsContext: event.toolsContext, includeToolsContext }) }); }, onStepEnd: (event) => { var _a222; return (_a222 = telemetryDispatcher.onStepEnd) == null ? void 0 : _a222.call( telemetryDispatcher, restrictStepResult({ step: event, includeRuntimeContext, includeToolsContext }) ); }, onStepFinish: (event) => { var _a222; return (_a222 = telemetryDispatcher.onStepEnd) == null ? void 0 : _a222.call( telemetryDispatcher, restrictStepResult({ step: event, includeRuntimeContext, includeToolsContext }) ); }, onEnd: (event) => { var _a222; return (_a222 = telemetryDispatcher.onEnd) == null ? void 0 : _a222.call( telemetryDispatcher, ((restrictedSteps) => { return { ...event, runtimeContext: filterIncludedContext({ context: event.runtimeContext, includeContext: includeRuntimeContext }), steps: restrictedSteps, finalStep: restrictedSteps.at(-1), toolsContext: filterToolsContext({ toolsContext: event.toolsContext, includeToolsContext }) }; })( event.steps.map( (step) => restrictStepResult({ step, includeRuntimeContext, includeToolsContext }) ) ) ); }, onAbort: (event) => { var _a222; return (_a222 = telemetryDispatcher.onAbort) == null ? void 0 : _a222.call(telemetryDispatcher, { ...event, steps: event.steps.map( (step) => restrictStepResult({ step, includeRuntimeContext, includeToolsContext }) ) }); }, onToolExecutionStart: (event) => { var _a222; return (_a222 = telemetryDispatcher.onToolExecutionStart) == null ? void 0 : _a222.call(telemetryDispatcher, { ...event, toolContext: filterToolContext({ toolName: event.toolCall.toolName, toolContext: event.toolContext, includeToolsContext }) }); }, onToolExecutionEnd: (event) => { var _a222; return (_a222 = telemetryDispatcher.onToolExecutionEnd) == null ? void 0 : _a222.call(telemetryDispatcher, { ...event, toolContext: filterToolContext({ toolName: event.toolCall.toolName, toolContext: event.toolContext, includeToolsContext }) }); } }; } function isStepCount(stepCount) { return ({ steps }) => steps.length === stepCount; } async function isStopConditionMet({ stopConditions, steps }) { return (await Promise.all(stopConditions.map((condition) => condition({ steps })))).some((result) => result); } function sumTokenCounts(tokenCount1, tokenCount2) { return tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 != null ? tokenCount1 : 0) + (tokenCount2 != null ? tokenCount2 : 0); } async function toResponseMessages({ content: inputContent, tools: tools2 }) { const responseMessages = []; const toolCallOrder = /* @__PURE__ */ new Map(); const content = []; for (const part of inputContent) { if (part.type === "source") { continue; } if ((part.type === "tool-result" || part.type === "tool-error") && !part.providerExecuted) { continue; } if (part.type === "text" && part.text.length === 0) { continue; } switch (part.type) { case "text": content.push({ type: "text", text: part.text, providerOptions: part.providerMetadata }); break; case "custom": content.push({ type: "custom", kind: part.kind, 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 "reasoning-file": content.push({ type: "reasoning-file", data: part.file.base64, mediaType: part.file.mediaType, providerOptions: part.providerMetadata }); break; case "tool-call": if (!toolCallOrder.has(part.toolCallId)) { toolCallOrder.set(part.toolCallId, toolCallOrder.size); } content.push({ type: "tool-call", toolCallId: part.toolCallId, toolName: part.toolName, input: part.invalid && typeof part.input !== "object" ? {} : part.input, providerExecuted: part.providerExecuted, providerOptions: part.providerMetadata }); break; case "tool-result": { const output = await createToolModelOutput({ toolCallId: part.toolCallId, input: part.input, tool: getOwn(tools2, 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: getOwn(tools2, 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, isAutomatic: part.isAutomatic, ...part.signature != null ? { signature: part.signature } : {} }); break; } } if (content.length > 0) { responseMessages.push({ role: "assistant", content }); } const toolResultContent = []; for (const part of inputContent) { if (part.type !== "tool-approval-response" && part.type !== "tool-result" && part.type !== "tool-error") { continue; } if (part.type === "tool-approval-response") { toolResultContent.push({ type: "tool-approval-response", approvalId: part.approvalId, approved: part.approved, reason: part.reason, providerExecuted: part.providerExecuted }); if (part.approved === false) { toolResultContent.push({ type: "tool-result", toolCallId: part.toolCall.toolCallId, toolName: part.toolCall.toolName, output: { type: "execution-denied", reason: part.reason } }); } continue; } if (part.providerExecuted) { continue; } const output = await createToolModelOutput({ toolCallId: part.toolCallId, input: part.input, tool: getOwn(tools2, part.toolName), output: part.type === "tool-result" ? part.output : part.error, errorMode: part.type === "tool-error" ? "text" : "none" }); toolResultContent.push({ type: "tool-result", toolCallId: part.toolCallId, toolName: part.toolName, output, ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {} }); } if (toolResultContent.length > 0) { responseMessages.push({ role: "tool", content: sortToolResultContentByToolCallOrder({ toolResultContent, toolCallOrder }) }); } return responseMessages; } function sortToolResultContentByToolCallOrder({ toolResultContent, toolCallOrder }) { const sortedToolResults = toolResultContent.filter((part) => part.type === "tool-result").map((part, index) => ({ part, index })).sort((a3, b5) => { const aOrder = toolCallOrder.get(a3.part.toolCallId); const bOrder = toolCallOrder.get(b5.part.toolCallId); if (aOrder == null && bOrder == null) { return a3.index - b5.index; } if (aOrder == null) { return 1; } if (bOrder == null) { return -1; } return aOrder - bOrder || a3.index - b5.index; }).map(({ part }) => part); let toolResultIndex = 0; return toolResultContent.map( (part) => part.type === "tool-result" ? sortedToolResults[toolResultIndex++] : part ); } var encoder = new TextEncoder(); function canonicalJSON(value) { if (value === null || value === void 0) { return JSON.stringify(value); } if (typeof value !== "object") { return JSON.stringify(value); } if (Array.isArray(value)) { return `[${value.map(canonicalJSON).join(",")}]`; } const keys = Object.keys(value).sort(); const entries = keys.map( (k) => `${JSON.stringify(k)}:${canonicalJSON(value[k])}` ); return `{${entries.join(",")}}`; } function toBase64url(bytes) { return convertUint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, ""); } async function hashCanonical(value) { const digest = await crypto.subtle.digest( "SHA-256", encoder.encode(canonicalJSON(value)) ); return toBase64url(new Uint8Array(digest)); } var encoder2 = new TextEncoder(); function fromBase64url(str) { return convertBase64ToUint8Array(str); } async function importKey(secret) { const keyData = typeof secret === "string" ? encoder2.encode(secret) : secret; return crypto.subtle.importKey( "raw", keyData, { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"] ); } function buildPayload(approvalId, toolCallId, toolName, inputDigest) { return encoder2.encode( `${approvalId} ${toolCallId} ${toolName} ${inputDigest}` ); } async function signToolApproval({ secret, approvalId, toolCallId, toolName, input }) { const key = await importKey(secret); const inputDigest = await hashCanonical(input); const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest); const sig = await crypto.subtle.sign("HMAC", key, payload); return toBase64url(new Uint8Array(sig)); } async function verifyToolApprovalSignature({ secret, signature, approvalId, toolCallId, toolName, input }) { const key = await importKey(secret); const inputDigest = await hashCanonical(input); const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest); const sigBytes = fromBase64url(signature); return crypto.subtle.verify("HMAC", key, sigBytes, payload); } async function maybeSignApproval({ secret, approvalId, toolCallId, toolName, input }) { if (secret == null) return void 0; return signToolApproval({ secret, approvalId, toolCallId, toolName, input }); } async function validateApprovedToolApprovals({ approvedToolApprovals, tools: tools2, toolApproval, messages, toolsContext, runtimeContext, toolApprovalSecret }) { var _a222; const approved = []; const denied = []; for (const approval of approvedToolApprovals) { const { toolCall, approvalRequest } = approval; const tool2 = getOwn(tools2, toolCall.toolName); if (toolApprovalSecret != null) { if (approvalRequest.signature == null) { throw new InvalidToolApprovalSignatureError({ approvalId: approvalRequest.approvalId, toolCallId: toolCall.toolCallId, reason: "missing signature" }); } const valid = await verifyToolApprovalSignature({ secret: toolApprovalSecret, signature: approvalRequest.signature, approvalId: approvalRequest.approvalId, toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, input: toolCall.input }); if (!valid) { throw new InvalidToolApprovalSignatureError({ approvalId: approvalRequest.approvalId, toolCallId: toolCall.toolCallId, reason: "invalid signature" }); } } if (isExecutableTool(tool2) && tool2.inputSchema != null) { const validation = await safeValidateTypes({ value: toolCall.input, schema: asSchema(tool2.inputSchema) }); if (!validation.success) { throw new InvalidToolInputError({ toolName: toolCall.toolName, toolInput: JSON.stringify(toolCall.input), cause: validation.error }); } } const approvalStatus = await resolveToolApproval({ tools: tools2, toolApproval, toolCall, messages, toolsContext, runtimeContext }); if (approvalStatus.type === "denied") { denied.push({ ...approval, approvalResponse: { ...approval.approvalResponse, approved: false, reason: (_a222 = approvalStatus.reason) != null ? _a222 : approval.approvalResponse.reason } }); } else { approved.push(approval); } } return { approvedToolApprovals: approved, deniedToolApprovals: denied }; } var originalGenerateId = createIdGenerator({ prefix: "aitxt", size: 24 }); var originalGenerateCallId = createIdGenerator({ prefix: "call", size: 24 }); async function generateText({ model: modelArg, tools: tools2, toolChoice, instructions, system, prompt, messages, allowSystemInMessages, maxRetries: maxRetriesArg, abortSignal, timeout, headers, stopWhen = isStepCount(1), experimental_sandbox: sandbox, output, toolApproval, experimental_toolApprovalSecret, experimental_telemetry, telemetry = experimental_telemetry, providerOptions, activeTools, toolOrder, prepareStep, experimental_repairToolCall, repairToolCall = experimental_repairToolCall, experimental_refineToolInput: refineToolInput, experimental_download: download2, runtimeContext = {}, toolsContext = {}, experimental_include, include = experimental_include, _internal: { generateId: generateId2 = originalGenerateId, generateCallId = originalGenerateCallId, now: now2 = now } = {}, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onLanguageModelCallStart, experimental_onLanguageModelCallStart, onLanguageModelCallEnd, experimental_onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, experimental_onToolCallStart, experimental_onToolCallFinish, onStepEnd, onStepFinish, onFinish, onEnd = onFinish, ...settings }) { var _a222, _b19, _c, _d; include = { requestBody: (_a222 = include == null ? void 0 : include.requestBody) != null ? _a222 : false, requestMessages: (_b19 = include == null ? void 0 : include.requestMessages) != null ? _b19 : false, responseBody: (_c = include == null ? void 0 : include.responseBody) != null ? _c : false }; const model = resolveLanguageModel(modelArg); const stopConditions = asArray(stopWhen); const resolvedOnStart = onStart != null ? onStart : experimental_onStart; const resolvedOnStepStart = onStepStart != null ? onStepStart : experimental_onStepStart; const resolvedOnLanguageModelCallStart = onLanguageModelCallStart != null ? onLanguageModelCallStart : experimental_onLanguageModelCallStart; const resolvedOnLanguageModelCallEnd = onLanguageModelCallEnd != null ? onLanguageModelCallEnd : experimental_onLanguageModelCallEnd; const resolvedOnToolExecutionStart = onToolExecutionStart != null ? onToolExecutionStart : experimental_onToolCallStart; const resolvedOnToolExecutionEnd = onToolExecutionEnd != null ? onToolExecutionEnd : experimental_onToolCallFinish; const resolvedOnStepEnd = onStepEnd != null ? onStepEnd : onStepFinish; const totalTimeoutMs = getTotalTimeoutMs(timeout); const stepTimeoutMs = getStepTimeoutMs(timeout); const stepAbortController = stepTimeoutMs != null ? new AbortController() : void 0; const mergedAbortSignal = mergeAbortSignals( abortSignal, totalTimeoutMs, stepAbortController == null ? void 0 : stepAbortController.signal ); const { maxRetries, retry } = prepareRetries({ maxRetries: maxRetriesArg, abortSignal: mergedAbortSignal }); const callSettings = prepareLanguageModelCallOptions(settings); const headersWithUserAgent = withUserAgentSuffix( headers != null ? headers : {}, `ai/${VERSION3}` ); const initialPrompt = await standardizePrompt({ instructions, system, prompt, messages, allowSystemInMessages }); const callId = generateCallId(); const telemetryDispatcher = createRestrictedTelemetryDispatcher({ telemetry, includeRuntimeContext: telemetry == null ? void 0 : telemetry.includeRuntimeContext, includeToolsContext: telemetry == null ? void 0 : telemetry.includeToolsContext }); const runInTracingChannelSpan = (_d = telemetryDispatcher.runInTracingChannelSpan) != null ? _d : async ({ execute }) => await execute(); const generateTextStartEvent = { callId, operationId: "ai.generateText", provider: model.provider, modelId: model.modelId, instructions: initialPrompt.instructions, messages: initialPrompt.messages, tools: tools2, toolChoice, activeTools, toolOrder, maxOutputTokens: callSettings.maxOutputTokens, temperature: callSettings.temperature, topP: callSettings.topP, topK: callSettings.topK, presencePenalty: callSettings.presencePenalty, frequencyPenalty: callSettings.frequencyPenalty, stopSequences: callSettings.stopSequences, seed: callSettings.seed, reasoning: callSettings.reasoning, maxRetries, timeout, headers: headersWithUserAgent, providerOptions, output, runtimeContext, toolsContext }; const executeGenerateText = async () => { var _a232; await notify({ event: generateTextStartEvent, callbacks: [resolvedOnStart, telemetryDispatcher.onStart] }); try { const initialMessages = initialPrompt.messages; const initialResponseMessages = []; const { approvedToolApprovals, deniedToolApprovals: collectedDeniedToolApprovals } = collectToolApprovals({ messages: initialMessages }); const { approvedToolApprovals: localApprovedToolApprovals, deniedToolApprovals: revalidationDeniedToolApprovals } = await validateApprovedToolApprovals({ approvedToolApprovals: approvedToolApprovals.filter( (toolApproval2) => !toolApproval2.toolCall.providerExecuted ), tools: tools2, toolApproval, messages: initialMessages, toolsContext, runtimeContext, toolApprovalSecret: experimental_toolApprovalSecret }); const deniedToolApprovals = [ ...collectedDeniedToolApprovals, ...revalidationDeniedToolApprovals ]; const deniedToolApprovalsWithoutResults = deniedToolApprovals.filter( (toolApproval2) => toolApproval2.existingToolResult == null ); if (deniedToolApprovalsWithoutResults.length > 0 || localApprovedToolApprovals.length > 0) { const toolResults2 = await executeTools({ toolCalls: localApprovedToolApprovals.map( (toolApproval2) => toolApproval2.toolCall ), tools: tools2, callId, messages: initialMessages, abortSignal: mergedAbortSignal, timeout, experimental_sandbox: sandbox, toolsContext, onToolExecutionStart: (event) => notify({ event, callbacks: [ resolvedOnToolExecutionStart, telemetryDispatcher.onToolExecutionStart ] }), onToolExecutionEnd: (event) => notify({ event, callbacks: [ resolvedOnToolExecutionEnd, telemetryDispatcher.onToolExecutionEnd ] }), executeToolInTelemetryContext: telemetryDispatcher.executeTool, runInTracingChannelSpan }); const toolContent = []; for (const result of toolResults2) { const output2 = result.output; const modelOutput = await createToolModelOutput({ toolCallId: output2.toolCallId, input: output2.input, tool: getOwn(tools2, output2.toolName), output: output2.type === "tool-result" ? output2.output : output2.error, errorMode: output2.type === "tool-error" ? "text" : "none" }); toolContent.push({ type: "tool-result", toolCallId: output2.toolCallId, toolName: output2.toolName, output: modelOutput }); } for (const toolApproval2 of deniedToolApprovalsWithoutResults) { toolContent.push({ type: "tool-result", toolCallId: toolApproval2.toolCall.toolCallId, toolName: toolApproval2.toolCall.toolName, output: { type: "execution-denied", reason: toolApproval2.approvalResponse.reason, // For provider-executed tools, include approvalId so provider can correlate ...toolApproval2.toolCall.providerExecuted && { providerOptions: { openai: { approvalId: toolApproval2.approvalResponse.approvalId } } } } }); } initialResponseMessages.push({ role: "tool", content: toolContent }); } const callSettings2 = prepareLanguageModelCallOptions(settings); let currentModelResponse; let clientToolCalls = []; let clientToolOutputs = []; let toolApprovalResponses = []; let deniedToolApprovalResponses = []; const steps = []; let instructionsForNextStep = initialPrompt.instructions; let messagesForNextStep = [ ...initialMessages, ...initialResponseMessages ]; const pendingDeferredToolCalls = /* @__PURE__ */ new Map(); do { const stepTimeoutId = setAbortTimeout({ abortController: stepAbortController, label: "Step", timeoutMs: stepTimeoutMs }); const stepNumber = steps.length; try { await runInTracingChannelSpan({ type: "step", event: { callId, stepNumber }, execute: async () => { var _a242, _b23, _c2, _d2, _e2, _f, _g, _h, _i2, _j, _k, _l, _m, _n3, _o, _p, _q; const accumulatedResponseMessages = [ ...initialResponseMessages, ...steps.flatMap((step) => step.response.messages) ]; const stepInputMessages = messagesForNextStep; const prepareStepResult = await (prepareStep == null ? void 0 : prepareStep({ model, steps, stepNumber: steps.length, instructions: instructionsForNextStep, initialInstructions: initialPrompt.instructions, messages: stepInputMessages, initialMessages, responseMessages: accumulatedResponseMessages, runtimeContext, toolsContext, experimental_sandbox: sandbox })); const stepSandbox = (_a242 = prepareStepResult == null ? void 0 : prepareStepResult.experimental_sandbox) != null ? _a242 : sandbox; const stepModel = resolveLanguageModel( (_b23 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _b23 : model ); const stepInstructions = (_d2 = (_c2 = prepareStepResult == null ? void 0 : prepareStepResult.instructions) != null ? _c2 : prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _d2 : instructionsForNextStep; const promptMessages = await convertToLanguageModelPrompt({ prompt: { instructions: stepInstructions, messages: (_e2 = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _e2 : stepInputMessages }, supportedUrls: await stepModel.supportedUrls, download: download2, provider: stepModel.provider.split(".")[0] }); runtimeContext = (_f = prepareStepResult == null ? void 0 : prepareStepResult.runtimeContext) != null ? _f : runtimeContext; toolsContext = (_g = prepareStepResult == null ? void 0 : prepareStepResult.toolsContext) != null ? _g : toolsContext; const stepActiveTools = filterActiveTools({ tools: tools2, activeTools: (_h = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _h : activeTools }); const stepToolOrder = (_i2 = prepareStepResult == null ? void 0 : prepareStepResult.toolOrder) != null ? _i2 : toolOrder; const stepTools = await prepareTools({ tools: stepActiveTools, toolOrder: stepToolOrder, // active tools context is a subset of the tools context, so we can cast to the unknown type toolsContext, experimental_sandbox: stepSandbox }); const stepToolChoice = prepareToolChoice({ toolChoice: (_j = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _j : toolChoice }); const stepMessages = (_k = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _k : stepInputMessages; const stepProviderOptions = mergeObjects( providerOptions, prepareStepResult == null ? void 0 : prepareStepResult.providerOptions ); await notify({ event: { callId, provider: stepModel.provider, modelId: stepModel.modelId, stepNumber, instructions: stepInstructions, messages: stepMessages, tools: tools2, toolChoice: (_l = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _l : toolChoice, activeTools: (_m = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _m : activeTools, toolOrder: stepToolOrder, steps: [...steps], providerOptions: stepProviderOptions, output, runtimeContext, promptMessages, stepTools, stepToolChoice, toolsContext }, callbacks: [ resolvedOnStepStart, telemetryDispatcher.onStepStart ] }); const languageModelCallContext = { provider: stepModel.provider, modelId: stepModel.modelId, instructions: stepInstructions, messages: stepMessages, tools: stepTools, ...callSettings2 }; const languageModelCallStartEvent = { callId, ...languageModelCallContext }; const stepStartTimestampMs = now2(); await notify({ event: languageModelCallStartEvent, callbacks: [ resolvedOnLanguageModelCallStart, telemetryDispatcher.onLanguageModelCallStart ] }); const executeLanguageModelCallInTelemetryContext = (_n3 = telemetryDispatcher.executeLanguageModelCall) != null ? _n3 : async ({ execute }) => await execute(); currentModelResponse = await retry(async () => { var _a25, _b33, _c3, _d3, _e22, _f2, _g2, _h2; const result = await executeLanguageModelCallInTelemetryContext( { ...languageModelCallStartEvent, execute: async () => await stepModel.doGenerate({ ...callSettings2, tools: stepTools, toolChoice: stepToolChoice, responseFormat: await (output == null ? void 0 : output.responseFormat), prompt: promptMessages, providerOptions: stepProviderOptions, abortSignal: mergedAbortSignal, headers: headersWithUserAgent }) } ); const responseData = { id: (_b33 = (_a25 = result.response) == null ? void 0 : _a25.id) != null ? _b33 : generateId2(), timestamp: (_d3 = (_c3 = result.response) == null ? void 0 : _c3.timestamp) != null ? _d3 : /* @__PURE__ */ new Date(), modelId: (_f2 = (_e22 = result.response) == null ? void 0 : _e22.modelId) != null ? _f2 : stepModel.modelId, headers: (_g2 = result.response) == null ? void 0 : _g2.headers, body: (_h2 = result.response) == null ? void 0 : _h2.body }; return { ...result, response: responseData }; }); const responseTimeMs = now2() - stepStartTimestampMs; const stepUsage = asLanguageModelUsage( currentModelResponse.usage ); const stepToolCalls = await Promise.all( currentModelResponse.content.filter( (part) => part.type === "tool-call" ).map( (toolCall) => parseToolCall({ toolCall, tools: tools2, repairToolCall, refineToolInput, instructions: stepInstructions, messages: stepMessages }) ) ); const toolApprovalRequests = {}; const stepToolApprovalResponses = {}; const blockedToolCallIds = /* @__PURE__ */ new Set(); const modelCallContent = asContent({ content: currentModelResponse.content, toolCalls: stepToolCalls, toolOutputs: [], toolApprovalRequests: [], toolApprovalResponses: [], tools: tools2 }); await notify({ event: { callId, provider: stepModel.provider, modelId: stepModel.modelId, finishReason: currentModelResponse.finishReason.unified, usage: stepUsage, content: modelCallContent, responseId: currentModelResponse.response.id, performance: { responseTimeMs, effectiveOutputTokensPerSecond: calculateTokensPerSecond({ tokens: stepUsage.outputTokens, durationMs: responseTimeMs }), outputTokensPerSecond: void 0, inputTokensPerSecond: void 0, effectiveTotalTokensPerSecond: calculateTokensPerSecond({ tokens: sumTokenCounts( stepUsage.inputTokens, stepUsage.outputTokens ), durationMs: responseTimeMs }), timeToFirstOutputMs: void 0 } }, callbacks: [ resolvedOnLanguageModelCallEnd, telemetryDispatcher.onLanguageModelCallEnd ] }); for (const toolCall of stepToolCalls) { if (toolCall.invalid) { continue; } const tool2 = getOwn(tools2, toolCall.toolName); if (tool2 == null) { continue; } if (tool2.onInputStart != null) { await tool2.onInputStart({ toolCallId: toolCall.toolCallId, messages: stepMessages, abortSignal: mergedAbortSignal, context: runtimeContext }); } if ((tool2 == null ? void 0 : tool2.onInputAvailable) != null) { await tool2.onInputAvailable({ input: toolCall.input, toolCallId: toolCall.toolCallId, messages: stepMessages, abortSignal: mergedAbortSignal, context: runtimeContext }); } const toolApprovalStatus = await resolveToolApproval({ tools: tools2, toolApproval, toolCall, messages: stepMessages, toolsContext, runtimeContext }); if (toolApprovalStatus.type === "not-applicable") { continue; } const approvalId = generateId2(); const signature = await maybeSignApproval({ secret: experimental_toolApprovalSecret, approvalId, toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, input: toolCall.input }); switch (toolApprovalStatus.type) { case "user-approval": { toolApprovalRequests[toolCall.toolCallId] = { type: "tool-approval-request", approvalId, toolCall, ...signature != null ? { signature } : {} }; blockedToolCallIds.add(toolCall.toolCallId); break; } case "approved": { toolApprovalRequests[toolCall.toolCallId] = { type: "tool-approval-request", approvalId, toolCall, isAutomatic: true, ...signature != null ? { signature } : {} }; stepToolApprovalResponses[toolCall.toolCallId] = { type: "tool-approval-response", approvalId, toolCall, approved: true, reason: toolApprovalStatus.reason, providerExecuted: toolCall.providerExecuted }; break; } case "denied": { toolApprovalRequests[toolCall.toolCallId] = { type: "tool-approval-request", approvalId, toolCall, isAutomatic: true, ...signature != null ? { signature } : {} }; stepToolApprovalResponses[toolCall.toolCallId] = { type: "tool-approval-response", approvalId, toolCall, approved: false, reason: toolApprovalStatus.reason, providerExecuted: toolCall.providerExecuted }; blockedToolCallIds.add(toolCall.toolCallId); break; } } } 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: getErrorMessage(toolCall.error), dynamic: true }); } clientToolCalls = stepToolCalls.filter( (toolCall) => !toolCall.providerExecuted ); toolApprovalResponses = Object.values(stepToolApprovalResponses); deniedToolApprovalResponses = toolApprovalResponses.filter( (toolApprovalResponse) => toolApprovalResponse.approved === false ); const toolExecutionMs = {}; if (tools2 != null) { const toolExecutionResults = await executeTools({ toolCalls: clientToolCalls.filter( (toolCall) => !toolCall.invalid && !blockedToolCallIds.has(toolCall.toolCallId) ), tools: tools2, callId, messages: stepMessages, abortSignal: mergedAbortSignal, timeout, experimental_sandbox: stepSandbox, toolsContext, onToolExecutionStart: (event) => notify({ event, callbacks: [ resolvedOnToolExecutionStart, telemetryDispatcher.onToolExecutionStart ] }), onToolExecutionEnd: (event) => notify({ event, callbacks: [ resolvedOnToolExecutionEnd, telemetryDispatcher.onToolExecutionEnd ] }), executeToolInTelemetryContext: telemetryDispatcher.executeTool, runInTracingChannelSpan }); for (const result of toolExecutionResults) { toolExecutionMs[result.output.toolCallId] = result.toolExecutionMs; clientToolOutputs.push(result.output); } } const stepTimeMs = now2() - stepStartTimestampMs; const stepPerformance = { effectiveOutputTokensPerSecond: calculateTokensPerSecond({ tokens: stepUsage.outputTokens, durationMs: responseTimeMs }), outputTokensPerSecond: void 0, inputTokensPerSecond: void 0, effectiveTotalTokensPerSecond: calculateTokensPerSecond({ tokens: sumTokenCounts( stepUsage.inputTokens, stepUsage.outputTokens ), durationMs: responseTimeMs }), stepTimeMs, responseTimeMs, toolExecutionMs, timeToFirstOutputMs: void 0 }; for (const toolCall of stepToolCalls) { if (!toolCall.providerExecuted) continue; const tool2 = getOwn(tools2, toolCall.toolName); if ((tool2 == null ? void 0 : tool2.type) === "provider" && tool2.supportsDeferredResults) { const hasResultInResponse = currentModelResponse.content.some( (part) => part.type === "tool-result" && part.toolCallId === toolCall.toolCallId ); if (!hasResultInResponse) { pendingDeferredToolCalls.set(toolCall.toolCallId, { toolName: toolCall.toolName }); } } } for (const part of currentModelResponse.content) { if (part.type === "tool-result") { pendingDeferredToolCalls.delete(part.toolCallId); } } const stepContent = asContent({ content: currentModelResponse.content, toolCalls: stepToolCalls, toolOutputs: clientToolOutputs, toolApprovalRequests: Object.values(toolApprovalRequests), toolApprovalResponses, tools: tools2 }); const stepResponseMessages = await toResponseMessages({ content: stepContent, tools: tools2 }); const stepRequest = { ...currentModelResponse.request, body: include.requestBody ? (_o = currentModelResponse.request) == null ? void 0 : _o.body : void 0, messages: include.requestMessages ? cloneModelMessages(stepMessages) : void 0 }; const stepResponse = { ...currentModelResponse.response, // deep clone msgs to avoid mutating step results in multi-step: messages: cloneModelMessages(stepResponseMessages), // Conditionally include response body: body: include.responseBody ? (_p = currentModelResponse.response) == null ? void 0 : _p.body : void 0 }; const currentStepResult = new DefaultStepResult({ callId, stepNumber, provider: stepModel.provider, modelId: stepModel.modelId, runtimeContext, content: stepContent, finishReason: currentModelResponse.finishReason.unified, rawFinishReason: currentModelResponse.finishReason.raw, usage: stepUsage, performance: stepPerformance, warnings: currentModelResponse.warnings, providerMetadata: currentModelResponse.providerMetadata, request: stepRequest, response: stepResponse, toolsContext }); logWarnings({ warnings: (_q = currentModelResponse.warnings) != null ? _q : [], provider: stepModel.provider, model: stepModel.modelId }); steps.push(currentStepResult); instructionsForNextStep = stepInstructions; messagesForNextStep = [...stepMessages, ...stepResponseMessages]; await notify({ event: currentStepResult, callbacks: [resolvedOnStepEnd, telemetryDispatcher.onStepEnd] }); return currentStepResult; } }); } finally { if (stepTimeoutId != null) { clearTimeout(stepTimeoutId); } } } while ( // Continue if: // 1. There are client tool calls that have all been executed or denied, OR // 2. There are pending deferred results from provider-executed tools (clientToolCalls.length > 0 && clientToolOutputs.length + deniedToolApprovalResponses.length === clientToolCalls.length || pendingDeferredToolCalls.size > 0) && // continue until a stop condition is met: !await isStopConditionMet({ stopConditions, steps }) ); const lastStep = steps[steps.length - 1]; const totalUsage = steps.reduce( (totalUsage2, step) => { return addLanguageModelUsage(totalUsage2, step.usage); }, { inputTokens: void 0, inputTokenDetails: { noCacheTokens: void 0, cacheReadTokens: void 0, cacheWriteTokens: void 0 }, outputTokens: void 0, outputTokenDetails: { textTokens: void 0, reasoningTokens: void 0 }, totalTokens: void 0 } ); const files = steps.flatMap((step) => step.files); const sources = steps.flatMap((step) => step.sources); const toolCalls = steps.flatMap((step) => step.toolCalls); const staticToolCalls = steps.flatMap((step) => step.staticToolCalls); const dynamicToolCalls = steps.flatMap((step) => step.dynamicToolCalls); const toolResults = steps.flatMap((step) => step.toolResults); const staticToolResults = steps.flatMap((step) => step.staticToolResults); const dynamicToolResults = steps.flatMap((step) => step.dynamicToolResults); const warnings = steps.flatMap((step) => { var _a242; return (_a242 = step.warnings) != null ? _a242 : []; }); const onEndEvent = { callId, stepNumber: lastStep.stepNumber, model: lastStep.model, runtimeContext: lastStep.runtimeContext, finishReason: lastStep.finishReason, rawFinishReason: lastStep.rawFinishReason, usage: totalUsage, totalUsage, content: steps.flatMap((step) => step.content), text: lastStep.text, reasoning: lastStep.reasoning, reasoningText: lastStep.reasoningText, files, sources, toolCalls, staticToolCalls, dynamicToolCalls, toolResults, staticToolResults, dynamicToolResults, responseMessages: [ ...initialResponseMessages, ...steps.flatMap((step) => step.response.messages) ], warnings, request: lastStep.request, response: lastStep.response, providerMetadata: lastStep.providerMetadata, steps, finalStep: lastStep, toolsContext }; await notify({ event: onEndEvent, callbacks: [onEnd, telemetryDispatcher.onEnd] }); let resolvedOutput; if (lastStep.finishReason === "stop") { const outputSpecification = output != null ? output : text(); resolvedOutput = await outputSpecification.parseCompleteOutput( { text: lastStep.text }, { response: lastStep.response, usage: lastStep.usage, finishReason: lastStep.finishReason } ); } return new DefaultGenerateTextResult({ initialResponseMessages, steps, totalUsage, output: resolvedOutput }); } catch (error40) { await ((_a232 = telemetryDispatcher.onError) == null ? void 0 : _a232.call(telemetryDispatcher, { callId, error: error40 })); throw wrapGatewayError(error40); } }; return await runInTracingChannelSpan({ type: "generateText", event: generateTextStartEvent, execute: executeGenerateText }); } async function executeTools({ toolCalls, tools: tools2, callId, messages, abortSignal, timeout, experimental_sandbox: sandbox, toolsContext, onToolExecutionStart, onToolExecutionEnd, executeToolInTelemetryContext, runInTracingChannelSpan }) { const toolResults = await Promise.all( toolCalls.map( async (toolCall) => await executeToolCall({ toolCall, tools: tools2, callId, messages, abortSignal, timeout, experimental_sandbox: sandbox, toolsContext, onToolExecutionStart, onToolExecutionEnd, executeToolInTelemetryContext, runInTracingChannelSpan }) ) ); return toolResults.filter( (result) => result != null ); } var DefaultGenerateTextResult = class { constructor(options) { this.initialResponseMessages = options.initialResponseMessages; this.steps = options.steps; this._output = options.output; this.totalUsage = options.totalUsage; } get finalStep() { return this.steps.at(-1); } get content() { return this.steps.flatMap((step) => step.content); } get text() { return this.finalStep.text; } get files() { return this.steps.flatMap((step) => step.files); } get reasoningText() { return this.finalStep.reasoningText; } get reasoning() { return convertToReasoningOutputs(this.finalStep.reasoning); } get toolCalls() { return this.steps.flatMap((step) => step.toolCalls); } get staticToolCalls() { return this.steps.flatMap((step) => step.staticToolCalls); } get dynamicToolCalls() { return this.steps.flatMap((step) => step.dynamicToolCalls); } get toolResults() { return this.steps.flatMap((step) => step.toolResults); } get staticToolResults() { return this.steps.flatMap((step) => step.staticToolResults); } get dynamicToolResults() { return this.steps.flatMap((step) => step.dynamicToolResults); } get sources() { return this.steps.flatMap((step) => step.sources); } get finishReason() { return this.finalStep.finishReason; } get rawFinishReason() { return this.finalStep.rawFinishReason; } get warnings() { return this.steps.flatMap((step) => { var _a222; return (_a222 = step.warnings) != null ? _a222 : []; }); } get providerMetadata() { return this.finalStep.providerMetadata; } get response() { return this.finalStep.response; } get responseMessages() { return [ ...this.initialResponseMessages, ...this.steps.flatMap((step) => step.response.messages) ]; } get request() { return this.finalStep.request; } get usage() { return this.totalUsage; } get output() { if (this._output == null) { throw new NoOutputGeneratedError(); } return this._output; } }; function asContent({ content, toolCalls, toolOutputs, toolApprovalRequests, toolApprovalResponses, tools: tools2 }) { const contentParts = []; const toolOutputsWithApprovalResponses = []; const toolOutputsWithoutApprovalResponses = []; const toolCallIdsWithApprovalResponses = new Set( toolApprovalResponses.map( (toolApprovalResponse) => toolApprovalResponse.toolCall.toolCallId ) ); for (const part of content) { switch (part.type) { case "text": case "reasoning": case "custom": case "source": contentParts.push(part); break; case "file": case "reasoning-file": { contentParts.push({ type: part.type, file: new DefaultGeneratedFile({ data: part.data.type === "data" ? part.data.data : part.data.url.toString(), mediaType: part.mediaType }), ...part.providerMetadata != null ? { 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 (toolCall == null) { const tool2 = getOwn(tools2, part.toolName); const supportsDeferredResults = (tool2 == null ? 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, ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}, ...(tool2 == null ? void 0 : tool2.metadata) != null ? { toolMetadata: tool2.metadata } : {} }); } else { contentParts.push({ type: "tool-result", toolCallId: part.toolCallId, toolName: part.toolName, input: void 0, output: part.result, providerExecuted: true, dynamic: part.dynamic, ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}, ...(tool2 == null ? void 0 : tool2.metadata) != null ? { toolMetadata: tool2.metadata } : {} }); } 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, ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}, ...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {} }); } else { contentParts.push({ type: "tool-result", toolCallId: part.toolCallId, toolName: part.toolName, input: toolCall.input, output: part.result, providerExecuted: true, dynamic: toolCall.dynamic, ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}, ...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {} }); } break; } case "tool-approval-request": { const toolCall = toolCalls.find( (toolCall2) => toolCall2.toolCallId === part.toolCallId ); if (toolCall == null) { throw new ToolCallNotFoundForApprovalError({ toolCallId: part.toolCallId, approvalId: part.approvalId }); } contentParts.push({ type: "tool-approval-request", approvalId: part.approvalId, toolCall }); break; } } } for (const toolOutput of toolOutputs) { if (toolCallIdsWithApprovalResponses.has(toolOutput.toolCallId)) { toolOutputsWithApprovalResponses.push(toolOutput); } else { toolOutputsWithoutApprovalResponses.push(toolOutput); } } return [ ...contentParts, ...toolOutputsWithoutApprovalResponses, ...toolApprovalRequests, ...toolApprovalResponses, ...toolOutputsWithApprovalResponses ]; } var JsonToSseTransformStream = class extends TransformStream { constructor() { super({ transform(part, controller) { controller.enqueue(`data: ${JSON.stringify(part)} `); }, flush(controller) { controller.enqueue("data: [DONE]\n\n"); } }); } }; var toolMetadataSchema = external_exports.record( external_exports.string(), jsonValueSchema.optional() ); var uiMessageChunkSchema = lazySchema( () => zodSchema( external_exports.union([ external_exports.strictObject({ type: external_exports.literal("text-start"), id: external_exports.string(), providerMetadata: providerMetadataSchema.optional() }), external_exports.strictObject({ type: external_exports.literal("text-delta"), id: external_exports.string(), delta: external_exports.string(), providerMetadata: providerMetadataSchema.optional() }), external_exports.strictObject({ type: external_exports.literal("text-end"), id: external_exports.string(), providerMetadata: providerMetadataSchema.optional() }), external_exports.strictObject({ type: external_exports.literal("error"), errorText: external_exports.string() }), external_exports.strictObject({ type: external_exports.literal("tool-input-start"), toolCallId: external_exports.string(), toolName: external_exports.string(), providerExecuted: external_exports.boolean().optional(), providerMetadata: providerMetadataSchema.optional(), toolMetadata: toolMetadataSchema.optional(), dynamic: external_exports.boolean().optional(), title: external_exports.string().optional() }), external_exports.strictObject({ type: external_exports.literal("tool-input-delta"), toolCallId: external_exports.string(), inputTextDelta: external_exports.string() }), external_exports.strictObject({ type: external_exports.literal("tool-input-available"), toolCallId: external_exports.string(), toolName: external_exports.string(), input: external_exports.unknown(), providerExecuted: external_exports.boolean().optional(), providerMetadata: providerMetadataSchema.optional(), toolMetadata: toolMetadataSchema.optional(), dynamic: external_exports.boolean().optional(), title: external_exports.string().optional() }), external_exports.strictObject({ type: external_exports.literal("tool-input-error"), toolCallId: external_exports.string(), toolName: external_exports.string(), input: external_exports.unknown(), providerExecuted: external_exports.boolean().optional(), providerMetadata: providerMetadataSchema.optional(), toolMetadata: toolMetadataSchema.optional(), dynamic: external_exports.boolean().optional(), errorText: external_exports.string(), title: external_exports.string().optional() }), external_exports.strictObject({ type: external_exports.literal("tool-approval-request"), approvalId: external_exports.string(), toolCallId: external_exports.string(), isAutomatic: external_exports.boolean().optional(), signature: external_exports.string().optional() }), external_exports.strictObject({ type: external_exports.literal("tool-approval-response"), approvalId: external_exports.string(), approved: external_exports.boolean(), reason: external_exports.string().optional(), providerExecuted: external_exports.boolean().optional(), providerMetadata: providerMetadataSchema.optional() }), external_exports.strictObject({ type: external_exports.literal("tool-output-available"), toolCallId: external_exports.string(), output: external_exports.unknown(), providerExecuted: external_exports.boolean().optional(), providerMetadata: providerMetadataSchema.optional(), toolMetadata: toolMetadataSchema.optional(), dynamic: external_exports.boolean().optional(), preliminary: external_exports.boolean().optional() }), external_exports.strictObject({ type: external_exports.literal("tool-output-error"), toolCallId: external_exports.string(), errorText: external_exports.string(), providerExecuted: external_exports.boolean().optional(), providerMetadata: providerMetadataSchema.optional(), toolMetadata: toolMetadataSchema.optional(), dynamic: external_exports.boolean().optional() }), external_exports.strictObject({ type: external_exports.literal("tool-output-denied"), toolCallId: external_exports.string() }), external_exports.strictObject({ type: external_exports.literal("reasoning-start"), id: external_exports.string(), providerMetadata: providerMetadataSchema.optional() }), external_exports.strictObject({ type: external_exports.literal("reasoning-delta"), id: external_exports.string(), delta: external_exports.string(), providerMetadata: providerMetadataSchema.optional() }), external_exports.strictObject({ type: external_exports.literal("reasoning-end"), id: external_exports.string(), providerMetadata: providerMetadataSchema.optional() }), external_exports.strictObject({ type: external_exports.literal("custom"), kind: external_exports.string().transform((value) => value), providerMetadata: providerMetadataSchema.optional() }), external_exports.strictObject({ type: external_exports.literal("source-url"), sourceId: external_exports.string(), url: external_exports.string(), title: external_exports.string().optional(), providerMetadata: providerMetadataSchema.optional() }), external_exports.strictObject({ type: external_exports.literal("source-document"), sourceId: external_exports.string(), mediaType: external_exports.string(), title: external_exports.string(), filename: external_exports.string().optional(), providerMetadata: providerMetadataSchema.optional() }), external_exports.strictObject({ type: external_exports.literal("file"), url: external_exports.string(), mediaType: external_exports.string(), providerMetadata: providerMetadataSchema.optional() }), external_exports.strictObject({ type: external_exports.literal("reasoning-file"), url: external_exports.string(), mediaType: external_exports.string(), providerMetadata: providerMetadataSchema.optional() }), external_exports.strictObject({ type: external_exports.custom( (value) => typeof value === "string" && value.startsWith("data-"), { message: 'Type must start with "data-"' } ), id: external_exports.string().optional(), data: external_exports.unknown(), transient: external_exports.boolean().optional() }), external_exports.strictObject({ type: external_exports.literal("start-step") }), external_exports.strictObject({ type: external_exports.literal("finish-step") }), external_exports.strictObject({ type: external_exports.literal("start"), messageId: external_exports.string().optional(), messageMetadata: external_exports.unknown().optional() }), external_exports.strictObject({ type: external_exports.literal("finish"), finishReason: external_exports.enum([ "stop", "length", "content-filter", "tool-calls", "error", "other" ]).optional(), messageMetadata: external_exports.unknown().optional() }), external_exports.strictObject({ type: external_exports.literal("abort"), reason: external_exports.string().optional() }), external_exports.strictObject({ type: external_exports.literal("message-metadata"), messageMetadata: external_exports.unknown() }) ]) ) ); var originalGenerateId2 = createIdGenerator({ prefix: "aitxt", size: 24 }); var originalGenerateCallId2 = createIdGenerator({ prefix: "call", size: 24 }); var originalGenerateId3 = createIdGenerator({ prefix: "aitxt", size: 24 }); var originalGenerateCallId3 = createIdGenerator({ prefix: "call", size: 24 }); var toolMetadataSchema2 = external_exports.record( external_exports.string(), jsonValueSchema.optional() ); var providerReferenceSchema2 = external_exports.record(external_exports.string(), external_exports.string()); var uiMessagesSchema = lazySchema( () => zodSchema( external_exports.array( external_exports.object({ id: external_exports.string(), role: external_exports.enum(["system", "user", "assistant"]), metadata: external_exports.unknown().optional(), parts: external_exports.array( external_exports.union([ external_exports.object({ type: external_exports.literal("text"), text: external_exports.string(), state: external_exports.enum(["streaming", "done"]).optional(), providerMetadata: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("reasoning"), text: external_exports.string(), state: external_exports.enum(["streaming", "done"]).optional(), providerMetadata: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("custom"), kind: external_exports.string(), providerMetadata: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("source-url"), sourceId: external_exports.string(), url: external_exports.string(), title: external_exports.string().optional(), providerMetadata: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("source-document"), sourceId: external_exports.string(), mediaType: external_exports.string(), title: external_exports.string(), filename: external_exports.string().optional(), providerMetadata: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("file"), mediaType: external_exports.string(), filename: external_exports.string().optional(), url: external_exports.string(), providerReference: providerReferenceSchema2.optional(), providerMetadata: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("reasoning-file"), mediaType: external_exports.string(), url: external_exports.string(), providerMetadata: providerMetadataSchema.optional() }), external_exports.object({ type: external_exports.literal("step-start") }), external_exports.object({ type: external_exports.string().startsWith("data-"), id: external_exports.string().optional(), data: external_exports.unknown() }), external_exports.object({ type: external_exports.literal("dynamic-tool"), toolName: external_exports.string(), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("input-streaming"), input: external_exports.unknown().optional(), providerExecuted: external_exports.boolean().optional(), callProviderMetadata: providerMetadataSchema.optional(), output: external_exports.never().optional(), errorText: external_exports.never().optional(), approval: external_exports.never().optional() }), external_exports.object({ type: external_exports.literal("dynamic-tool"), toolName: external_exports.string(), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("input-available"), input: external_exports.unknown(), providerExecuted: external_exports.boolean().optional(), output: external_exports.never().optional(), errorText: external_exports.never().optional(), callProviderMetadata: providerMetadataSchema.optional(), approval: external_exports.never().optional() }), external_exports.object({ type: external_exports.literal("dynamic-tool"), toolName: external_exports.string(), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("approval-requested"), input: external_exports.unknown(), providerExecuted: external_exports.boolean().optional(), output: external_exports.never().optional(), errorText: external_exports.never().optional(), callProviderMetadata: providerMetadataSchema.optional(), approval: external_exports.object({ id: external_exports.string(), approved: external_exports.never().optional(), reason: external_exports.never().optional(), isAutomatic: external_exports.boolean().optional(), signature: external_exports.string().optional() }) }), external_exports.object({ type: external_exports.literal("dynamic-tool"), toolName: external_exports.string(), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("approval-responded"), input: external_exports.unknown(), providerExecuted: external_exports.boolean().optional(), output: external_exports.never().optional(), errorText: external_exports.never().optional(), callProviderMetadata: providerMetadataSchema.optional(), approval: external_exports.object({ id: external_exports.string(), approved: external_exports.boolean(), reason: external_exports.string().optional(), isAutomatic: external_exports.boolean().optional(), signature: external_exports.string().optional() }) }), external_exports.object({ type: external_exports.literal("dynamic-tool"), toolName: external_exports.string(), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("output-available"), input: external_exports.unknown(), providerExecuted: external_exports.boolean().optional(), output: external_exports.unknown(), errorText: external_exports.never().optional(), callProviderMetadata: providerMetadataSchema.optional(), resultProviderMetadata: providerMetadataSchema.optional(), preliminary: external_exports.boolean().optional(), approval: external_exports.object({ id: external_exports.string(), approved: external_exports.literal(true), reason: external_exports.string().optional(), isAutomatic: external_exports.boolean().optional(), signature: external_exports.string().optional() }).optional() }), external_exports.object({ type: external_exports.literal("dynamic-tool"), toolName: external_exports.string(), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("output-error"), input: external_exports.unknown().optional(), rawInput: external_exports.unknown().optional(), providerExecuted: external_exports.boolean().optional(), output: external_exports.never().optional(), errorText: external_exports.string(), callProviderMetadata: providerMetadataSchema.optional(), resultProviderMetadata: providerMetadataSchema.optional(), approval: external_exports.object({ id: external_exports.string(), approved: external_exports.literal(true), reason: external_exports.string().optional(), isAutomatic: external_exports.boolean().optional(), signature: external_exports.string().optional() }).optional() }), external_exports.object({ type: external_exports.literal("dynamic-tool"), toolName: external_exports.string(), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("output-denied"), input: external_exports.unknown(), providerExecuted: external_exports.boolean().optional(), output: external_exports.never().optional(), errorText: external_exports.never().optional(), callProviderMetadata: providerMetadataSchema.optional(), approval: external_exports.object({ id: external_exports.string(), approved: external_exports.literal(false), reason: external_exports.string().optional(), isAutomatic: external_exports.boolean().optional(), signature: external_exports.string().optional() }) }), external_exports.object({ type: external_exports.string().startsWith("tool-"), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("input-streaming"), providerExecuted: external_exports.boolean().optional(), callProviderMetadata: providerMetadataSchema.optional(), input: external_exports.unknown().optional(), output: external_exports.never().optional(), errorText: external_exports.never().optional(), approval: external_exports.never().optional() }), external_exports.object({ type: external_exports.string().startsWith("tool-"), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("input-available"), providerExecuted: external_exports.boolean().optional(), input: external_exports.unknown(), output: external_exports.never().optional(), errorText: external_exports.never().optional(), callProviderMetadata: providerMetadataSchema.optional(), approval: external_exports.never().optional() }), external_exports.object({ type: external_exports.string().startsWith("tool-"), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("approval-requested"), input: external_exports.unknown(), providerExecuted: external_exports.boolean().optional(), output: external_exports.never().optional(), errorText: external_exports.never().optional(), callProviderMetadata: providerMetadataSchema.optional(), approval: external_exports.object({ id: external_exports.string(), approved: external_exports.never().optional(), reason: external_exports.never().optional(), isAutomatic: external_exports.boolean().optional(), signature: external_exports.string().optional() }) }), external_exports.object({ type: external_exports.string().startsWith("tool-"), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("approval-responded"), input: external_exports.unknown(), providerExecuted: external_exports.boolean().optional(), output: external_exports.never().optional(), errorText: external_exports.never().optional(), callProviderMetadata: providerMetadataSchema.optional(), approval: external_exports.object({ id: external_exports.string(), approved: external_exports.boolean(), reason: external_exports.string().optional(), isAutomatic: external_exports.boolean().optional(), signature: external_exports.string().optional() }) }), external_exports.object({ type: external_exports.string().startsWith("tool-"), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("output-available"), providerExecuted: external_exports.boolean().optional(), input: external_exports.unknown(), output: external_exports.unknown(), errorText: external_exports.never().optional(), callProviderMetadata: providerMetadataSchema.optional(), resultProviderMetadata: providerMetadataSchema.optional(), preliminary: external_exports.boolean().optional(), approval: external_exports.object({ id: external_exports.string(), approved: external_exports.literal(true), reason: external_exports.string().optional(), isAutomatic: external_exports.boolean().optional(), signature: external_exports.string().optional() }).optional() }), external_exports.object({ type: external_exports.string().startsWith("tool-"), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("output-error"), providerExecuted: external_exports.boolean().optional(), input: external_exports.unknown().optional(), rawInput: external_exports.unknown().optional(), output: external_exports.never().optional(), errorText: external_exports.string(), callProviderMetadata: providerMetadataSchema.optional(), resultProviderMetadata: providerMetadataSchema.optional(), approval: external_exports.object({ id: external_exports.string(), approved: external_exports.literal(true), reason: external_exports.string().optional(), isAutomatic: external_exports.boolean().optional(), signature: external_exports.string().optional() }).optional() }), external_exports.object({ type: external_exports.string().startsWith("tool-"), toolCallId: external_exports.string(), toolMetadata: toolMetadataSchema2.optional(), state: external_exports.literal("output-denied"), providerExecuted: external_exports.boolean().optional(), input: external_exports.unknown(), output: external_exports.never().optional(), errorText: external_exports.never().optional(), callProviderMetadata: providerMetadataSchema.optional(), approval: external_exports.object({ id: external_exports.string(), approved: external_exports.literal(false), reason: external_exports.string().optional(), isAutomatic: external_exports.boolean().optional(), signature: external_exports.string().optional() }) }) ]) ) }).superRefine((message, context) => { if (message.role !== "assistant" && message.parts.length === 0) { context.addIssue({ origin: "array", code: "too_small", minimum: 1, inclusive: true, input: message.parts, path: ["parts"], message: "Message must contain at least one part" }); } }) ).nonempty("Messages array must not be empty") ) ); var originalGenerateCallId4 = createIdGenerator({ prefix: "call", size: 24 }); var originalGenerateCallId5 = createIdGenerator({ prefix: "call", size: 24 }); var originalGenerateId4 = createIdGenerator({ prefix: "aiobj", size: 24 }); function createDownload(options) { return ({ url: url2, abortSignal }) => download({ url: url2, maxBytes: options == null ? void 0 : options.maxBytes, abortSignal }); } var originalGenerateId5 = createIdGenerator({ prefix: "aiobj", size: 24 }); var defaultDownload = createDownload(); var name21 = "AI_NoSuchProviderError"; var marker21 = `vercel.ai.error.${name21}`; var symbol21 = Symbol.for(marker21); var _a21; _a21 = symbol21; var originalGenerateCallId6 = createIdGenerator({ prefix: "call", size: 24 }); var defaultDownload2 = createDownload(); // node_modules/@ai-sdk/openai/dist/index.js var openaiErrorDataSchema = external_exports.object({ error: external_exports.object({ message: external_exports.string(), // The additional information below is handled loosely to support // OpenAI-compatible providers that have slightly different error // responses: type: external_exports.string().nullish(), param: external_exports.any().nullish(), code: external_exports.union([external_exports.string(), external_exports.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") || modelId.startsWith("gpt-5.5") || modelId.startsWith("gpt-5.6"); const systemMessageMode = isReasoningModel ? "developer" : "system"; return { supportsFlexProcessing, supportsPriorityProcessing, isReasoningModel, systemMessageMode, supportsNonReasoningParameters }; } async function throwIfOpenAIStreamErrorBeforeOutput({ stream, getError, isOutputChunk, url: url2, requestBodyValues, responseHeaders }) { const [streamForEarlyError, streamForConsumer] = stream.tee(); const reader = streamForEarlyError.getReader(); try { while (true) { const result = await reader.read(); if (result.done) { return streamForConsumer; } const chunk = result.value; if (!chunk.success) { return streamForConsumer; } const errorFrame = getError(chunk.value); if (errorFrame != null) { streamForConsumer.cancel().catch(() => { }); throw createOpenAIStreamError({ frame: errorFrame, url: url2, requestBodyValues, responseHeaders }); } if (isOutputChunk(chunk.value)) { return streamForConsumer; } } } finally { reader.cancel().catch(() => { }); reader.releaseLock(); } } function createOpenAIStreamError({ frame, url: url2, requestBodyValues, responseHeaders }) { var _a25; const streamError = parseStreamError(frame); return new APICallError({ message: (_a25 = streamError == null ? void 0 : streamError.message) != null ? _a25 : "OpenAI stream failed before any output was generated", url: url2, requestBodyValues, statusCode: streamError == null ? 500 : getStatusCode(streamError), responseHeaders, responseBody: JSON.stringify(frame), data: frame }); } function parseStreamError(frame) { var _a25; const value = asRecord(frame); if (value == null) { return void 0; } if (value.type === "response.failed") { const response = asRecord(value.response); const responseError = asRecord(response == null ? void 0 : response.error); return typeof (responseError == null ? void 0 : responseError.message) === "string" ? { message: responseError.message, code: getStringOrNumber(responseError.code), type: "response.failed", frame } : void 0; } const error40 = (_a25 = asRecord(value.error)) != null ? _a25 : value; return typeof error40.message === "string" && (asRecord(value.error) != null || typeof error40.type === "string" || "code" in error40 || "param" in error40) ? { message: error40.message, code: getStringOrNumber(error40.code), type: typeof error40.type === "string" ? error40.type : void 0, frame } : void 0; } function getStatusCode(error40) { if (typeof error40.code === "number" && isHttpErrorStatusCode(error40.code)) { return error40.code; } if (typeof error40.code === "string" && /^\d{3}$/.test(error40.code)) { const numericCode = Number(error40.code); if (isHttpErrorStatusCode(numericCode)) { return numericCode; } } const discriminator = [error40.code, error40.type].filter((value) => typeof value === "string" || typeof value === "number").join(" ").toLowerCase(); if (["insufficient_quota", "rate_limit"].some( (term) => discriminator.includes(term) )) { return 429; } if (discriminator.includes("authentication")) return 401; if (discriminator.includes("permission")) return 403; if (discriminator.includes("not_found")) return 404; if (["invalid", "bad_request", "context_length"].some( (term) => discriminator.includes(term) )) { return 400; } if (discriminator.includes("overload")) return 503; if (discriminator.includes("timeout")) return 504; return 500; } function asRecord(value) { return typeof value === "object" && value != null ? value : void 0; } function getStringOrNumber(value) { return typeof value === "string" || typeof value === "number" ? value : void 0; } function isHttpErrorStatusCode(value) { return Number.isInteger(value) && value >= 400 && value <= 599; } function convertOpenAIChatUsage(usage) { var _a25, _b19, _c, _d, _e2, _f, _g, _h; if (usage == null) { 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 = (_a25 = usage.prompt_tokens) != null ? _a25 : 0; const completionTokens = (_b19 = usage.completion_tokens) != null ? _b19 : 0; const cachedTokens = (_d = (_c = usage.prompt_tokens_details) == null ? void 0 : _c.cached_tokens) != null ? _d : 0; const cacheWriteTokens = (_f = (_e2 = usage.prompt_tokens_details) == null ? void 0 : _e2.cache_write_tokens) != null ? _f : void 0; const reasoningTokens = (_h = (_g = usage.completion_tokens_details) == null ? void 0 : _g.reasoning_tokens) != null ? _h : 0; return { inputTokens: { total: promptTokens, noCache: promptTokens - cachedTokens - (cacheWriteTokens != null ? cacheWriteTokens : 0), cacheRead: cachedTokens, cacheWrite: cacheWriteTokens }, outputTokens: { total: completionTokens, text: completionTokens - reasoningTokens, reasoning: reasoningTokens }, raw: usage }; } function serializeToolCallArguments(input) { return JSON.stringify(input === void 0 ? {} : input); } function getPromptCacheBreakpoint(providerOptions) { var _a25; return (_a25 = providerOptions == null ? void 0 : providerOptions.openai) == null ? void 0 : _a25.promptCacheBreakpoint; } function convertToOpenAIChatMessages({ prompt, systemMessageMode = "system" }) { var _a25, _b19; const messages = []; const warnings = []; for (const { role, content, providerOptions } of prompt) { switch (role) { case "system": { switch (systemMessageMode) { case "system": { const promptCacheBreakpoint = getPromptCacheBreakpoint(providerOptions); messages.push({ role: "system", content: promptCacheBreakpoint == null ? content : [ { type: "text", text: content, prompt_cache_breakpoint: promptCacheBreakpoint } ] }); break; } case "developer": { const promptCacheBreakpoint = getPromptCacheBreakpoint(providerOptions); messages.push({ role: "developer", content: promptCacheBreakpoint == null ? content : [ { type: "text", text: content, prompt_cache_breakpoint: promptCacheBreakpoint } ] }); 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 (content.length === 1 && content[0].type === "text" && getPromptCacheBreakpoint(content[0].providerOptions) == null) { messages.push({ role: "user", content: content[0].text }); break; } messages.push({ role: "user", content: content.map((part, index) => { var _a26, _b23, _c; switch (part.type) { case "text": { const promptCacheBreakpoint = getPromptCacheBreakpoint( part.providerOptions ); return { type: "text", text: part.text, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } case "file": { const promptCacheBreakpoint = getPromptCacheBreakpoint( part.providerOptions ); switch (part.data.type) { case "reference": { return { type: "file", file: { file_id: resolveProviderReference({ reference: part.data.reference, provider: "openai" }) }, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } case "text": { throw new UnsupportedFunctionalityError({ functionality: "text file parts" }); } case "url": case "data": { const topLevel = getTopLevelMediaType(part.mediaType); if (topLevel === "image") { return { type: "image_url", image_url: { url: part.data.type === "url" ? part.data.url.toString() : `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`, detail: (_b23 = (_a26 = part.providerOptions) == null ? void 0 : _a26.openai) == null ? void 0 : _b23.imageDetail }, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } else if (topLevel === "audio") { if (part.data.type === "url") { throw new UnsupportedFunctionalityError({ functionality: "audio file parts with URLs" }); } const fullMediaType = resolveFullMediaType({ part }); switch (fullMediaType) { case "audio/wav": { return { type: "input_audio", input_audio: { data: convertToBase64(part.data.data), format: "wav" }, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } case "audio/mp3": case "audio/mpeg": { return { type: "input_audio", input_audio: { data: convertToBase64(part.data.data), format: "mp3" }, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } default: { throw new UnsupportedFunctionalityError({ functionality: `audio content parts with media type ${fullMediaType}` }); } } } { const fullMediaType = resolveFullMediaType({ part }); if (fullMediaType !== "application/pdf") { throw new UnsupportedFunctionalityError({ functionality: `file part media type ${fullMediaType}` }); } if (part.data.type === "url") { throw new UnsupportedFunctionalityError({ functionality: "PDF file parts with URLs" }); } return { type: "file", file: { filename: (_c = part.filename) != null ? _c : `part-${index}.pdf`, file_data: `data:application/pdf;base64,${convertToBase64(part.data.data)}` }, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } } } } } }) }); break; } case "assistant": { let text2 = ""; const textParts = []; let hasPromptCacheBreakpoint = false; const toolCalls = []; for (const part of content) { switch (part.type) { case "text": { const promptCacheBreakpoint = getPromptCacheBreakpoint( part.providerOptions ); text2 += part.text; textParts.push({ type: "text", text: part.text, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }); hasPromptCacheBreakpoint || (hasPromptCacheBreakpoint = promptCacheBreakpoint != null); break; } case "tool-call": { toolCalls.push({ id: part.toolCallId, type: "function", function: { name: part.toolName, arguments: serializeToolCallArguments(part.input) } }); break; } } } messages.push({ role: "assistant", content: hasPromptCacheBreakpoint ? textParts : toolCalls.length > 0 ? text2 || null : text2, tool_calls: toolCalls.length > 0 ? toolCalls : void 0 }); break; } case "tool": { for (const toolResponse of content) { if (toolResponse.type === "tool-approval-response") { continue; } const output = toolResponse.output; const promptCacheBreakpoint = (_a25 = output.type === "content" ? output.value.map((part) => getPromptCacheBreakpoint(part.providerOptions)).find((breakpoint) => breakpoint != null) : getPromptCacheBreakpoint(output.providerOptions)) != null ? _a25 : getPromptCacheBreakpoint(toolResponse.providerOptions); let contentValue; switch (output.type) { case "text": case "error-text": contentValue = output.value; break; case "execution-denied": contentValue = (_b19 = output.reason) != null ? _b19 : "Tool call 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: promptCacheBreakpoint == null ? contentValue : [ { type: "text", text: contentValue, prompt_cache_breakpoint: promptCacheBreakpoint } ] }); } break; } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } return { messages, warnings }; } function getResponseMetadata({ id, model, created }) { return { id: id != null ? id : void 0, modelId: model != null ? model : void 0, timestamp: created ? new Date(created * 1e3) : 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 = lazySchema( () => zodSchema( external_exports.object({ id: external_exports.string().nullish(), created: external_exports.number().nullish(), model: external_exports.string().nullish(), choices: external_exports.array( external_exports.object({ message: external_exports.object({ role: external_exports.literal("assistant").nullish(), content: external_exports.string().nullish(), tool_calls: external_exports.array( external_exports.object({ id: external_exports.string().nullish(), type: external_exports.literal("function"), function: external_exports.object({ name: external_exports.string(), arguments: external_exports.string() }) }) ).nullish(), annotations: external_exports.array( external_exports.object({ type: external_exports.literal("url_citation"), url_citation: external_exports.object({ start_index: external_exports.number(), end_index: external_exports.number(), url: external_exports.string(), title: external_exports.string() }) }) ).nullish() }), index: external_exports.number(), logprobs: external_exports.object({ content: external_exports.array( external_exports.object({ token: external_exports.string(), logprob: external_exports.number(), top_logprobs: external_exports.array( external_exports.object({ token: external_exports.string(), logprob: external_exports.number() }) ) }) ).nullish() }).nullish(), finish_reason: external_exports.string().nullish() }) ), usage: external_exports.object({ prompt_tokens: external_exports.number().nullish(), completion_tokens: external_exports.number().nullish(), total_tokens: external_exports.number().nullish(), prompt_tokens_details: external_exports.object({ cached_tokens: external_exports.number().nullish(), cache_write_tokens: external_exports.number().nullish() }).nullish(), completion_tokens_details: external_exports.object({ reasoning_tokens: external_exports.number().nullish(), accepted_prediction_tokens: external_exports.number().nullish(), rejected_prediction_tokens: external_exports.number().nullish() }).nullish() }).nullish() }) ) ); var openaiChatChunkSchema = lazySchema( () => zodSchema( external_exports.union([ external_exports.object({ id: external_exports.string().nullish(), created: external_exports.number().nullish(), model: external_exports.string().nullish(), choices: external_exports.array( external_exports.object({ delta: external_exports.object({ role: external_exports.enum(["assistant"]).nullish(), content: external_exports.string().nullish(), tool_calls: external_exports.array( external_exports.object({ index: external_exports.number(), id: external_exports.string().nullish(), type: external_exports.literal("function").nullish(), function: external_exports.object({ name: external_exports.string().nullish(), arguments: external_exports.string().nullish() }) }) ).nullish(), annotations: external_exports.array( external_exports.object({ type: external_exports.literal("url_citation"), url_citation: external_exports.object({ start_index: external_exports.number(), end_index: external_exports.number(), url: external_exports.string(), title: external_exports.string() }) }) ).nullish() }).nullish(), logprobs: external_exports.object({ content: external_exports.array( external_exports.object({ token: external_exports.string(), logprob: external_exports.number(), top_logprobs: external_exports.array( external_exports.object({ token: external_exports.string(), logprob: external_exports.number() }) ) }) ).nullish() }).nullish(), finish_reason: external_exports.string().nullish(), index: external_exports.number() }) ), usage: external_exports.object({ prompt_tokens: external_exports.number().nullish(), completion_tokens: external_exports.number().nullish(), total_tokens: external_exports.number().nullish(), prompt_tokens_details: external_exports.object({ cached_tokens: external_exports.number().nullish(), cache_write_tokens: external_exports.number().nullish() }).nullish(), completion_tokens_details: external_exports.object({ reasoning_tokens: external_exports.number().nullish(), accepted_prediction_tokens: external_exports.number().nullish(), rejected_prediction_tokens: external_exports.number().nullish() }).nullish() }).nullish() }), openaiErrorDataSchema ]) ) ); var openaiLanguageModelChatOptions = lazySchema( () => zodSchema( external_exports.object({ /** * Modify the likelihood of specified tokens appearing in the completion. * * Accepts a JSON object that maps tokens (specified by their token ID in * the GPT tokenizer) to an associated bias value from -100 to 100. */ logitBias: external_exports.record(external_exports.coerce.number(), external_exports.number()).optional(), /** * Return the log probabilities of the tokens. * * Setting to true will return the log probabilities of the tokens that * were generated. * * Setting to a number will return the log probabilities of the top n * tokens that were generated. */ logprobs: external_exports.union([external_exports.boolean(), external_exports.number()]).optional(), /** * Whether to enable parallel function calling during tool use. Default to true. */ parallelToolCalls: external_exports.boolean().optional(), /** * A unique identifier representing your end-user, which can help OpenAI to * monitor and detect abuse. */ user: external_exports.string().optional(), /** * Reasoning effort for reasoning models. Defaults to `medium`. */ reasoningEffort: external_exports.enum(["none", "minimal", "low", "medium", "high", "xhigh", "max"]).optional(), /** * Maximum number of completion tokens to generate. Useful for reasoning models. */ maxCompletionTokens: external_exports.number().optional(), /** * Whether to enable persistence in responses API. */ store: external_exports.boolean().optional(), /** * Metadata to associate with the request. */ metadata: external_exports.record(external_exports.string().max(64), external_exports.string().max(512)).optional(), /** * Parameters for prediction mode. */ prediction: external_exports.record(external_exports.string(), external_exports.any()).optional(), /** * Service tier for the request. * - 'auto': Default service tier. The request will be processed with the service tier configured in the * Project settings. Unless otherwise configured, the Project will use 'default'. * - 'flex': 50% cheaper processing at the cost of increased latency. Only available for o3 and o4-mini models. * - 'priority': Higher-speed processing with predictably low latency at premium cost. Available for Enterprise customers. * - 'default': The request will be processed with the standard pricing and performance for the selected model. * * @default 'auto' */ serviceTier: external_exports.enum(["auto", "flex", "priority", "default"]).optional(), /** * Whether to use strict JSON schema validation. * * @default true */ strictJsonSchema: external_exports.boolean().optional(), /** * Controls the verbosity of the model's responses. * Lower values will result in more concise responses, while higher values will result in more verbose responses. */ textVerbosity: external_exports.enum(["low", "medium", "high"]).optional(), /** * A cache key for prompt caching. Allows manual control over prompt caching behavior. * Useful for improving cache hit rates and working around automatic caching issues. */ promptCacheKey: external_exports.string().optional(), /** * Prompt cache behavior for GPT-5.6 and later models. * `mode` controls whether OpenAI also places an implicit breakpoint. * `ttl` sets the minimum cache lifetime and currently only supports 30 minutes. */ promptCacheOptions: external_exports.object({ mode: external_exports.enum(["implicit", "explicit"]).optional(), ttl: external_exports.literal("30m").optional() }).optional(), /** * The retention policy for the prompt cache. * - 'in_memory': Default. Standard prompt caching behavior. * - '24h': Extended prompt caching that keeps cached prefixes active for up to 24 hours. * Available for models before GPT-5.6 that support extended caching. * * @deprecated For GPT-5.6 and later models, use `promptCacheOptions.ttl`. * * @default 'in_memory' */ promptCacheRetention: external_exports.enum(["in_memory", "24h"]).optional(), /** * A stable identifier used to help detect users of your application * that may be violating OpenAI's usage policies. The IDs should be a * string that uniquely identifies each user. We recommend hashing their * username or email address, in order to avoid sending us any identifying * information. */ safetyIdentifier: external_exports.string().optional(), /** * Override the system message mode for this model. * - 'system': Use the 'system' role for system messages (default for most models) * - 'developer': Use the 'developer' role for system messages (used by reasoning models) * - 'remove': Remove system messages entirely * * If not specified, the mode is automatically determined based on the model. */ systemMessageMode: external_exports.enum(["system", "developer", "remove"]).optional(), /** * Force treating this model as a reasoning model. * * This is useful for "stealth" reasoning models (e.g. via a custom baseURL) * where the model ID is not recognized by the SDK's allowlist. * * When enabled, the SDK applies reasoning-model parameter compatibility rules * and defaults `systemMessageMode` to `developer` unless overridden. */ forceReasoning: external_exports.boolean().optional() }) ) ); function prepareChatTools({ tools: tools2, toolChoice }) { tools2 = (tools2 == null ? void 0 : tools2.length) ? tools2 : void 0; const toolWarnings = []; if (tools2 == null) { return { tools: void 0, toolChoice: void 0, toolWarnings }; } const openaiTools2 = []; for (const tool2 of tools2) { switch (tool2.type) { case "function": openaiTools2.push({ type: "function", function: { name: tool2.name, description: tool2.description, parameters: tool2.inputSchema, ...tool2.strict != null ? { strict: tool2.strict } : {} } }); break; default: toolWarnings.push({ type: "unsupported", feature: `tool type: ${tool2.type}` }); break; } } if (toolChoice == null) { 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 _OpenAIChatLanguageModel { constructor(modelId, config2) { this.specificationVersion = "v4"; this.supportedUrls = { "image/*": [/^https?:\/\/.*$/] }; this.modelId = modelId; this.config = config2; } static [WORKFLOW_SERIALIZE](model) { return serializeModelOptions({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE](options) { return new _OpenAIChatLanguageModel(options.modelId, options.config); } get provider() { return this.config.provider; } async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools: tools2, toolChoice, reasoning, providerOptions }) { var _a25, _b19, _c, _d, _e2, _f; const warnings = []; const openaiOptions = (_a25 = await parseProviderOptions({ provider: "openai", providerOptions, schema: openaiLanguageModelChatOptions })) != null ? _a25 : {}; const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId); const resolvedReasoningEffort = (_b19 = openaiOptions.reasoningEffort) != null ? _b19 : isCustomReasoning(reasoning) ? reasoning : void 0; const isReasoningModel = (_c = openaiOptions.forceReasoning) != null ? _c : modelCapabilities.isReasoningModel; if (topK != null) { warnings.push({ type: "unsupported", feature: "topK" }); } const { messages, warnings: messageWarnings } = convertToOpenAIChatMessages( { prompt, systemMessageMode: (_d = openaiOptions.systemMessageMode) != null ? _d : isReasoningModel ? "developer" : modelCapabilities.systemMessageMode } ); warnings.push(...messageWarnings); const strictJsonSchema = (_e2 = openaiOptions.strictJsonSchema) != null ? _e2 : true; const baseArgs = { // model id: model: this.modelId, // model specific settings: logit_bias: openaiOptions.logitBias, logprobs: openaiOptions.logprobs === true || typeof openaiOptions.logprobs === "number" ? true : void 0, top_logprobs: typeof openaiOptions.logprobs === "number" ? openaiOptions.logprobs : typeof openaiOptions.logprobs === "boolean" ? openaiOptions.logprobs ? 0 : void 0 : void 0, user: openaiOptions.user, parallel_tool_calls: openaiOptions.parallelToolCalls, // standardized settings: max_tokens: maxOutputTokens, temperature, top_p: topP, frequency_penalty: frequencyPenalty, presence_penalty: presencePenalty, response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? { type: "json_schema", json_schema: { schema: responseFormat.schema, strict: strictJsonSchema, name: (_f = responseFormat.name) != null ? _f : "response", description: responseFormat.description } } : { type: "json_object" } : void 0, stop: stopSequences, seed, verbosity: openaiOptions.textVerbosity, // openai specific settings: // TODO AI SDK 6: remove, we auto-map maxOutputTokens now max_completion_tokens: openaiOptions.maxCompletionTokens, store: openaiOptions.store, metadata: openaiOptions.metadata, prediction: openaiOptions.prediction, reasoning_effort: resolvedReasoningEffort, service_tier: openaiOptions.serviceTier, prompt_cache_key: openaiOptions.promptCacheKey, prompt_cache_options: openaiOptions.promptCacheOptions, prompt_cache_retention: openaiOptions.promptCacheRetention, safety_identifier: openaiOptions.safetyIdentifier, // messages: messages }; if (isReasoningModel) { if (resolvedReasoningEffort !== "none" || !modelCapabilities.supportsNonReasoningParameters) { if (baseArgs.temperature != null) { baseArgs.temperature = void 0; warnings.push({ type: "unsupported", feature: "temperature", details: "temperature is not supported for reasoning models" }); } if (baseArgs.top_p != null) { baseArgs.top_p = void 0; warnings.push({ type: "unsupported", feature: "topP", details: "topP is not supported for reasoning models" }); } if (baseArgs.logprobs != null) { baseArgs.logprobs = void 0; warnings.push({ type: "other", message: "logprobs is not supported for reasoning models" }); } } if (baseArgs.frequency_penalty != null) { baseArgs.frequency_penalty = void 0; warnings.push({ type: "unsupported", feature: "frequencyPenalty", details: "frequencyPenalty is not supported for reasoning models" }); } if (baseArgs.presence_penalty != null) { baseArgs.presence_penalty = void 0; warnings.push({ type: "unsupported", feature: "presencePenalty", details: "presencePenalty is not supported for reasoning models" }); } if (baseArgs.logit_bias != null) { baseArgs.logit_bias = void 0; warnings.push({ type: "other", message: "logitBias is not supported for reasoning models" }); } if (baseArgs.top_logprobs != null) { baseArgs.top_logprobs = void 0; warnings.push({ type: "other", message: "topLogprobs is not supported for reasoning models" }); } if (baseArgs.max_tokens != null) { if (baseArgs.max_completion_tokens == null) { 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 (baseArgs.temperature != null) { 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 (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" }); baseArgs.service_tier = void 0; } if (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" }); baseArgs.service_tier = void 0; } const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = prepareChatTools({ tools: tools2, toolChoice }); return { args: { ...baseArgs, tools: openaiTools2, tool_choice: openaiToolChoice }, warnings: [...warnings, ...toolWarnings] }; } async doGenerate(options) { var _a25, _b19, _c, _d, _e2, _f, _g, _h; const { args: body, warnings } = await this.getArgs(options); const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({ url: this.config.url({ path: "/chat/completions", modelId: this.modelId }), headers: combineHeaders((_b19 = (_a25 = this.config).headers) == null ? void 0 : _b19.call(_a25), options.headers), body, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler( openaiChatResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const choice2 = response.choices[0]; const content = []; const text2 = choice2.message.content; if (text2 != null && text2.length > 0) { content.push({ type: "text", text: text2 }); } for (const toolCall of (_c = choice2.message.tool_calls) != null ? _c : []) { content.push({ type: "tool-call", toolCallId: (_d = toolCall.id) != null ? _d : generateId(), toolName: toolCall.function.name, input: toolCall.function.arguments }); } for (const annotation of (_e2 = choice2.message.annotations) != null ? _e2 : []) { content.push({ type: "source", sourceType: "url", id: generateId(), url: annotation.url_citation.url, title: annotation.url_citation.title }); } const completionTokenDetails = (_f = response.usage) == null ? void 0 : _f.completion_tokens_details; const providerMetadata = { openai: {} }; if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) { providerMetadata.openai.acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens; } if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) { providerMetadata.openai.rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens; } if (((_g = choice2.logprobs) == null ? void 0 : _g.content) != null) { providerMetadata.openai.logprobs = choice2.logprobs.content; } return { content, finishReason: { unified: mapOpenAIFinishReason(choice2.finish_reason), raw: (_h = choice2.finish_reason) != null ? _h : void 0 }, usage: convertOpenAIChatUsage(response.usage), request: { body }, response: { ...getResponseMetadata(response), headers: responseHeaders, body: rawResponse }, warnings, providerMetadata }; } async doStream(options) { var _a25, _b19; const { args, warnings } = await this.getArgs(options); const body = { ...args, stream: true, stream_options: { include_usage: true } }; const url2 = this.config.url({ path: "/chat/completions", modelId: this.modelId }); const { responseHeaders, value: response } = await postJsonToApi({ url: url2, headers: combineHeaders((_b19 = (_a25 = this.config).headers) == null ? void 0 : _b19.call(_a25), options.headers), body, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createEventSourceResponseHandler( openaiChatChunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const checkedResponse = await throwIfOpenAIStreamErrorBeforeOutput({ stream: response, getError: (chunk) => "error" in chunk ? chunk.error : void 0, isOutputChunk: isOpenAIChatOutputChunk, url: url2, requestBodyValues: body, responseHeaders }); let toolCallTracker; let finishReason = { unified: "other", raw: void 0 }; let usage = void 0; let metadataExtracted = false; let isActiveText = false; const providerMetadata = { openai: {} }; const result = { stream: checkedResponse.pipeThrough( new TransformStream({ start(controller) { toolCallTracker = new StreamingToolCallTracker(controller, { generateId, typeValidation: "if-present" }); controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { var _a26, _b23, _c, _d, _e2; if (options.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 value = chunk.value; if ("error" in value) { finishReason = { unified: "error", raw: void 0 }; controller.enqueue({ type: "error", error: value.error }); return; } if (!metadataExtracted) { const metadata = getResponseMetadata(value); if (Object.values(metadata).some(Boolean)) { metadataExtracted = true; controller.enqueue({ type: "response-metadata", ...getResponseMetadata(value) }); } } if (value.usage != null) { usage = value.usage; if (((_a26 = value.usage.completion_tokens_details) == null ? void 0 : _a26.accepted_prediction_tokens) != null) { providerMetadata.openai.acceptedPredictionTokens = (_b23 = value.usage.completion_tokens_details) == null ? void 0 : _b23.accepted_prediction_tokens; } if (((_c = value.usage.completion_tokens_details) == null ? void 0 : _c.rejected_prediction_tokens) != null) { providerMetadata.openai.rejectedPredictionTokens = (_d = value.usage.completion_tokens_details) == null ? void 0 : _d.rejected_prediction_tokens; } } const choice2 = value.choices[0]; if ((choice2 == null ? void 0 : choice2.finish_reason) != null) { finishReason = { unified: mapOpenAIFinishReason(choice2.finish_reason), raw: choice2.finish_reason }; } if (((_e2 = choice2 == null ? void 0 : choice2.logprobs) == null ? void 0 : _e2.content) != null) { providerMetadata.openai.logprobs = choice2.logprobs.content; } if ((choice2 == null ? void 0 : choice2.delta) == null) { return; } const delta = choice2.delta; if (delta.content != null) { if (!isActiveText) { controller.enqueue({ type: "text-start", id: "0" }); isActiveText = true; } controller.enqueue({ type: "text-delta", id: "0", delta: delta.content }); } if (delta.tool_calls != null) { for (const toolCallDelta of delta.tool_calls) { toolCallTracker.processDelta(toolCallDelta); } } if (delta.annotations != null) { 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" }); } toolCallTracker.flush(); controller.enqueue({ type: "finish", finishReason, usage: convertOpenAIChatUsage(usage), ...providerMetadata != null ? { providerMetadata } : {} }); } }) ), request: { body }, response: { headers: responseHeaders } }; return result; } }; function isOpenAIChatOutputChunk(chunk) { if ("error" in chunk) { return false; } return chunk.choices.some((choice2) => { const delta = choice2.delta; return (delta == null ? void 0 : delta.content) != null && delta.content.length > 0 || (delta == null ? void 0 : delta.tool_calls) != null && delta.tool_calls.length > 0 || (delta == null ? void 0 : delta.annotations) != null && delta.annotations.length > 0; }); } function convertOpenAICompletionUsage(usage) { var _a25, _b19, _c, _d; if (usage == null) { 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 = (_a25 = usage.prompt_tokens) != null ? _a25 : 0; const completionTokens = (_b19 = usage.completion_tokens) != null ? _b19 : 0; return { inputTokens: { total: (_c = usage.prompt_tokens) != null ? _c : void 0, noCache: promptTokens, cacheRead: void 0, cacheWrite: void 0 }, outputTokens: { total: (_d = usage.completion_tokens) != null ? _d : void 0, text: completionTokens, reasoning: void 0 }, raw: usage }; } function convertToOpenAICompletionPrompt({ prompt, user = "user", assistant = "assistant" }) { let text2 = ""; if (prompt[0].role === "system") { text2 += `${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(""); text2 += `${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(""); text2 += `${assistant}: ${assistantMessage} `; break; } case "tool": { throw new UnsupportedFunctionalityError({ functionality: "tool messages" }); } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } text2 += `${assistant}: `; return { prompt: text2, stopSequences: [` ${user}:`] }; } function getResponseMetadata2({ id, model, created }) { return { id: id != null ? id : void 0, modelId: model != null ? model : void 0, timestamp: created != null ? new Date(created * 1e3) : 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 = lazySchema( () => zodSchema( external_exports.object({ id: external_exports.string().nullish(), created: external_exports.number().nullish(), model: external_exports.string().nullish(), choices: external_exports.array( external_exports.object({ text: external_exports.string(), finish_reason: external_exports.string(), logprobs: external_exports.object({ tokens: external_exports.array(external_exports.string()), token_logprobs: external_exports.array(external_exports.number()), top_logprobs: external_exports.array(external_exports.record(external_exports.string(), external_exports.number())).nullish() }).nullish() }) ), usage: external_exports.object({ prompt_tokens: external_exports.number(), completion_tokens: external_exports.number(), total_tokens: external_exports.number() }).nullish() }) ) ); var openaiCompletionChunkSchema = lazySchema( () => zodSchema( external_exports.union([ external_exports.object({ id: external_exports.string().nullish(), created: external_exports.number().nullish(), model: external_exports.string().nullish(), choices: external_exports.array( external_exports.object({ text: external_exports.string(), finish_reason: external_exports.string().nullish(), index: external_exports.number(), logprobs: external_exports.object({ tokens: external_exports.array(external_exports.string()), token_logprobs: external_exports.array(external_exports.number()), top_logprobs: external_exports.array(external_exports.record(external_exports.string(), external_exports.number())).nullish() }).nullish() }) ), usage: external_exports.object({ prompt_tokens: external_exports.number(), completion_tokens: external_exports.number(), total_tokens: external_exports.number() }).nullish() }), openaiErrorDataSchema ]) ) ); var openaiLanguageModelCompletionOptions = lazySchema( () => zodSchema( external_exports.object({ /** * Echo back the prompt in addition to the completion. */ echo: external_exports.boolean().optional(), /** * Modify the likelihood of specified tokens appearing in the completion. * * Accepts a JSON object that maps tokens (specified by their token ID in * the GPT tokenizer) to an associated bias value from -100 to 100. You * can use this tokenizer tool to convert text to token IDs. Mathematically, * the bias is added to the logits generated by the model prior to sampling. * The exact effect will vary per model, but values between -1 and 1 should * decrease or increase likelihood of selection; values like -100 or 100 * should result in a ban or exclusive selection of the relevant token. * * As an example, you can pass {"50256": -100} to prevent the <|endoftext|> * token from being generated. */ logitBias: external_exports.record(external_exports.string(), external_exports.number()).optional(), /** * The suffix that comes after a completion of inserted text. */ suffix: external_exports.string().optional(), /** * A unique identifier representing your end-user, which can help OpenAI to * monitor and detect abuse. Learn more. */ user: external_exports.string().optional(), /** * Return the log probabilities of the tokens. Including logprobs will increase * the response size and can slow down response times. However, it can * be useful to better understand how the model is behaving. * Setting to true will return the log probabilities of the tokens that * were generated. * Setting to a number will return the log probabilities of the top n * tokens that were generated. */ logprobs: external_exports.union([external_exports.boolean(), external_exports.number()]).optional() }) ) ); var OpenAICompletionLanguageModel = class _OpenAICompletionLanguageModel { constructor(modelId, config2) { this.specificationVersion = "v4"; this.supportedUrls = { // No URLs are supported for completion models. }; this.modelId = modelId; this.config = config2; } get providerOptionsName() { return this.config.provider.split(".")[0].trim(); } static [WORKFLOW_SERIALIZE](model) { return serializeModelOptions({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE](options) { return new _OpenAICompletionLanguageModel(options.modelId, options.config); } get provider() { return this.config.provider; } async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences: userStopSequences, responseFormat, tools: tools2, toolChoice, seed, providerOptions }) { const warnings = []; const openaiOptions = { ...await parseProviderOptions({ provider: "openai", providerOptions, schema: openaiLanguageModelCompletionOptions }), ...await parseProviderOptions({ provider: this.providerOptionsName, providerOptions, schema: openaiLanguageModelCompletionOptions }) }; if (topK != null) { warnings.push({ type: "unsupported", feature: "topK" }); } if (tools2 == null ? void 0 : tools2.length) { warnings.push({ type: "unsupported", feature: "tools" }); } if (toolChoice != null) { warnings.push({ type: "unsupported", feature: "toolChoice" }); } if (responseFormat != null && responseFormat.type !== "text") { warnings.push({ type: "unsupported", feature: "responseFormat", details: "JSON response format is not supported." }); } const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt }); const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []]; return { args: { // model id: model: this.modelId, // model specific settings: echo: openaiOptions.echo, logit_bias: openaiOptions.logitBias, logprobs: (openaiOptions == null ? void 0 : openaiOptions.logprobs) === true ? 0 : (openaiOptions == null ? void 0 : openaiOptions.logprobs) === false ? void 0 : openaiOptions == null ? void 0 : openaiOptions.logprobs, suffix: openaiOptions.suffix, user: openaiOptions.user, // standardized settings: max_tokens: maxOutputTokens, temperature, top_p: topP, frequency_penalty: frequencyPenalty, presence_penalty: presencePenalty, seed, // prompt: prompt: completionPrompt, // stop sequences: stop: stop.length > 0 ? stop : void 0 }, warnings }; } async doGenerate(options) { var _a25, _b19, _c; const { args, warnings } = await this.getArgs(options); const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({ url: this.config.url({ path: "/completions", modelId: this.modelId }), headers: combineHeaders((_b19 = (_a25 = this.config).headers) == null ? void 0 : _b19.call(_a25), options.headers), body: args, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler( openaiCompletionResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const choice2 = response.choices[0]; const providerMetadata = { openai: {} }; if (choice2.logprobs != null) { providerMetadata.openai.logprobs = choice2.logprobs; } return { content: [{ type: "text", text: choice2.text }], usage: convertOpenAICompletionUsage(response.usage), finishReason: { unified: mapOpenAIFinishReason2(choice2.finish_reason), raw: (_c = choice2.finish_reason) != null ? _c : void 0 }, request: { body: args }, response: { ...getResponseMetadata2(response), headers: responseHeaders, body: rawResponse }, providerMetadata, warnings }; } async doStream(options) { var _a25, _b19; const { args, warnings } = await this.getArgs(options); const body = { ...args, stream: true, stream_options: { include_usage: true } }; const url2 = this.config.url({ path: "/completions", modelId: this.modelId }); const { responseHeaders, value: response } = await postJsonToApi({ url: url2, headers: combineHeaders((_b19 = (_a25 = this.config).headers) == null ? void 0 : _b19.call(_a25), options.headers), body, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createEventSourceResponseHandler( openaiCompletionChunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const checkedResponse = await throwIfOpenAIStreamErrorBeforeOutput({ stream: response, getError: (chunk) => "error" in chunk ? chunk.error : void 0, isOutputChunk: isOpenAICompletionOutputChunk, url: url2, requestBodyValues: body, responseHeaders }); let finishReason = { unified: "other", raw: void 0 }; const providerMetadata = { openai: {} }; let usage = void 0; let isFirstChunk = true; const result = { stream: checkedResponse.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { if (options.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 value = chunk.value; if ("error" in value) { finishReason = { unified: "error", raw: void 0 }; controller.enqueue({ type: "error", error: value.error }); return; } if (isFirstChunk) { isFirstChunk = false; controller.enqueue({ type: "response-metadata", ...getResponseMetadata2(value) }); controller.enqueue({ type: "text-start", id: "0" }); } if (value.usage != null) { usage = value.usage; } const choice2 = value.choices[0]; if ((choice2 == null ? void 0 : choice2.finish_reason) != null) { finishReason = { unified: mapOpenAIFinishReason2(choice2.finish_reason), raw: choice2.finish_reason }; } if ((choice2 == null ? void 0 : choice2.logprobs) != null) { providerMetadata.openai.logprobs = choice2.logprobs; } if ((choice2 == null ? void 0 : choice2.text) != null && choice2.text.length > 0) { controller.enqueue({ type: "text-delta", id: "0", delta: choice2.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 } }; return result; } }; function isOpenAICompletionOutputChunk(chunk) { return !("error" in chunk) && chunk.choices.some((choice2) => choice2.text.length > 0); } var openaiEmbeddingModelOptions = lazySchema( () => zodSchema( external_exports.object({ /** * The number of dimensions the resulting output embeddings should have. * Only supported in text-embedding-3 and later models. */ dimensions: external_exports.number().optional(), /** * A unique identifier representing your end-user, which can help OpenAI to * monitor and detect abuse. Learn more. */ user: external_exports.string().optional() }) ) ); var openaiTextEmbeddingResponseSchema = lazySchema( () => zodSchema( external_exports.object({ data: external_exports.array(external_exports.object({ embedding: external_exports.array(external_exports.number()) })), usage: external_exports.object({ prompt_tokens: external_exports.number() }).nullish() }) ) ); var OpenAIEmbeddingModel = class _OpenAIEmbeddingModel { constructor(modelId, config2) { this.specificationVersion = "v4"; this.maxEmbeddingsPerCall = 2048; this.supportsParallelCalls = true; this.modelId = modelId; this.config = config2; } static [WORKFLOW_SERIALIZE](model) { return serializeModelOptions({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE](options) { return new _OpenAIEmbeddingModel(options.modelId, options.config); } get provider() { return this.config.provider; } async doEmbed({ values, headers, abortSignal, providerOptions }) { var _a25, _b19, _c; if (values.length > this.maxEmbeddingsPerCall) { throw new TooManyEmbeddingValuesForCallError({ provider: this.provider, modelId: this.modelId, maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, values }); } const openaiOptions = (_a25 = await parseProviderOptions({ provider: "openai", providerOptions, schema: openaiEmbeddingModelOptions })) != null ? _a25 : {}; const { responseHeaders, value: response, rawValue } = await postJsonToApi({ url: this.config.url({ path: "/embeddings", modelId: this.modelId }), headers: combineHeaders((_c = (_b19 = this.config).headers) == null ? void 0 : _c.call(_b19), 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 openaiFilesResponseSchema = lazySchema( () => zodSchema( external_exports.object({ id: external_exports.string(), object: external_exports.string().nullish(), bytes: external_exports.number().nullish(), created_at: external_exports.number().nullish(), filename: external_exports.string().nullish(), purpose: external_exports.string().nullish(), status: external_exports.string().nullish(), expires_at: external_exports.number().nullish() }) ) ); var openaiFilesOptionsSchema = lazySchema( () => zodSchema( external_exports.object({ /* * Required by the OpenAI API, but optional here because * the SDK defaults to "assistants" — by far the most common * purpose when uploading files in this context. */ purpose: external_exports.string().optional(), expiresAfter: external_exports.number().optional() }) ) ); var OpenAIFiles = class { constructor(config2) { this.config = config2; this.specificationVersion = "v4"; } get provider() { return this.config.provider; } async uploadFile({ data, mediaType, filename, providerOptions }) { var _a25, _b19, _c; const openaiOptions = await parseProviderOptions({ provider: "openai", providerOptions, schema: openaiFilesOptionsSchema }); const fileBytes = convertInlineFileDataToUint8Array(data); const blob = new Blob([fileBytes], { type: mediaType }); const formData = new FormData(); if (filename != null) { formData.append("file", blob, filename); } else { formData.append("file", blob); } formData.append("purpose", (_a25 = openaiOptions == null ? void 0 : openaiOptions.purpose) != null ? _a25 : "assistants"); if ((openaiOptions == null ? void 0 : openaiOptions.expiresAfter) != null) { formData.append("expires_after", String(openaiOptions.expiresAfter)); } const { value: response } = await postFormDataToApi({ url: `${this.config.baseURL}/files`, headers: combineHeaders(this.config.headers()), formData, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler( openaiFilesResponseSchema ), fetch: this.config.fetch }); return { warnings: [], providerReference: { openai: response.id }, ...((_b19 = response.filename) != null ? _b19 : filename) ? { filename: (_c = response.filename) != null ? _c : filename } : {}, ...mediaType != null ? { mediaType } : {}, providerMetadata: { openai: { ...response.filename != null ? { filename: response.filename } : {}, ...response.purpose != null ? { purpose: response.purpose } : {}, ...response.bytes != null ? { bytes: response.bytes } : {}, ...response.created_at != null ? { createdAt: response.created_at } : {}, ...response.status != null ? { status: response.status } : {}, ...response.expires_at != null ? { expiresAt: response.expires_at } : {} } } }; } }; var openaiImageResponseSchema = lazySchema( () => zodSchema( external_exports.object({ created: external_exports.number().nullish(), data: external_exports.array( external_exports.object({ b64_json: external_exports.string(), revised_prompt: external_exports.string().nullish() }) ), background: external_exports.string().nullish(), output_format: external_exports.string().nullish(), size: external_exports.string().nullish(), quality: external_exports.string().nullish(), usage: external_exports.object({ input_tokens: external_exports.number().nullish(), output_tokens: external_exports.number().nullish(), total_tokens: external_exports.number().nullish(), input_tokens_details: external_exports.object({ image_tokens: external_exports.number().nullish(), text_tokens: external_exports.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, "gpt-image-2": 10, "chatgpt-image-latest": 10 }; var defaultResponseFormatPrefixes = [ "chatgpt-image-", "gpt-image-1-mini", "gpt-image-1.5", "gpt-image-1", "gpt-image-2" ]; function hasDefaultResponseFormat(modelId) { return defaultResponseFormatPrefixes.some( (prefix) => modelId.startsWith(prefix) ); } var baseImageModelOptionsObject = external_exports.object({ /** * Quality of the generated image(s). * * Valid values: `standard`, `hd`, `low`, `medium`, `high`, `auto`. */ quality: external_exports.enum(["standard", "hd", "low", "medium", "high", "auto"]).optional(), /** * Background behavior for the generated image(s). * * If `transparent`, the output format must support transparency * (i.e. `png` or `webp`). */ background: external_exports.enum(["transparent", "opaque", "auto"]).optional(), /** * Format in which the generated image(s) are returned. */ outputFormat: external_exports.enum(["png", "jpeg", "webp"]).optional(), /** * Compression level (0-100) for the generated image(s). Applies to the * `jpeg` and `webp` output formats. */ outputCompression: external_exports.number().int().min(0).max(100).optional(), /** * A unique identifier representing your end-user, which can help OpenAI * to monitor and detect abuse. */ user: external_exports.string().optional() }); var openaiImageModelOptions = lazySchema( () => zodSchema(baseImageModelOptionsObject) ); var openaiImageModelGenerationOptions = lazySchema( () => zodSchema( baseImageModelOptionsObject.extend({ /** * Style of the generated image. `vivid` produces hyper-real and * dramatic images; `natural` produces more subdued, less hyper-real * looking images. */ style: external_exports.enum(["vivid", "natural"]).optional(), /** * Content moderation level for the generated image(s). `low` applies * less restrictive filtering. */ moderation: external_exports.enum(["auto", "low"]).optional() }) ) ); var openaiImageModelEditOptions = lazySchema( () => zodSchema( baseImageModelOptionsObject.extend({ /** * Fidelity of the output image(s) to the input image(s). */ inputFidelity: external_exports.enum(["high", "low"]).optional() }) ) ); var OpenAIImageModel = class _OpenAIImageModel { constructor(modelId, config2) { this.modelId = modelId; this.config = config2; this.specificationVersion = "v4"; } static [WORKFLOW_SERIALIZE](model) { return serializeModelOptions({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE](options) { return new _OpenAIImageModel(options.modelId, options.config); } get maxImagesPerCall() { var _a25; return (_a25 = modelMaxImagesPerCall[this.modelId]) != null ? _a25 : 1; } get provider() { return this.config.provider; } async doGenerate({ prompt, files, mask, n: n5, size, aspectRatio, seed, providerOptions, headers, abortSignal }) { var _a25, _b19, _c, _d, _e2, _f, _g, _h, _i2, _j, _k, _l, _m, _n3, _o; const warnings = []; if (aspectRatio != null) { warnings.push({ type: "unsupported", feature: "aspectRatio", details: "This model does not support aspect ratio. Use `size` instead." }); } if (seed != null) { warnings.push({ type: "unsupported", feature: "seed" }); } const currentDate = (_c = (_b19 = (_a25 = this.config._internal) == null ? void 0 : _a25.currentDate) == null ? void 0 : _b19.call(_a25)) != null ? _c : /* @__PURE__ */ new Date(); if (files != null) { const openaiOptions2 = (_d = await parseProviderOptions({ provider: "openai", providerOptions, schema: openaiImageModelEditOptions })) != null ? _d : {}; const { value: response2, responseHeaders: responseHeaders2 } = await postFormDataToApi({ url: this.config.url({ path: "/images/edits", modelId: this.modelId }), headers: combineHeaders((_f = (_e2 = this.config).headers) == null ? void 0 : _f.call(_e2), headers), formData: convertToFormData({ model: this.modelId, prompt, image: await Promise.all( files.map( (file2) => file2.type === "file" ? new Blob( [ file2.data instanceof Uint8Array ? new Blob([file2.data], { type: file2.mediaType }) : new Blob([convertBase64ToUint8Array(file2.data)], { type: file2.mediaType }) ], { type: file2.mediaType } ) : downloadBlob(file2.url) ) ), mask: mask != null ? await fileToBlob(mask) : void 0, n: n5, size, quality: openaiOptions2.quality, background: openaiOptions2.background, output_format: openaiOptions2.outputFormat, output_compression: openaiOptions2.outputCompression, input_fidelity: openaiOptions2.inputFidelity, user: openaiOptions2.user }), failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler( openaiImageResponseSchema ), abortSignal, fetch: this.config.fetch }); return { images: response2.data.map((item) => item.b64_json), warnings, usage: response2.usage != null ? { inputTokens: (_g = response2.usage.input_tokens) != null ? _g : void 0, outputTokens: (_h = response2.usage.output_tokens) != null ? _h : void 0, totalTokens: (_i2 = response2.usage.total_tokens) != null ? _i2 : void 0 } : void 0, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders2 }, providerMetadata: { openai: { images: response2.data.map((item, index) => { var _a26, _b23, _c2, _d2, _e22, _f2; return { ...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {}, created: (_a26 = response2.created) != null ? _a26 : void 0, size: (_b23 = response2.size) != null ? _b23 : void 0, quality: (_c2 = response2.quality) != null ? _c2 : void 0, background: (_d2 = response2.background) != null ? _d2 : void 0, outputFormat: (_e22 = response2.output_format) != null ? _e22 : void 0, ...distributeTokenDetails( (_f2 = response2.usage) == null ? void 0 : _f2.input_tokens_details, index, response2.data.length ) }; }) } } }; } const openaiOptions = (_j = await parseProviderOptions({ provider: "openai", providerOptions, schema: openaiImageModelGenerationOptions })) != null ? _j : {}; const { value: response, responseHeaders } = await postJsonToApi({ url: this.config.url({ path: "/images/generations", modelId: this.modelId }), headers: combineHeaders((_l = (_k = this.config).headers) == null ? void 0 : _l.call(_k), headers), body: { model: this.modelId, prompt, n: n5, size, quality: openaiOptions.quality, style: openaiOptions.style, background: openaiOptions.background, moderation: openaiOptions.moderation, output_format: openaiOptions.outputFormat, output_compression: openaiOptions.outputCompression, user: openaiOptions.user, ...!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: response.usage != null ? { inputTokens: (_m = response.usage.input_tokens) != null ? _m : void 0, outputTokens: (_n3 = response.usage.output_tokens) != null ? _n3 : void 0, totalTokens: (_o = response.usage.total_tokens) != null ? _o : void 0 } : void 0, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders }, providerMetadata: { openai: { images: response.data.map((item, index) => { var _a26, _b23, _c2, _d2, _e22, _f2; return { ...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {}, created: (_a26 = response.created) != null ? _a26 : void 0, size: (_b23 = response.size) != null ? _b23 : void 0, quality: (_c2 = response.quality) != null ? _c2 : void 0, background: (_d2 = response.background) != null ? _d2 : void 0, outputFormat: (_e22 = response.output_format) != null ? _e22 : void 0, ...distributeTokenDetails( (_f2 = response.usage) == null ? void 0 : _f2.input_tokens_details, index, response.data.length ) }; }) } } }; } }; function distributeTokenDetails(details, index, total) { if (details == null) { return {}; } const result = {}; if (details.image_tokens != null) { const base = Math.floor(details.image_tokens / total); const remainder = details.image_tokens - base * (total - 1); result.imageTokens = index === total - 1 ? remainder : base; } if (details.text_tokens != null) { 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(file2) { if (!file2) return void 0; if (file2.type === "url") { return downloadBlob(file2.url); } const data = file2.data instanceof Uint8Array ? file2.data : convertBase64ToUint8Array(file2.data); return new Blob([data], { type: file2.mediaType }); } var applyPatchInputSchema = lazySchema( () => zodSchema( external_exports.object({ callId: external_exports.string(), operation: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("create_file"), path: external_exports.string(), diff: external_exports.string() }), external_exports.object({ type: external_exports.literal("delete_file"), path: external_exports.string() }), external_exports.object({ type: external_exports.literal("update_file"), path: external_exports.string(), diff: external_exports.string() }) ]) }) ) ); var applyPatchOutputSchema = lazySchema( () => zodSchema( external_exports.object({ status: external_exports.enum(["completed", "failed"]), output: external_exports.string().optional() }) ) ); var applyPatchArgsSchema = lazySchema(() => zodSchema(external_exports.object({}))); var applyPatchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({ id: "openai.apply_patch", inputSchema: applyPatchInputSchema, outputSchema: applyPatchOutputSchema }); var applyPatch = applyPatchToolFactory; var codeInterpreterInputSchema = lazySchema( () => zodSchema( external_exports.object({ code: external_exports.string().nullish(), containerId: external_exports.string() }) ) ); var codeInterpreterOutputSchema = lazySchema( () => zodSchema( external_exports.object({ outputs: external_exports.array( external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("logs"), logs: external_exports.string() }), external_exports.object({ type: external_exports.literal("image"), url: external_exports.string() }) ]) ).nullish() }) ) ); var codeInterpreterArgsSchema = lazySchema( () => zodSchema( external_exports.object({ container: external_exports.union([ external_exports.string(), external_exports.object({ fileIds: external_exports.array(external_exports.string()).optional() }) ]).optional() }) ) ); var codeInterpreterToolFactory = createProviderExecutedToolFactory({ id: "openai.code_interpreter", inputSchema: codeInterpreterInputSchema, outputSchema: codeInterpreterOutputSchema }); var codeInterpreter = (args = {}) => { return codeInterpreterToolFactory(args); }; var safetyCheckSchema = external_exports.object({ id: external_exports.string(), code: external_exports.string().optional(), message: external_exports.string().optional() }); var computerActionSchema = external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("click"), button: external_exports.enum(["left", "right", "wheel", "back", "forward"]), x: external_exports.number(), y: external_exports.number(), keys: external_exports.array(external_exports.string()).optional() }), external_exports.object({ type: external_exports.literal("double_click"), x: external_exports.number(), y: external_exports.number(), keys: external_exports.array(external_exports.string()).optional() }), external_exports.object({ type: external_exports.literal("drag"), path: external_exports.array(external_exports.object({ x: external_exports.number(), y: external_exports.number() })), keys: external_exports.array(external_exports.string()).optional() }), external_exports.object({ type: external_exports.literal("keypress"), keys: external_exports.array(external_exports.string()) }), external_exports.object({ type: external_exports.literal("move"), x: external_exports.number(), y: external_exports.number(), keys: external_exports.array(external_exports.string()).optional() }), external_exports.object({ type: external_exports.literal("screenshot") }), external_exports.object({ type: external_exports.literal("scroll"), x: external_exports.number(), y: external_exports.number(), scrollX: external_exports.number(), scrollY: external_exports.number(), keys: external_exports.array(external_exports.string()).optional() }), external_exports.object({ type: external_exports.literal("type"), text: external_exports.string() }), external_exports.object({ type: external_exports.literal("wait") }) ]); var computerInputSchema = lazySchema( () => zodSchema( external_exports.object({ actions: external_exports.array(computerActionSchema), pendingSafetyChecks: external_exports.array(safetyCheckSchema), status: external_exports.enum(["in_progress", "completed", "incomplete"]) }) ) ); var computerOutputSchema = lazySchema( () => zodSchema( external_exports.object({ output: external_exports.union([ external_exports.object({ type: external_exports.literal("computer_screenshot"), imageUrl: external_exports.string(), fileId: external_exports.string().optional(), detail: external_exports.enum(["auto", "low", "high", "original"]).optional() }), external_exports.object({ type: external_exports.literal("computer_screenshot"), fileId: external_exports.string(), imageUrl: external_exports.string().optional(), detail: external_exports.enum(["auto", "low", "high", "original"]).optional() }) ]), acknowledgedSafetyChecks: external_exports.array(safetyCheckSchema).optional() }) ) ); var computerToolFactory = createProviderDefinedToolFactoryWithOutputSchema({ id: "openai.computer", inputSchema: computerInputSchema, outputSchema: computerOutputSchema }); var computer = (options = {}) => computerToolFactory(options); var customArgsSchema = lazySchema( () => zodSchema( external_exports.object({ description: external_exports.string().optional(), format: external_exports.union([ external_exports.object({ type: external_exports.literal("grammar"), syntax: external_exports.enum(["regex", "lark"]), definition: external_exports.string() }), external_exports.object({ type: external_exports.literal("text") }) ]).optional() }) ) ); var customInputSchema = lazySchema(() => zodSchema(external_exports.string())); var customToolFactory = createProviderDefinedToolFactory({ id: "openai.custom", inputSchema: customInputSchema }); var customTool = (args) => customToolFactory(args); var comparisonFilterSchema = external_exports.object({ key: external_exports.string(), type: external_exports.enum(["eq", "ne", "gt", "gte", "lt", "lte", "in", "nin"]), value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.array(external_exports.string())]) }); var compoundFilterSchema = external_exports.object({ type: external_exports.enum(["and", "or"]), filters: external_exports.array( external_exports.union([comparisonFilterSchema, external_exports.lazy(() => compoundFilterSchema)]) ) }); var fileSearchArgsSchema = lazySchema( () => zodSchema( external_exports.object({ vectorStoreIds: external_exports.array(external_exports.string()), maxNumResults: external_exports.number().optional(), ranking: external_exports.object({ ranker: external_exports.string().optional(), scoreThreshold: external_exports.number().optional() }).optional(), filters: external_exports.union([comparisonFilterSchema, compoundFilterSchema]).optional() }) ) ); var fileSearchOutputSchema = lazySchema( () => zodSchema( external_exports.object({ queries: external_exports.array(external_exports.string()), results: external_exports.array( external_exports.object({ attributes: external_exports.record(external_exports.string(), external_exports.unknown()), fileId: external_exports.string(), filename: external_exports.string(), score: external_exports.number(), text: external_exports.string() }) ).nullable() }) ) ); var fileSearch = createProviderExecutedToolFactory({ id: "openai.file_search", inputSchema: external_exports.object({}), outputSchema: fileSearchOutputSchema }); var imageGenerationArgsSchema = lazySchema( () => zodSchema( external_exports.object({ background: external_exports.enum(["auto", "opaque", "transparent"]).optional(), inputFidelity: external_exports.enum(["low", "high"]).optional(), inputImageMask: external_exports.object({ fileId: external_exports.string().optional(), imageUrl: external_exports.string().optional() }).optional(), model: external_exports.string().optional(), moderation: external_exports.enum(["auto"]).optional(), outputCompression: external_exports.number().int().min(0).max(100).optional(), outputFormat: external_exports.enum(["png", "jpeg", "webp"]).optional(), partialImages: external_exports.number().int().min(0).max(3).optional(), quality: external_exports.enum(["auto", "low", "medium", "high"]).optional(), size: external_exports.enum(["1024x1024", "1024x1536", "1536x1024", "auto"]).optional() }).strict() ) ); var imageGenerationInputSchema = lazySchema(() => zodSchema(external_exports.object({}))); var imageGenerationOutputSchema = lazySchema( () => zodSchema(external_exports.object({ result: external_exports.string() })) ); var imageGenerationToolFactory = createProviderExecutedToolFactory({ id: "openai.image_generation", inputSchema: imageGenerationInputSchema, outputSchema: imageGenerationOutputSchema }); var imageGeneration = (args = {}) => { return imageGenerationToolFactory(args); }; var localShellInputSchema = lazySchema( () => zodSchema( external_exports.object({ action: external_exports.object({ type: external_exports.literal("exec"), command: external_exports.array(external_exports.string()), timeoutMs: external_exports.number().optional(), user: external_exports.string().optional(), workingDirectory: external_exports.string().optional(), env: external_exports.record(external_exports.string(), external_exports.string()).optional() }) }) ) ); var localShellOutputSchema = lazySchema( () => zodSchema(external_exports.object({ output: external_exports.string() })) ); var localShell = createProviderDefinedToolFactoryWithOutputSchema({ id: "openai.local_shell", inputSchema: localShellInputSchema, outputSchema: localShellOutputSchema }); var shellInputSchema = lazySchema( () => zodSchema( external_exports.object({ action: external_exports.object({ commands: external_exports.array(external_exports.string()), timeoutMs: external_exports.number().optional(), maxOutputLength: external_exports.number().optional() }) }) ) ); var shellOutputSchema = lazySchema( () => zodSchema( external_exports.object({ output: external_exports.array( external_exports.object({ stdout: external_exports.string(), stderr: external_exports.string(), outcome: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("timeout") }), external_exports.object({ type: external_exports.literal("exit"), exitCode: external_exports.number() }) ]) }) ) }) ) ); var shellSkillsSchema = external_exports.array( external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("skillReference"), providerReference: external_exports.record(external_exports.string(), external_exports.string()), version: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("inline"), name: external_exports.string(), description: external_exports.string(), source: external_exports.object({ type: external_exports.literal("base64"), mediaType: external_exports.literal("application/zip"), data: external_exports.string() }) }) ]) ).optional(); var shellArgsSchema = lazySchema( () => zodSchema( external_exports.object({ environment: external_exports.union([ external_exports.object({ type: external_exports.literal("containerAuto"), fileIds: external_exports.array(external_exports.string()).optional(), memoryLimit: external_exports.enum(["1g", "4g", "16g", "64g"]).optional(), networkPolicy: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("disabled") }), external_exports.object({ type: external_exports.literal("allowlist"), allowedDomains: external_exports.array(external_exports.string()), domainSecrets: external_exports.array( external_exports.object({ domain: external_exports.string(), name: external_exports.string(), value: external_exports.string() }) ).optional() }) ]).optional(), skills: shellSkillsSchema }), external_exports.object({ type: external_exports.literal("containerReference"), containerId: external_exports.string() }), external_exports.object({ type: external_exports.literal("local").optional(), skills: external_exports.array( external_exports.object({ name: external_exports.string(), description: external_exports.string(), path: external_exports.string() }) ).optional() }) ]).optional() }) ) ); var shell = createProviderDefinedToolFactoryWithOutputSchema({ id: "openai.shell", inputSchema: shellInputSchema, outputSchema: shellOutputSchema }); var toolSearchArgsSchema = lazySchema( () => zodSchema( external_exports.object({ execution: external_exports.enum(["server", "client"]).optional(), description: external_exports.string().optional(), parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional() }) ) ); var toolSearchInputSchema = lazySchema( () => zodSchema( external_exports.object({ arguments: external_exports.unknown().optional(), call_id: external_exports.string().nullish() }) ) ); var toolSearchOutputSchema = lazySchema( () => zodSchema( external_exports.object({ tools: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())) }) ) ); var toolSearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({ id: "openai.tool_search", inputSchema: toolSearchInputSchema, outputSchema: toolSearchOutputSchema }); var toolSearch = (args = {}) => toolSearchToolFactory(args); var webSearchArgsSchema = lazySchema( () => zodSchema( external_exports.object({ externalWebAccess: external_exports.boolean().optional(), filters: external_exports.object({ allowedDomains: external_exports.array(external_exports.string()).optional() }).optional(), searchContextSize: external_exports.enum(["low", "medium", "high"]).optional(), userLocation: external_exports.object({ type: external_exports.literal("approximate"), country: external_exports.string().optional(), city: external_exports.string().optional(), region: external_exports.string().optional(), timezone: external_exports.string().optional() }).optional() }) ) ); var webSearchInputSchema = lazySchema(() => zodSchema(external_exports.object({}))); var webSearchOutputSchema = lazySchema( () => zodSchema( external_exports.object({ action: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("search"), query: external_exports.string().optional(), queries: external_exports.array(external_exports.string()).optional() }), external_exports.object({ type: external_exports.literal("openPage"), url: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("findInPage"), url: external_exports.string().nullish(), pattern: external_exports.string().nullish() }) ]).optional(), sources: external_exports.array( external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("url"), url: external_exports.string() }), external_exports.object({ type: external_exports.literal("api"), name: external_exports.string() }) ]) ).optional() }) ) ); var webSearchToolFactory = createProviderExecutedToolFactory({ id: "openai.web_search", inputSchema: webSearchInputSchema, outputSchema: webSearchOutputSchema }); var webSearch = (args = {}) => webSearchToolFactory(args); var webSearchPreviewArgsSchema = lazySchema( () => zodSchema( external_exports.object({ searchContextSize: external_exports.enum(["low", "medium", "high"]).optional(), userLocation: external_exports.object({ type: external_exports.literal("approximate"), country: external_exports.string().optional(), city: external_exports.string().optional(), region: external_exports.string().optional(), timezone: external_exports.string().optional() }).optional() }) ) ); var webSearchPreviewInputSchema = lazySchema( () => zodSchema(external_exports.object({})) ); var webSearchPreviewOutputSchema = lazySchema( () => zodSchema( external_exports.object({ action: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("search"), query: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("openPage"), url: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("findInPage"), url: external_exports.string().nullish(), pattern: external_exports.string().nullish() }) ]).optional() }) ) ); var webSearchPreview = createProviderExecutedToolFactory({ id: "openai.web_search_preview", inputSchema: webSearchPreviewInputSchema, outputSchema: webSearchPreviewOutputSchema }); var jsonValueSchema2 = external_exports.lazy( () => external_exports.union([ external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(jsonValueSchema2), external_exports.record(external_exports.string(), jsonValueSchema2) ]) ); var mcpArgsSchema = lazySchema( () => zodSchema( external_exports.object({ serverLabel: external_exports.string(), allowedTools: external_exports.union([ external_exports.array(external_exports.string()), external_exports.object({ readOnly: external_exports.boolean().optional(), toolNames: external_exports.array(external_exports.string()).optional() }) ]).optional(), authorization: external_exports.string().optional(), connectorId: external_exports.string().optional(), headers: external_exports.record(external_exports.string(), external_exports.string()).optional(), requireApproval: external_exports.union([ external_exports.enum(["always", "never"]), external_exports.object({ never: external_exports.object({ toolNames: external_exports.array(external_exports.string()).optional() }).optional() }) ]).optional(), serverDescription: external_exports.string().optional(), serverUrl: external_exports.string().optional() }).refine( (v2) => v2.serverUrl != null || v2.connectorId != null, "One of serverUrl or connectorId must be provided." ) ) ); var mcpInputSchema = lazySchema(() => zodSchema(external_exports.object({}))); var mcpOutputSchema = lazySchema( () => zodSchema( external_exports.object({ type: external_exports.literal("call"), serverLabel: external_exports.string(), name: external_exports.string(), arguments: external_exports.string(), output: external_exports.string().nullish(), error: external_exports.union([external_exports.string(), jsonValueSchema2]).optional() }) ) ); var mcpToolFactory = createProviderExecutedToolFactory({ id: "openai.mcp", inputSchema: mcpInputSchema, outputSchema: mcpOutputSchema }); var mcp = (args) => mcpToolFactory(args); var openaiTools = { /** * The apply_patch tool lets GPT-5.1 create, update, and delete files in your * codebase using structured diffs. Instead of just suggesting edits, the model * emits patch operations that your application applies and then reports back on, * enabling iterative, multi-step code editing workflows. * */ applyPatch, /** * Custom tools let callers constrain model output to a grammar (regex or * Lark syntax). The model returns a `custom_tool_call` output item whose * `input` field is a string matching the specified grammar. * * @param description - An optional description of the tool. * @param format - The output format constraint (grammar type, syntax, and definition). */ customTool, /** * The Code Interpreter tool allows models to write and run Python code in a * sandboxed environment to solve complex problems in domains like data analysis, * coding, and math. * * @param container - The container to use for the code interpreter. */ codeInterpreter, /** * The computer tool allows models to operate a browser or desktop through * batched UI actions. Your application executes the actions and returns an * updated screenshot. * * WARNING: Run computer use in an isolated environment, treat on-screen * content as untrusted, and require confirmation for consequential actions. */ computer, /** * File search is a tool available in the Responses API. It enables models to * retrieve information in a knowledge base of previously uploaded files through * semantic and keyword search. * * @param vectorStoreIds - The vector store IDs to use for the file search. * @param maxNumResults - The maximum number of results to return. * @param ranking - The ranking options to use for the file search. * @param filters - The filters to use for the file search. */ fileSearch, /** * The image generation tool allows you to generate images using a text prompt, * and optionally image inputs. It leverages the GPT Image model, * and automatically optimizes text inputs for improved performance. * * @param background - Background type for the generated image. One of 'auto', 'opaque', or 'transparent'. * @param inputFidelity - Input fidelity for the generated image. One of 'low' or 'high'. * @param inputImageMask - Optional mask for inpainting. Contains fileId and/or imageUrl. * @param model - The image generation model to use. Default: gpt-image-1. * @param moderation - Moderation level for the generated image. Default: 'auto'. * @param outputCompression - Compression level for the output image (0-100). * @param outputFormat - The output format of the generated image. One of 'png', 'jpeg', or 'webp'. * @param partialImages - Number of partial images to generate in streaming mode (0-3). * @param quality - The quality of the generated image. One of 'auto', 'low', 'medium', or 'high'. * @param size - The size of the generated image. One of 'auto', '1024x1024', '1024x1536', or '1536x1024'. */ imageGeneration, /** * Local shell is a tool that allows agents to run shell commands locally * on a machine you or the user provides. * * Supported models: `gpt-5-codex` */ localShell, /** * The shell tool allows the model to interact with your local computer through * a controlled command-line interface. The model proposes shell commands; your * integration executes them and returns the outputs. * * Available through the Responses API for use with GPT-5.1. * * WARNING: Running arbitrary shell commands can be dangerous. Always sandbox * execution or add strict allow-/deny-lists before forwarding a command to * the system shell. */ shell, /** * Web search allows models to access up-to-date information from the internet * and provide answers with sourced citations. * * @param searchContextSize - The search context size to use for the web search. * @param userLocation - The user location to use for the web search. */ webSearchPreview, /** * Web search allows models to access up-to-date information from the internet * and provide answers with sourced citations. * * @param filters - The filters to use for the web search. * @param searchContextSize - The search context size to use for the web search. * @param userLocation - The user location to use for the web search. */ webSearch, /** * MCP (Model Context Protocol) allows models to call tools exposed by * remote MCP servers or service connectors. * * @param serverLabel - Label to identify the MCP server. * @param allowedTools - Allowed tool names or filter object. * @param authorization - OAuth access token for the MCP server/connector. * @param connectorId - Identifier for a service connector. * @param headers - Optional headers to include in MCP requests. * // param requireApproval - Approval policy ('always'|'never'|filter object). (Removed - always 'never') * @param serverDescription - Optional description of the server. * @param serverUrl - URL for the MCP server. */ mcp, /** * Tool search allows the model to dynamically search for and load deferred * tools into the model's context as needed. This helps reduce overall token * usage, cost, and latency by only loading tools when the model needs them. * * To use tool search, mark functions or namespaces with `defer_loading: true` * in the tools array. The model will use tool search to load these tools * when it determines they are needed. */ toolSearch }; function parseOpenAIRealtimeServerEvent(raw) { var _a25, _b19, _c, _d, _e2, _f, _g, _h, _i2, _j, _k, _l, _m, _n3, _o, _p, _q, _r2, _s2; const event = raw; const type = event.type; switch (type) { // ── Session lifecycle ────────────────────────────────────────── case "session.created": return { type: "session-created", sessionId: (_a25 = event.session) == null ? void 0 : _a25.id, raw }; case "session.updated": return { type: "session-updated", raw }; // ── Input audio buffer ───────────────────────────────────────── case "input_audio_buffer.speech_started": return { type: "speech-started", itemId: event.item_id, raw }; case "input_audio_buffer.speech_stopped": return { type: "speech-stopped", itemId: event.item_id, raw }; case "input_audio_buffer.committed": return { type: "audio-committed", itemId: event.item_id, previousItemId: event.previous_item_id, raw }; // ── Conversation items ───────────────────────────────────────── case "conversation.item.added": return { type: "conversation-item-added", itemId: (_c = (_b19 = event.item) == null ? void 0 : _b19.id) != null ? _c : event.item_id, item: event.item, raw }; case "conversation.item.input_audio_transcription.completed": return { type: "input-transcription-completed", itemId: event.item_id, transcript: (_d = event.transcript) != null ? _d : "", raw }; // ── Response lifecycle ────────────────────────────────────────── case "response.created": return { type: "response-created", responseId: (_f = (_e2 = event.response) == null ? void 0 : _e2.id) != null ? _f : event.response_id, raw }; case "response.done": return { type: "response-done", responseId: (_h = (_g = event.response) == null ? void 0 : _g.id) != null ? _h : event.response_id, status: (_j = (_i2 = event.response) == null ? void 0 : _i2.status) != null ? _j : "completed", raw }; // ── Output item lifecycle ─────────────────────────────────────── case "response.output_item.added": return { type: "output-item-added", responseId: event.response_id, itemId: (_l = (_k = event.item) == null ? void 0 : _k.id) != null ? _l : event.item_id, raw }; case "response.output_item.done": return { type: "output-item-done", responseId: event.response_id, itemId: (_n3 = (_m = event.item) == null ? void 0 : _m.id) != null ? _n3 : event.item_id, raw }; case "response.content_part.added": return { type: "content-part-added", responseId: event.response_id, itemId: event.item_id, raw }; case "response.content_part.done": return { type: "content-part-done", responseId: event.response_id, itemId: event.item_id, raw }; // ── Audio output ──────────────────────────────────────────────── case "response.output_audio.delta": return { type: "audio-delta", responseId: event.response_id, itemId: event.item_id, delta: event.delta, raw }; case "response.output_audio.done": return { type: "audio-done", responseId: event.response_id, itemId: event.item_id, raw }; // ── Audio transcript output ───────────────────────────────────── case "response.output_audio_transcript.delta": return { type: "audio-transcript-delta", responseId: event.response_id, itemId: event.item_id, delta: event.delta, raw }; case "response.output_audio_transcript.done": return { type: "audio-transcript-done", responseId: event.response_id, itemId: event.item_id, transcript: event.transcript, raw }; // ── Text output ───────────────────────────────────────────────── case "response.output_text.delta": return { type: "text-delta", responseId: event.response_id, itemId: event.item_id, delta: event.delta, raw }; case "response.output_text.done": return { type: "text-done", responseId: event.response_id, itemId: event.item_id, text: event.text, raw }; // ── Function calling ──────────────────────────────────────────── case "response.function_call_arguments.delta": return { type: "function-call-arguments-delta", responseId: event.response_id, itemId: event.item_id, callId: event.call_id, delta: event.delta, raw }; case "response.function_call_arguments.done": return { type: "function-call-arguments-done", responseId: event.response_id, itemId: event.item_id, callId: event.call_id, name: event.name, arguments: event.arguments, raw }; // ── Error ─────────────────────────────────────────────────────── case "error": return { type: "error", message: (_q = (_p = (_o = event.error) == null ? void 0 : _o.message) != null ? _p : event.message) != null ? _q : "Unknown error", code: (_s2 = (_r2 = event.error) == null ? void 0 : _r2.code) != null ? _s2 : event.code, raw }; // ── Pass-through ──────────────────────────────────────────────── default: return { type: "custom", rawType: type, raw }; } } function serializeOpenAIRealtimeClientEvent(event, modelId) { switch (event.type) { case "session-update": return { type: "session.update", session: buildOpenAISessionConfig(event.config, modelId) }; case "input-audio-append": return { type: "input_audio_buffer.append", audio: event.audio }; case "input-audio-commit": return { type: "input_audio_buffer.commit" }; case "input-audio-clear": return { type: "input_audio_buffer.clear" }; case "conversation-item-create": { const item = event.item; switch (item.type) { case "text-message": return { type: "conversation.item.create", item: { type: "message", role: item.role, content: [{ type: "input_text", text: item.text }] } }; case "audio-message": return { type: "conversation.item.create", item: { type: "message", role: item.role, content: [{ type: "input_audio", audio: item.audio }] } }; case "function-call-output": return { type: "conversation.item.create", item: { type: "function_call_output", call_id: item.callId, output: item.output } }; } break; } case "conversation-item-truncate": return { type: "conversation.item.truncate", item_id: event.itemId, content_index: event.contentIndex, audio_end_ms: event.audioEndMs }; case "response-create": return { type: "response.create", ...event.options != null ? { response: { ...event.options.modalities != null ? { output_modalities: event.options.modalities } : {}, ...event.options.instructions != null ? { instructions: event.options.instructions } : {}, ...event.options.metadata != null ? { metadata: event.options.metadata } : {} } } : {} }; case "response-cancel": return { type: "response.cancel" }; } } function buildOpenAISessionConfig(config2, modelId) { var _a25; const session2 = { type: "realtime", model: modelId }; if (config2.instructions != null) { session2.instructions = config2.instructions; } if (config2.outputModalities != null) { session2.output_modalities = config2.outputModalities; } const audio = {}; if (config2.inputAudioFormat != null || config2.inputAudioTranscription != null || config2.turnDetection != null) { const input = {}; if (config2.inputAudioFormat != null) { input.format = { type: config2.inputAudioFormat.type, ...config2.inputAudioFormat.rate != null ? { rate: config2.inputAudioFormat.rate } : {} }; } if (config2.turnDetection != null) { if (config2.turnDetection.type === "disabled") { input.turn_detection = null; } else { const td2 = { type: config2.turnDetection.type === "server-vad" ? "server_vad" : "semantic_vad" }; if (config2.turnDetection.threshold != null) { td2.threshold = config2.turnDetection.threshold; } if (config2.turnDetection.silenceDurationMs != null) { td2.silence_duration_ms = config2.turnDetection.silenceDurationMs; } if (config2.turnDetection.prefixPaddingMs != null) { td2.prefix_padding_ms = config2.turnDetection.prefixPaddingMs; } input.turn_detection = td2; } } if (config2.inputAudioTranscription != null) { input.transcription = { model: (_a25 = config2.inputAudioTranscription.model) != null ? _a25 : "gpt-realtime-whisper", ...config2.inputAudioTranscription.language != null ? { language: config2.inputAudioTranscription.language } : {}, ...config2.inputAudioTranscription.prompt != null ? { prompt: config2.inputAudioTranscription.prompt } : {} }; } audio.input = input; } if (config2.outputAudioFormat != null || config2.voice != null) { const output = {}; if (config2.outputAudioFormat != null) { output.format = { type: config2.outputAudioFormat.type, ...config2.outputAudioFormat.rate != null ? { rate: config2.outputAudioFormat.rate } : {} }; } if (config2.voice != null) { output.voice = config2.voice; } audio.output = output; } if (Object.keys(audio).length > 0) { session2.audio = audio; } if (config2.tools != null && config2.tools.length > 0) { session2.tools = config2.tools.map((tool2) => ({ type: tool2.type, name: tool2.name, description: tool2.description, parameters: tool2.parameters })); session2.tool_choice = "auto"; } if (config2.providerOptions != null) { Object.assign(session2, config2.providerOptions); } return session2; } var OpenAIRealtimeModel = class { constructor(modelId, config2) { this.specificationVersion = "v4"; this.modelId = modelId; this.provider = config2.provider; this.config = config2; } async doCreateClientSecret(options) { var _a25; const fetchFn = (_a25 = this.config.fetch) != null ? _a25 : fetch; const url2 = `${this.config.baseURL}/realtime/client_secrets`; const session2 = options.sessionConfig != null ? buildOpenAISessionConfig(options.sessionConfig, this.modelId) : { type: "realtime", model: this.modelId }; const response = await fetchFn(url2, { method: "POST", headers: { ...this.config.headers(), "Content-Type": "application/json" }, body: JSON.stringify({ session: session2, ...options.expiresAfterSeconds != null ? { // `anchor` is required by the client secrets endpoint; without it // the request fails with "Missing required parameter: // 'expires_after.anchor'". expires_after: { anchor: "created_at", seconds: options.expiresAfterSeconds } } : {} }) }); if (!response.ok) { const text2 = await response.text(); throw new Error( `OpenAI realtime client secret request failed: ${response.status} ${text2}` ); } const data = await response.json(); return { token: data.value, url: `wss://${new URL(this.config.baseURL).host}/v1/realtime?model=${encodeURIComponent(this.modelId)}`, expiresAt: data.expires_at }; } getWebSocketConfig(options) { return { url: options.url, protocols: ["realtime", `openai-insecure-api-key.${options.token}`] }; } parseServerEvent(raw) { return parseOpenAIRealtimeServerEvent(raw); } serializeClientEvent(event) { return serializeOpenAIRealtimeClientEvent(event, this.modelId); } buildSessionConfig(config2) { return buildOpenAISessionConfig(config2, this.modelId); } }; function convertOpenAIResponsesUsage(usage) { var _a25, _b19, _c, _d, _e2, _f; if (usage == null) { 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 = (_b19 = (_a25 = usage.input_tokens_details) == null ? void 0 : _a25.cached_tokens) != null ? _b19 : 0; const cacheWriteTokens = (_d = (_c = usage.input_tokens_details) == null ? void 0 : _c.cache_write_tokens) != null ? _d : void 0; const reasoningTokens = (_f = (_e2 = usage.output_tokens_details) == null ? void 0 : _e2.reasoning_tokens) != null ? _f : 0; return { inputTokens: { total: inputTokens, noCache: inputTokens - cachedTokens - (cacheWriteTokens != null ? cacheWriteTokens : 0), cacheRead: cachedTokens, cacheWrite: cacheWriteTokens }, outputTokens: { total: outputTokens, text: outputTokens - reasoningTokens, reasoning: reasoningTokens }, raw: usage }; } function serializeToolCallArguments2(input) { return JSON.stringify(input === void 0 ? {} : input); } function getPromptCacheBreakpoint2(providerOptions, providerOptionsName) { var _a25; return (_a25 = providerOptions == null ? void 0 : providerOptions[providerOptionsName]) == null ? void 0 : _a25.promptCacheBreakpoint; } function isFileId(data, prefixes) { if (!prefixes) return false; return prefixes.some((prefix) => data.startsWith(prefix)); } async function convertToOpenAIResponsesInput({ prompt, toolNameMapping, systemMessageMode, providerOptionsName, fileIdPrefixes, passThroughUnsupportedFiles = false, store, hasConversation = false, hasPreviousResponseId = false, hasLocalShellTool = false, hasShellTool = false, hasApplyPatchTool = false, hasComputerTool = false, customProviderToolNames }) { var _a25, _b19, _c, _d, _e2, _f, _g, _h, _i2, _j, _k, _l, _m, _n3, _o, _p, _q, _r2, _s2, _t2, _u, _v, _w, _x, _y; let input = []; const warnings = []; const processedApprovalIds = /* @__PURE__ */ new Set(); for (const { role, content, providerOptions } of prompt) { switch (role) { case "system": { switch (systemMessageMode) { case "system": { const promptCacheBreakpoint = getPromptCacheBreakpoint2( providerOptions, providerOptionsName ); input.push({ role: "system", content: promptCacheBreakpoint == null ? content : [ { type: "input_text", text: content, prompt_cache_breakpoint: promptCacheBreakpoint } ] }); break; } case "developer": { const promptCacheBreakpoint = getPromptCacheBreakpoint2( providerOptions, providerOptionsName ); input.push({ role: "developer", content: promptCacheBreakpoint == null ? content : [ { type: "input_text", text: content, prompt_cache_breakpoint: promptCacheBreakpoint } ] }); 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 _a26, _b23, _c2, _d2, _e22; switch (part.type) { case "text": { const promptCacheBreakpoint = getPromptCacheBreakpoint2( part.providerOptions, providerOptionsName ); return { type: "input_text", text: part.text, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } case "file": { const promptCacheBreakpoint = getPromptCacheBreakpoint2( part.providerOptions, providerOptionsName ); switch (part.data.type) { case "reference": { const fileId = resolveProviderReference({ reference: part.data.reference, provider: providerOptionsName }); if (getTopLevelMediaType(part.mediaType) === "image") { return { type: "input_image", file_id: fileId, detail: (_b23 = (_a26 = part.providerOptions) == null ? void 0 : _a26[providerOptionsName]) == null ? void 0 : _b23.imageDetail, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } return { type: "input_file", file_id: fileId, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } case "text": { throw new UnsupportedFunctionalityError({ functionality: "text file parts" }); } case "url": case "data": { const topLevel = getTopLevelMediaType(part.mediaType); if (topLevel === "image") { return { type: "input_image", ...part.data.type === "url" ? { image_url: part.data.url.toString() } : typeof part.data.data === "string" && isFileId(part.data.data, fileIdPrefixes) ? { file_id: part.data.data } : { image_url: `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}` }, detail: (_d2 = (_c2 = part.providerOptions) == null ? void 0 : _c2[providerOptionsName]) == null ? void 0 : _d2.imageDetail, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } else { if (part.data.type === "url") { return { type: "input_file", file_url: part.data.url.toString(), ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } const fullMediaType = resolveFullMediaType({ part }); if (fullMediaType !== "application/pdf" && !passThroughUnsupportedFiles) { throw new UnsupportedFunctionalityError({ functionality: `file part media type ${fullMediaType}` }); } return { type: "input_file", ...typeof part.data.data === "string" && isFileId(part.data.data, fileIdPrefixes) ? { file_id: part.data.data } : { filename: (_e22 = part.filename) != null ? _e22 : fullMediaType === "application/pdf" ? `part-${index}.pdf` : `part-${index}`, file_data: `data:${fullMediaType};base64,${convertToBase64(part.data.data)}` }, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } } } } } }) }); break; } case "assistant": { const reasoningMessages = {}; for (const part of content) { switch (part.type) { case "text": { const providerOptions2 = (_a25 = part.providerOptions) == null ? void 0 : _a25[providerOptionsName]; const id = providerOptions2 == null ? void 0 : providerOptions2.itemId; const phase = providerOptions2 == null ? void 0 : providerOptions2.phase; if (hasConversation && id != null) { break; } if (store && id != null) { input.push({ type: "item_reference", id }); break; } input.push({ role: "assistant", content: [{ type: "output_text", text: part.text }], id, ...phase != null && { phase } }); break; } case "tool-call": { const id = (_f = (_c = (_b19 = part.providerOptions) == null ? void 0 : _b19[providerOptionsName]) == null ? void 0 : _c.itemId) != null ? _f : (_e2 = (_d = part.providerMetadata) == null ? void 0 : _d[providerOptionsName]) == null ? void 0 : _e2.itemId; const namespace = (_k = (_h = (_g = part.providerOptions) == null ? void 0 : _g[providerOptionsName]) == null ? void 0 : _h.namespace) != null ? _k : (_j = (_i2 = part.providerMetadata) == null ? void 0 : _i2[providerOptionsName]) == null ? void 0 : _j.namespace; if (hasConversation && id != null) { break; } const resolvedToolName = toolNameMapping.toProviderToolName( part.toolName ); if (resolvedToolName === "tool_search") { if (store && id != null) { input.push({ type: "item_reference", id }); break; } const parsedInput = typeof part.input === "string" ? await parseJSON({ text: part.input, schema: toolSearchInputSchema }) : await validateTypes({ value: part.input, schema: toolSearchInputSchema }); const execution = parsedInput.call_id != null ? "client" : "server"; input.push({ type: "tool_search_call", id: id != null ? id : part.toolCallId, execution, call_id: (_l = parsedInput.call_id) != null ? _l : null, status: "completed", arguments: parsedInput.arguments }); break; } if (part.providerExecuted) { if (store && id != null) { input.push({ type: "item_reference", id }); } break; } if (hasPreviousResponseId && store && id != null) { break; } const isProviderDefinedToolCall = hasLocalShellTool && resolvedToolName === "local_shell" || hasShellTool && resolvedToolName === "shell" || hasApplyPatchTool && resolvedToolName === "apply_patch" || hasComputerTool && resolvedToolName === "computer" || ((_m = customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) != null ? _m : false); if (store && id != null && isProviderDefinedToolCall) { input.push({ type: "item_reference", id }); break; } if (hasLocalShellTool && resolvedToolName === "local_shell") { const parsedInput = await 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 && resolvedToolName === "shell") { const parsedInput = await 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 && resolvedToolName === "apply_patch") { const parsedInput = await validateTypes({ value: part.input, schema: applyPatchInputSchema }); input.push({ type: "apply_patch_call", call_id: parsedInput.callId, id, status: "completed", operation: parsedInput.operation }); break; } if (hasComputerTool && resolvedToolName === "computer") { const parsedInput = await validateTypes({ value: part.input, schema: computerInputSchema }); input.push({ type: "computer_call", call_id: part.toolCallId, id, status: parsedInput.status, actions: parsedInput.actions.map((action) => { switch (action.type) { case "click": case "double_click": case "move": return { ...action, keys: action.keys }; case "drag": return { ...action, keys: action.keys }; case "scroll": return { type: "scroll", x: action.x, y: action.y, scroll_x: action.scrollX, scroll_y: action.scrollY, keys: action.keys }; default: return action; } }), pending_safety_checks: parsedInput.pendingSafetyChecks.map( (safetyCheck) => ({ id: safetyCheck.id, code: safetyCheck.code, message: safetyCheck.message }) ) }); break; } if (customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) { input.push({ type: "custom_tool_call", call_id: part.toolCallId, name: resolvedToolName, input: typeof part.input === "string" ? part.input : JSON.stringify(part.input), id }); break; } input.push({ type: "function_call", call_id: part.toolCallId, name: resolvedToolName, arguments: serializeToolCallArguments2(part.input), ...namespace != null && { namespace } }); break; } // assistant tool result parts are from provider-executed tools: case "tool-result": { if (part.output.type === "execution-denied" || part.output.type === "json" && typeof part.output.value === "object" && part.output.value != null && "type" in part.output.value && part.output.value.type === "execution-denied") { break; } if (hasConversation) { break; } const resolvedResultToolName = toolNameMapping.toProviderToolName( part.toolName ); if (resolvedResultToolName === "tool_search") { const itemId = (_p = (_o = (_n3 = part.providerOptions) == null ? void 0 : _n3[providerOptionsName]) == null ? void 0 : _o.itemId) != null ? _p : part.toolCallId; if (store) { input.push({ type: "item_reference", id: itemId }); } else if (part.output.type === "json") { const parsedOutput = await 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 && resolvedResultToolName === "shell") { if (part.output.type === "json") { const parsedOutput = await 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: item.outcome.type === "timeout" ? { type: "timeout" } : { type: "exit", exit_code: item.outcome.exitCode } })) }); } break; } if (store) { const itemId = (_s2 = (_r2 = (_q = part.providerOptions) == null ? void 0 : _q[providerOptionsName]) == null ? void 0 : _r2.itemId) != null ? _s2 : 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 providerOptions2 = await parseProviderOptions({ provider: providerOptionsName, providerOptions: part.providerOptions, schema: openaiResponsesReasoningProviderOptionsSchema }); const reasoningId = providerOptions2 == null ? void 0 : providerOptions2.itemId; if ((hasConversation || hasPreviousResponseId) && reasoningId != null) { break; } if (reasoningId != null) { const reasoningMessage = reasoningMessages[reasoningId]; if (store) { if (reasoningMessage === void 0) { 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 (reasoningMessage !== void 0) { warnings.push({ type: "other", message: `Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(part)}.` }); } if (reasoningMessage === void 0) { reasoningMessages[reasoningId] = { type: "reasoning", id: reasoningId, encrypted_content: providerOptions2 == null ? void 0 : providerOptions2.reasoningEncryptedContent, summary: summaryParts }; input.push(reasoningMessages[reasoningId]); } else { reasoningMessage.summary.push(...summaryParts); if ((providerOptions2 == null ? void 0 : providerOptions2.reasoningEncryptedContent) != null) { reasoningMessage.encrypted_content = providerOptions2.reasoningEncryptedContent; } } } } else { const encryptedContent = providerOptions2 == null ? void 0 : providerOptions2.reasoningEncryptedContent; if (encryptedContent != null) { 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; } case "custom": { if (part.kind === "openai.compaction") { const providerOptions2 = (_t2 = part.providerOptions) == null ? void 0 : _t2[providerOptionsName]; const id = providerOptions2 == null ? void 0 : providerOptions2.itemId; if (hasConversation && id != null) { break; } if (store && id != null) { input.push({ type: "item_reference", id }); break; } const encryptedContent = providerOptions2 == null ? void 0 : providerOptions2.encryptedContent; if (id != null) { input.push({ type: "compaction", id, encrypted_content: encryptedContent }); } } break; } } } break; } case "tool": { for (const part of content) { if (part.type === "tool-approval-response") { 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 (output.type === "execution-denied") { const approvalId = (_v = (_u = output.providerOptions) == null ? void 0 : _u.openai) == null ? void 0 : _v.approvalId; if (approvalId) { continue; } } const resolvedToolName = toolNameMapping.toProviderToolName( part.toolName ); if (resolvedToolName === "tool_search" && output.type === "json") { const parsedOutput = await 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 && resolvedToolName === "local_shell" && output.type === "json") { const parsedOutput = await validateTypes({ value: output.value, schema: localShellOutputSchema }); input.push({ type: "local_shell_call_output", call_id: part.toolCallId, output: parsedOutput.output }); continue; } if (hasShellTool && resolvedToolName === "shell" && output.type === "json") { const parsedOutput = await 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: item.outcome.type === "timeout" ? { type: "timeout" } : { type: "exit", exit_code: item.outcome.exitCode } })) }); continue; } if (hasApplyPatchTool && part.toolName === "apply_patch" && output.type === "json") { const parsedOutput = await 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 (hasComputerTool && resolvedToolName === "computer" && output.type === "json") { const parsedOutput = await validateTypes({ value: output.value, schema: computerOutputSchema }); input.push({ type: "computer_call_output", call_id: part.toolCallId, output: { type: "computer_screenshot", image_url: parsedOutput.output.imageUrl, file_id: parsedOutput.output.fileId, detail: parsedOutput.output.detail }, acknowledged_safety_checks: (_w = parsedOutput.acknowledgedSafetyChecks) == null ? void 0 : _w.map((safetyCheck) => ({ id: safetyCheck.id, code: safetyCheck.code, message: safetyCheck.message })) }); continue; } if (customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) { let outputValue; switch (output.type) { case "text": case "error-text": outputValue = output.value; break; case "execution-denied": outputValue = (_x = output.reason) != null ? _x : "Tool call execution denied."; break; case "json": case "error-json": outputValue = JSON.stringify(output.value); break; case "content": outputValue = output.value.map((item) => { var _a26, _b23, _c2; const promptCacheBreakpoint = getPromptCacheBreakpoint2( item.providerOptions, providerOptionsName ); switch (item.type) { case "text": return { type: "input_text", text: item.text, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; case "file": { const topLevel = getTopLevelMediaType(item.mediaType); const imageDetail = (_b23 = (_a26 = item.providerOptions) == null ? void 0 : _a26[providerOptionsName]) == null ? void 0 : _b23.imageDetail; if (item.data.type === "data") { const fullMediaType = resolveFullMediaType({ part: item }); if (topLevel === "image") { return { type: "input_image", image_url: `data:${fullMediaType};base64,${convertToBase64(item.data.data)}`, detail: imageDetail, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } return { type: "input_file", filename: (_c2 = item.filename) != null ? _c2 : "data", file_data: `data:${fullMediaType};base64,${convertToBase64(item.data.data)}`, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } if (item.data.type === "url") { if (topLevel === "image") { return { type: "input_image", image_url: item.data.url.toString(), detail: imageDetail, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } return { type: "input_file", file_url: item.data.url.toString(), ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } warnings.push({ type: "other", message: `unsupported custom tool content part type: ${item.type} with data type: ${item.data.type}` }); return void 0; } default: warnings.push({ type: "other", message: `unsupported custom tool content part type: ${item.type}` }); return void 0; } }).filter(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 = (_y = output.reason) != null ? _y : "Tool call execution denied."; break; case "json": case "error-json": contentValue = JSON.stringify(output.value); break; case "content": contentValue = output.value.map((item) => { var _a26, _b23, _c2; const promptCacheBreakpoint = getPromptCacheBreakpoint2( item.providerOptions, providerOptionsName ); switch (item.type) { case "text": { return { type: "input_text", text: item.text, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } case "file": { const topLevel = getTopLevelMediaType(item.mediaType); const imageDetail = (_b23 = (_a26 = item.providerOptions) == null ? void 0 : _a26[providerOptionsName]) == null ? void 0 : _b23.imageDetail; if (item.data.type === "data") { const fullMediaType = resolveFullMediaType({ part: item }); if (topLevel === "image") { return { type: "input_image", image_url: `data:${fullMediaType};base64,${convertToBase64(item.data.data)}`, detail: imageDetail, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } return { type: "input_file", filename: (_c2 = item.filename) != null ? _c2 : "data", file_data: `data:${fullMediaType};base64,${convertToBase64(item.data.data)}`, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } if (item.data.type === "url") { if (topLevel === "image") { return { type: "input_image", image_url: item.data.url.toString(), detail: imageDetail, ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } return { type: "input_file", file_url: item.data.url.toString(), ...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint } }; } warnings.push({ type: "other", message: `unsupported tool content part type: ${item.type} with data type: ${item.data.type}` }); return void 0; } default: { warnings.push({ type: "other", message: `unsupported tool content part type: ${item.type}` }); return void 0; } } }).filter(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 && item.type === "reasoning" && item.encrypted_content == null )) { 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) || item.type !== "reasoning" || item.encrypted_content != null ); } return { input, warnings }; } var openaiResponsesReasoningProviderOptionsSchema = external_exports.object({ itemId: external_exports.string().nullish(), reasoningEncryptedContent: external_exports.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 jsonValueSchema22 = external_exports.lazy( () => external_exports.union([ external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null(), external_exports.array(jsonValueSchema22), external_exports.record(external_exports.string(), jsonValueSchema22.optional()) ]) ); var openaiResponsesComputerSafetyCheckSchema = external_exports.object({ id: external_exports.string(), code: external_exports.string().nullish(), message: external_exports.string().nullish() }); var openaiResponsesComputerActionSchema = external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("click"), button: external_exports.enum(["left", "right", "wheel", "back", "forward"]), x: external_exports.number(), y: external_exports.number(), keys: external_exports.array(external_exports.string()).nullish() }), external_exports.object({ type: external_exports.literal("double_click"), x: external_exports.number(), y: external_exports.number(), keys: external_exports.array(external_exports.string()).nullish() }), external_exports.object({ type: external_exports.literal("drag"), path: external_exports.array(external_exports.object({ x: external_exports.number(), y: external_exports.number() })), keys: external_exports.array(external_exports.string()).nullish() }), external_exports.object({ type: external_exports.literal("keypress"), keys: external_exports.array(external_exports.string()) }), external_exports.object({ type: external_exports.literal("move"), x: external_exports.number(), y: external_exports.number(), keys: external_exports.array(external_exports.string()).nullish() }), external_exports.object({ type: external_exports.literal("screenshot") }), external_exports.object({ type: external_exports.literal("scroll"), x: external_exports.number(), y: external_exports.number(), scroll_x: external_exports.number(), scroll_y: external_exports.number(), keys: external_exports.array(external_exports.string()).nullish() }), external_exports.object({ type: external_exports.literal("type"), text: external_exports.string() }), external_exports.object({ type: external_exports.literal("wait") }) ]); var openaiResponsesComputerCallSchema = external_exports.object({ type: external_exports.literal("computer_call"), id: external_exports.string(), call_id: external_exports.string().nullish(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), action: openaiResponsesComputerActionSchema.nullish(), actions: external_exports.array(openaiResponsesComputerActionSchema).nullish(), pending_safety_checks: external_exports.array(openaiResponsesComputerSafetyCheckSchema).nullish() }); var openaiResponsesNestedErrorChunkSchema = external_exports.object({ type: external_exports.literal("error"), sequence_number: external_exports.number(), error: external_exports.object({ type: external_exports.string(), code: external_exports.string(), message: external_exports.string(), param: external_exports.string().nullish() }) }); var openaiResponsesErrorChunkSchema = external_exports.object({ type: external_exports.literal("error"), sequence_number: external_exports.number(), code: external_exports.string().nullish(), message: external_exports.string(), param: external_exports.string().nullish() }); var openaiResponsesChunkSchema = lazySchema( () => zodSchema( external_exports.union([ external_exports.object({ type: external_exports.literal("response.output_text.delta"), item_id: external_exports.string(), delta: external_exports.string(), logprobs: external_exports.array( external_exports.object({ token: external_exports.string(), logprob: external_exports.number(), top_logprobs: external_exports.array( external_exports.object({ token: external_exports.string(), logprob: external_exports.number() }) ) }) ).nullish() }), external_exports.object({ type: external_exports.enum(["response.completed", "response.incomplete"]), response: external_exports.object({ incomplete_details: external_exports.object({ reason: external_exports.string() }).nullish(), usage: external_exports.object({ input_tokens: external_exports.number(), input_tokens_details: external_exports.object({ cached_tokens: external_exports.number().nullish(), cache_write_tokens: external_exports.number().nullish(), orchestration_input_tokens: external_exports.number().nullish(), orchestration_input_cached_tokens: external_exports.number().nullish() }).nullish(), output_tokens: external_exports.number(), output_tokens_details: external_exports.object({ reasoning_tokens: external_exports.number().nullish(), orchestration_output_tokens: external_exports.number().nullish() }).nullish() }), reasoning: external_exports.object({ context: external_exports.string().nullish() }).nullish(), service_tier: external_exports.string().nullish() }) }), external_exports.object({ type: external_exports.literal("response.failed"), sequence_number: external_exports.number(), response: external_exports.object({ error: external_exports.object({ code: external_exports.string().nullish(), message: external_exports.string() }).nullish(), incomplete_details: external_exports.object({ reason: external_exports.string() }).nullish(), usage: external_exports.object({ input_tokens: external_exports.number(), input_tokens_details: external_exports.object({ cached_tokens: external_exports.number().nullish(), cache_write_tokens: external_exports.number().nullish(), orchestration_input_tokens: external_exports.number().nullish(), orchestration_input_cached_tokens: external_exports.number().nullish() }).nullish(), output_tokens: external_exports.number(), output_tokens_details: external_exports.object({ reasoning_tokens: external_exports.number().nullish(), orchestration_output_tokens: external_exports.number().nullish() }).nullish() }).nullish(), reasoning: external_exports.object({ context: external_exports.string().nullish() }).nullish(), service_tier: external_exports.string().nullish() }) }), external_exports.object({ type: external_exports.literal("response.created"), response: external_exports.object({ id: external_exports.string(), created_at: external_exports.number(), model: external_exports.string(), service_tier: external_exports.string().nullish() }) }), external_exports.object({ type: external_exports.literal("response.output_item.added"), output_index: external_exports.number(), item: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("message"), id: external_exports.string(), phase: external_exports.enum(["commentary", "final_answer"]).nullish() }), external_exports.object({ type: external_exports.literal("reasoning"), id: external_exports.string(), encrypted_content: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("function_call"), id: external_exports.string(), call_id: external_exports.string(), name: external_exports.string(), arguments: external_exports.string(), namespace: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("web_search_call"), id: external_exports.string(), status: external_exports.string() }), openaiResponsesComputerCallSchema, external_exports.object({ type: external_exports.literal("file_search_call"), id: external_exports.string() }), external_exports.object({ type: external_exports.literal("image_generation_call"), id: external_exports.string() }), external_exports.object({ type: external_exports.literal("code_interpreter_call"), id: external_exports.string(), container_id: external_exports.string(), code: external_exports.string().nullable(), outputs: external_exports.array( external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("logs"), logs: external_exports.string() }), external_exports.object({ type: external_exports.literal("image"), url: external_exports.string() }) ]) ).nullable(), status: external_exports.string() }), external_exports.object({ type: external_exports.literal("mcp_call"), id: external_exports.string(), status: external_exports.string(), approval_request_id: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("mcp_list_tools"), id: external_exports.string() }), external_exports.object({ type: external_exports.literal("mcp_approval_request"), id: external_exports.string() }), external_exports.object({ type: external_exports.literal("apply_patch_call"), id: external_exports.string(), call_id: external_exports.string(), status: external_exports.enum(["in_progress", "completed"]), operation: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("create_file"), path: external_exports.string(), diff: external_exports.string() }), external_exports.object({ type: external_exports.literal("delete_file"), path: external_exports.string() }), external_exports.object({ type: external_exports.literal("update_file"), path: external_exports.string(), diff: external_exports.string() }) ]) }), external_exports.object({ type: external_exports.literal("custom_tool_call"), id: external_exports.string(), call_id: external_exports.string(), name: external_exports.string(), input: external_exports.string() }), external_exports.object({ type: external_exports.literal("shell_call"), id: external_exports.string(), call_id: external_exports.string(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), action: external_exports.object({ commands: external_exports.array(external_exports.string()) }) }), external_exports.object({ type: external_exports.literal("compaction"), id: external_exports.string(), encrypted_content: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("shell_call_output"), id: external_exports.string(), call_id: external_exports.string(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), output: external_exports.array( external_exports.object({ stdout: external_exports.string(), stderr: external_exports.string(), outcome: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("timeout") }), external_exports.object({ type: external_exports.literal("exit"), exit_code: external_exports.number() }) ]) }) ) }), external_exports.object({ type: external_exports.literal("tool_search_call"), id: external_exports.string(), execution: external_exports.enum(["server", "client"]), call_id: external_exports.string().nullable(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), arguments: external_exports.unknown() }), external_exports.object({ type: external_exports.literal("tool_search_output"), id: external_exports.string(), execution: external_exports.enum(["server", "client"]), call_id: external_exports.string().nullable(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), tools: external_exports.array(external_exports.record(external_exports.string(), jsonValueSchema22.optional())) }) ]) }), external_exports.object({ type: external_exports.literal("response.output_item.done"), output_index: external_exports.number(), item: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("message"), id: external_exports.string(), phase: external_exports.enum(["commentary", "final_answer"]).nullish() }), external_exports.object({ type: external_exports.literal("reasoning"), id: external_exports.string(), encrypted_content: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("function_call"), id: external_exports.string(), call_id: external_exports.string(), name: external_exports.string(), arguments: external_exports.string(), status: external_exports.literal("completed"), namespace: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("custom_tool_call"), id: external_exports.string(), call_id: external_exports.string(), name: external_exports.string(), input: external_exports.string(), status: external_exports.literal("completed") }), external_exports.object({ type: external_exports.literal("code_interpreter_call"), id: external_exports.string(), code: external_exports.string().nullable(), container_id: external_exports.string(), outputs: external_exports.array( external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("logs"), logs: external_exports.string() }), external_exports.object({ type: external_exports.literal("image"), url: external_exports.string() }) ]) ).nullable() }), external_exports.object({ type: external_exports.literal("image_generation_call"), id: external_exports.string(), result: external_exports.string() }), external_exports.object({ type: external_exports.literal("web_search_call"), id: external_exports.string(), status: external_exports.string(), action: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("search"), query: external_exports.string().nullish(), queries: external_exports.array(external_exports.string()).nullish(), sources: external_exports.array( external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("url"), url: external_exports.string() }), external_exports.object({ type: external_exports.literal("api"), name: external_exports.string() }) ]) ).nullish() }), external_exports.object({ type: external_exports.literal("open_page"), url: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("find_in_page"), url: external_exports.string().nullish(), pattern: external_exports.string().nullish() }) ]).nullish() }), external_exports.object({ type: external_exports.literal("file_search_call"), id: external_exports.string(), queries: external_exports.array(external_exports.string()), results: external_exports.array( external_exports.object({ attributes: external_exports.record( external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]) ), file_id: external_exports.string(), filename: external_exports.string(), score: external_exports.number(), text: external_exports.string() }) ).nullish() }), external_exports.object({ type: external_exports.literal("local_shell_call"), id: external_exports.string(), call_id: external_exports.string(), action: external_exports.object({ type: external_exports.literal("exec"), command: external_exports.array(external_exports.string()), timeout_ms: external_exports.number().optional(), user: external_exports.string().optional(), working_directory: external_exports.string().optional(), env: external_exports.record(external_exports.string(), external_exports.string()).optional() }) }), openaiResponsesComputerCallSchema, external_exports.object({ type: external_exports.literal("mcp_call"), id: external_exports.string(), status: external_exports.string(), arguments: external_exports.string(), name: external_exports.string(), server_label: external_exports.string(), output: external_exports.string().nullish(), error: external_exports.union([ external_exports.string(), external_exports.object({ type: external_exports.string().optional(), code: external_exports.union([external_exports.number(), external_exports.string()]).optional(), message: external_exports.string().optional() }).loose() ]).nullish(), approval_request_id: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("mcp_list_tools"), id: external_exports.string(), server_label: external_exports.string(), tools: external_exports.array( external_exports.object({ name: external_exports.string(), description: external_exports.string().optional(), input_schema: external_exports.any(), annotations: external_exports.record(external_exports.string(), external_exports.unknown()).optional() }) ), error: external_exports.union([ external_exports.string(), external_exports.object({ type: external_exports.string().optional(), code: external_exports.union([external_exports.number(), external_exports.string()]).optional(), message: external_exports.string().optional() }).loose() ]).optional() }), external_exports.object({ type: external_exports.literal("mcp_approval_request"), id: external_exports.string(), server_label: external_exports.string(), name: external_exports.string(), arguments: external_exports.string(), approval_request_id: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("apply_patch_call"), id: external_exports.string(), call_id: external_exports.string(), status: external_exports.enum(["in_progress", "completed"]), operation: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("create_file"), path: external_exports.string(), diff: external_exports.string() }), external_exports.object({ type: external_exports.literal("delete_file"), path: external_exports.string() }), external_exports.object({ type: external_exports.literal("update_file"), path: external_exports.string(), diff: external_exports.string() }) ]) }), external_exports.object({ type: external_exports.literal("shell_call"), id: external_exports.string(), call_id: external_exports.string(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), action: external_exports.object({ commands: external_exports.array(external_exports.string()) }) }), external_exports.object({ type: external_exports.literal("compaction"), id: external_exports.string(), encrypted_content: external_exports.string() }), external_exports.object({ type: external_exports.literal("shell_call_output"), id: external_exports.string(), call_id: external_exports.string(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), output: external_exports.array( external_exports.object({ stdout: external_exports.string(), stderr: external_exports.string(), outcome: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("timeout") }), external_exports.object({ type: external_exports.literal("exit"), exit_code: external_exports.number() }) ]) }) ) }), external_exports.object({ type: external_exports.literal("tool_search_call"), id: external_exports.string(), execution: external_exports.enum(["server", "client"]), call_id: external_exports.string().nullable(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), arguments: external_exports.unknown() }), external_exports.object({ type: external_exports.literal("tool_search_output"), id: external_exports.string(), execution: external_exports.enum(["server", "client"]), call_id: external_exports.string().nullable(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), tools: external_exports.array(external_exports.record(external_exports.string(), jsonValueSchema22.optional())) }) ]) }), external_exports.object({ type: external_exports.literal("response.function_call_arguments.delta"), item_id: external_exports.string(), output_index: external_exports.number(), delta: external_exports.string() }), external_exports.object({ type: external_exports.literal("response.custom_tool_call_input.delta"), item_id: external_exports.string(), output_index: external_exports.number(), delta: external_exports.string() }), external_exports.object({ type: external_exports.literal("response.image_generation_call.partial_image"), item_id: external_exports.string(), output_index: external_exports.number(), partial_image_b64: external_exports.string() }), external_exports.object({ type: external_exports.literal("response.code_interpreter_call_code.delta"), item_id: external_exports.string(), output_index: external_exports.number(), delta: external_exports.string() }), external_exports.object({ type: external_exports.literal("response.code_interpreter_call_code.done"), item_id: external_exports.string(), output_index: external_exports.number(), code: external_exports.string() }), external_exports.object({ type: external_exports.literal("response.output_text.annotation.added"), annotation: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("url_citation"), start_index: external_exports.number(), end_index: external_exports.number(), url: external_exports.string(), title: external_exports.string() }), external_exports.object({ type: external_exports.literal("file_citation"), file_id: external_exports.string(), filename: external_exports.string(), index: external_exports.number() }), external_exports.object({ type: external_exports.literal("container_file_citation"), container_id: external_exports.string(), file_id: external_exports.string(), filename: external_exports.string(), start_index: external_exports.number(), end_index: external_exports.number() }), external_exports.object({ type: external_exports.literal("file_path"), file_id: external_exports.string(), index: external_exports.number() }) ]) }), external_exports.object({ type: external_exports.literal("response.reasoning_summary_part.added"), item_id: external_exports.string(), summary_index: external_exports.number() }), external_exports.object({ type: external_exports.literal("response.reasoning_summary_text.delta"), item_id: external_exports.string(), summary_index: external_exports.number(), delta: external_exports.string() }), external_exports.object({ type: external_exports.literal("response.reasoning_summary_part.done"), item_id: external_exports.string(), summary_index: external_exports.number() }), external_exports.object({ type: external_exports.literal("response.apply_patch_call_operation_diff.delta"), item_id: external_exports.string(), output_index: external_exports.number(), delta: external_exports.string(), obfuscation: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("response.apply_patch_call_operation_diff.done"), item_id: external_exports.string(), output_index: external_exports.number(), diff: external_exports.string() }), openaiResponsesNestedErrorChunkSchema, openaiResponsesErrorChunkSchema, external_exports.object({ type: external_exports.string() }).loose().transform((value) => ({ type: "unknown_chunk", message: value.type })) // fallback for unknown chunks ]) ) ); var openaiResponsesResponseSchema = lazySchema( () => zodSchema( external_exports.object({ id: external_exports.string().optional(), created_at: external_exports.number().optional(), error: external_exports.object({ message: external_exports.string(), type: external_exports.string(), param: external_exports.string().nullish(), code: external_exports.string() }).nullish(), model: external_exports.string().optional(), output: external_exports.array( external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("message"), role: external_exports.literal("assistant"), id: external_exports.string(), phase: external_exports.enum(["commentary", "final_answer"]).nullish(), content: external_exports.array( external_exports.object({ type: external_exports.literal("output_text"), text: external_exports.string(), logprobs: external_exports.array( external_exports.object({ token: external_exports.string(), logprob: external_exports.number(), top_logprobs: external_exports.array( external_exports.object({ token: external_exports.string(), logprob: external_exports.number() }) ) }) ).nullish(), annotations: external_exports.array( external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("url_citation"), start_index: external_exports.number(), end_index: external_exports.number(), url: external_exports.string(), title: external_exports.string() }), external_exports.object({ type: external_exports.literal("file_citation"), file_id: external_exports.string(), filename: external_exports.string(), index: external_exports.number() }), external_exports.object({ type: external_exports.literal("container_file_citation"), container_id: external_exports.string(), file_id: external_exports.string(), filename: external_exports.string(), start_index: external_exports.number(), end_index: external_exports.number() }), external_exports.object({ type: external_exports.literal("file_path"), file_id: external_exports.string(), index: external_exports.number() }) ]) ) }) ) }), external_exports.object({ type: external_exports.literal("web_search_call"), id: external_exports.string(), status: external_exports.string(), action: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("search"), query: external_exports.string().nullish(), queries: external_exports.array(external_exports.string()).nullish(), sources: external_exports.array( external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("url"), url: external_exports.string() }), external_exports.object({ type: external_exports.literal("api"), name: external_exports.string() }) ]) ).nullish() }), external_exports.object({ type: external_exports.literal("open_page"), url: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("find_in_page"), url: external_exports.string().nullish(), pattern: external_exports.string().nullish() }) ]).nullish() }), external_exports.object({ type: external_exports.literal("file_search_call"), id: external_exports.string(), queries: external_exports.array(external_exports.string()), results: external_exports.array( external_exports.object({ attributes: external_exports.record( external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]) ), file_id: external_exports.string(), filename: external_exports.string(), score: external_exports.number(), text: external_exports.string() }) ).nullish() }), external_exports.object({ type: external_exports.literal("code_interpreter_call"), id: external_exports.string(), code: external_exports.string().nullable(), container_id: external_exports.string(), outputs: external_exports.array( external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("logs"), logs: external_exports.string() }), external_exports.object({ type: external_exports.literal("image"), url: external_exports.string() }) ]) ).nullable() }), external_exports.object({ type: external_exports.literal("image_generation_call"), id: external_exports.string(), result: external_exports.string() }), external_exports.object({ type: external_exports.literal("local_shell_call"), id: external_exports.string(), call_id: external_exports.string(), action: external_exports.object({ type: external_exports.literal("exec"), command: external_exports.array(external_exports.string()), timeout_ms: external_exports.number().optional(), user: external_exports.string().optional(), working_directory: external_exports.string().optional(), env: external_exports.record(external_exports.string(), external_exports.string()).optional() }) }), external_exports.object({ type: external_exports.literal("function_call"), call_id: external_exports.string(), name: external_exports.string(), arguments: external_exports.string(), id: external_exports.string(), namespace: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("custom_tool_call"), call_id: external_exports.string(), name: external_exports.string(), input: external_exports.string(), id: external_exports.string() }), openaiResponsesComputerCallSchema, external_exports.object({ type: external_exports.literal("reasoning"), id: external_exports.string(), encrypted_content: external_exports.string().nullish(), summary: external_exports.array( external_exports.object({ type: external_exports.literal("summary_text"), text: external_exports.string() }) ) }), external_exports.object({ type: external_exports.literal("mcp_call"), id: external_exports.string(), status: external_exports.string(), arguments: external_exports.string(), name: external_exports.string(), server_label: external_exports.string(), output: external_exports.string().nullish(), error: external_exports.union([ external_exports.string(), external_exports.object({ type: external_exports.string().optional(), code: external_exports.union([external_exports.number(), external_exports.string()]).optional(), message: external_exports.string().optional() }).loose() ]).nullish(), approval_request_id: external_exports.string().nullish() }), external_exports.object({ type: external_exports.literal("mcp_list_tools"), id: external_exports.string(), server_label: external_exports.string(), tools: external_exports.array( external_exports.object({ name: external_exports.string(), description: external_exports.string().optional(), input_schema: external_exports.any(), annotations: external_exports.record(external_exports.string(), external_exports.unknown()).optional() }) ), error: external_exports.union([ external_exports.string(), external_exports.object({ type: external_exports.string().optional(), code: external_exports.union([external_exports.number(), external_exports.string()]).optional(), message: external_exports.string().optional() }).loose() ]).optional() }), external_exports.object({ type: external_exports.literal("mcp_approval_request"), id: external_exports.string(), server_label: external_exports.string(), name: external_exports.string(), arguments: external_exports.string(), approval_request_id: external_exports.string().optional() }), external_exports.object({ type: external_exports.literal("apply_patch_call"), id: external_exports.string(), call_id: external_exports.string(), status: external_exports.enum(["in_progress", "completed"]), operation: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("create_file"), path: external_exports.string(), diff: external_exports.string() }), external_exports.object({ type: external_exports.literal("delete_file"), path: external_exports.string() }), external_exports.object({ type: external_exports.literal("update_file"), path: external_exports.string(), diff: external_exports.string() }) ]) }), external_exports.object({ type: external_exports.literal("shell_call"), id: external_exports.string(), call_id: external_exports.string(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), action: external_exports.object({ commands: external_exports.array(external_exports.string()) }) }), external_exports.object({ type: external_exports.literal("compaction"), id: external_exports.string(), encrypted_content: external_exports.string() }), external_exports.object({ type: external_exports.literal("shell_call_output"), id: external_exports.string(), call_id: external_exports.string(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), output: external_exports.array( external_exports.object({ stdout: external_exports.string(), stderr: external_exports.string(), outcome: external_exports.discriminatedUnion("type", [ external_exports.object({ type: external_exports.literal("timeout") }), external_exports.object({ type: external_exports.literal("exit"), exit_code: external_exports.number() }) ]) }) ) }), external_exports.object({ type: external_exports.literal("tool_search_call"), id: external_exports.string(), execution: external_exports.enum(["server", "client"]), call_id: external_exports.string().nullable(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), arguments: external_exports.unknown() }), external_exports.object({ type: external_exports.literal("tool_search_output"), id: external_exports.string(), execution: external_exports.enum(["server", "client"]), call_id: external_exports.string().nullable(), status: external_exports.enum(["in_progress", "completed", "incomplete"]), tools: external_exports.array(external_exports.record(external_exports.string(), jsonValueSchema22.optional())) }) ]) ).optional(), service_tier: external_exports.string().nullish(), reasoning: external_exports.object({ context: external_exports.string().nullish() }).nullish(), incomplete_details: external_exports.object({ reason: external_exports.string() }).nullish(), usage: external_exports.object({ input_tokens: external_exports.number(), input_tokens_details: external_exports.object({ cached_tokens: external_exports.number().nullish(), cache_write_tokens: external_exports.number().nullish(), orchestration_input_tokens: external_exports.number().nullish(), orchestration_input_cached_tokens: external_exports.number().nullish() }).nullish(), output_tokens: external_exports.number(), output_tokens_details: external_exports.object({ reasoning_tokens: external_exports.number().nullish(), orchestration_output_tokens: external_exports.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", "gpt-5.5", "gpt-5.5-2026-04-23", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra" ]; var openaiResponsesModelIds = [ "gpt-4.1", "gpt-4.1-2025-04-14", "gpt-4.1-mini", "gpt-4.1-mini-2025-04-14", "gpt-4.1-nano", "gpt-4.1-nano-2025-04-14", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-2024-11-20", "gpt-4o-audio-preview", "gpt-4o-audio-preview-2024-12-17", "gpt-4o-search-preview", "gpt-4o-search-preview-2025-03-11", "gpt-4o-mini-search-preview", "gpt-4o-mini-search-preview-2025-03-11", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", "gpt-3.5-turbo-0125", "gpt-3.5-turbo", "gpt-3.5-turbo-1106", "gpt-5-chat-latest", ...openaiResponsesReasoningModelIds ]; var openaiLanguageModelResponsesOptionsSchema = lazySchema( () => zodSchema( external_exports.object({ /** * The ID of the OpenAI Conversation to continue. * You must create a conversation first via the OpenAI API. * Cannot be used in conjunction with `previousResponseId`. * Defaults to `undefined`. * @see https://platform.openai.com/docs/api-reference/conversations/create */ conversation: external_exports.string().nullish(), /** * The set of extra fields to include in the response (advanced, usually not needed). * Example values: 'reasoning.encrypted_content', 'file_search_call.results', 'web_search_call.results', 'message.output_text.logprobs'. */ include: external_exports.array( external_exports.enum([ "reasoning.encrypted_content", // handled internally by default, only needed for unknown reasoning models "file_search_call.results", "web_search_call.results", "message.output_text.logprobs" ]) ).nullish(), /** * Instructions for the model. * They can be used to change the system or developer message when continuing a conversation using the `previousResponseId` option. * Defaults to `undefined`. */ instructions: external_exports.string().nullish(), /** * Return the log probabilities of the tokens. Including logprobs will increase * the response size and can slow down response times. However, it can * be useful to better understand how the model is behaving. * * Setting to true will return the log probabilities of the tokens that * were generated. * * Setting to a number will return the log probabilities of the top n * tokens that were generated. * * @see https://platform.openai.com/docs/api-reference/responses/create * @see https://cookbook.openai.com/examples/using_logprobs */ logprobs: external_exports.union([external_exports.boolean(), external_exports.number().min(1).max(TOP_LOGPROBS_MAX)]).optional(), /** * The maximum number of total calls to built-in tools that can be processed in a response. * This maximum number applies across all built-in tool calls, not per individual tool. * Any further attempts to call a tool by the model will be ignored. */ maxToolCalls: external_exports.number().nullish(), /** * Additional metadata to store with the generation. */ metadata: external_exports.any().nullish(), /** * Whether to use parallel tool calls. Defaults to `true`. */ parallelToolCalls: external_exports.boolean().nullish(), /** * The ID of the previous response. You can use it to continue a conversation. * Defaults to `undefined`. */ previousResponseId: external_exports.string().nullish(), /** * Sets a cache key to tie this prompt to cached prefixes for better caching performance. */ promptCacheKey: external_exports.string().nullish(), /** * Prompt cache behavior for GPT-5.6 and later models. * `mode` controls whether OpenAI also places an implicit breakpoint. * `ttl` sets the minimum cache lifetime and currently only supports 30 minutes. */ promptCacheOptions: external_exports.object({ mode: external_exports.enum(["implicit", "explicit"]).optional(), ttl: external_exports.literal("30m").optional() }).optional(), /** * The retention policy for the prompt cache. * - 'in_memory': Default. Standard prompt caching behavior. * - '24h': Extended prompt caching that keeps cached prefixes active for up to 24 hours. * Available for models before GPT-5.6 that support extended caching. * * @deprecated For GPT-5.6 and later models, use `promptCacheOptions.ttl`. * * @default 'in_memory' */ promptCacheRetention: external_exports.enum(["in_memory", "24h"]).nullish(), /** * Reasoning effort for reasoning models. Defaults to `medium`. If you use * `providerOptions` to set the `reasoningEffort` option, this model setting will be ignored. * GPT-5.6 supports 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'. * Supported values vary by model. */ reasoningEffort: external_exports.string().nullish(), /** * Controls how much model work GPT-5.6 performs before returning a final answer. * `standard` is the default. `pro` increases quality, latency, and token usage. */ reasoningMode: external_exports.enum(["standard", "pro"]).optional(), /** * Controls which available reasoning items GPT-5.6 can use. * `auto` uses the model default, `current_turn` excludes reasoning from earlier * turns, and `all_turns` makes compatible earlier reasoning available. */ reasoningContext: external_exports.enum(["auto", "current_turn", "all_turns"]).optional(), /** * Controls reasoning summary output from the model. * Set to "auto" to automatically receive the richest level available, * or "detailed" for comprehensive summaries. */ reasoningSummary: external_exports.string().nullish(), /** * The identifier for safety monitoring and tracking. */ safetyIdentifier: external_exports.string().nullish(), /** * Service tier for the request. * Set to 'flex' for 50% cheaper processing at the cost of increased latency (available for o3, o4-mini, and gpt-5 models). * Set to 'priority' for faster processing with Enterprise access (available for gpt-4, gpt-5, gpt-5-mini, o3, o4-mini; gpt-5-nano is not supported). * * Defaults to 'auto'. */ serviceTier: external_exports.enum(["auto", "flex", "priority", "default"]).nullish(), /** * Whether to store the generation. Defaults to `true`. */ store: external_exports.boolean().nullish(), /** * Whether to pass through non-image file types as generic input files. * * By default, inline file inputs are restricted to images and PDFs. * Enable this when the target OpenAI Responses model supports additional * file media types, such as text/csv. */ passThroughUnsupportedFiles: external_exports.boolean().optional(), /** * Whether to use strict JSON schema validation. * Defaults to `true`. */ strictJsonSchema: external_exports.boolean().nullish(), /** * Controls the verbosity of the model's responses. Lower values ('low') will result * in more concise responses, while higher values ('high') will result in more verbose responses. * Valid values: 'low', 'medium', 'high'. */ textVerbosity: external_exports.enum(["low", "medium", "high"]).nullish(), /** * Controls output truncation. 'auto' (default) performs truncation automatically; * 'disabled' turns truncation off. */ truncation: external_exports.enum(["auto", "disabled"]).nullish(), /** * A unique identifier representing your end-user, which can help OpenAI to * monitor and detect abuse. * Defaults to `undefined`. * @see https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids */ user: external_exports.string().nullish(), /** * Override the system message mode for this model. * - 'system': Use the 'system' role for system messages (default for most models) * - 'developer': Use the 'developer' role for system messages (used by reasoning models) * - 'remove': Remove system messages entirely * * If not specified, the mode is automatically determined based on the model. */ systemMessageMode: external_exports.enum(["system", "developer", "remove"]).optional(), /** * Force treating this model as a reasoning model. * * This is useful for "stealth" reasoning models (e.g. via a custom baseURL) * where the model ID is not recognized by the SDK's allowlist. * * When enabled, the SDK applies reasoning-model parameter compatibility rules * and defaults `systemMessageMode` to `developer` unless overridden. */ forceReasoning: external_exports.boolean().optional(), /** * Enable server-side context management (compaction). */ contextManagement: external_exports.array( external_exports.object({ type: external_exports.literal("compaction"), compactThreshold: external_exports.number() }) ).nullish(), /** * Restrict the callable tools to a subset while keeping the full tools * list intact, so prompt caching is preserved across requests with * different allowlists. * * When set, this overrides the request-level `toolChoice` and emits * `tool_choice: { type: "allowed_tools", mode, tools }` on the wire. * * @see https://developers.openai.com/api/reference/resources/responses/methods/create#(resource)%20responses%20%3E%20(model)%20tool_choice_allowed%20%3E%20(schema) */ allowedTools: external_exports.object({ toolNames: external_exports.array(external_exports.string()).min(1), mode: external_exports.enum(["auto", "required"]).optional() }).optional() }) ) ); async function prepareResponsesTools({ tools: tools2, toolChoice, allowedTools, toolNameMapping, customProviderToolNames }) { var _a25, _b19, _c; tools2 = (tools2 == null ? void 0 : tools2.length) ? tools2 : void 0; const toolWarnings = []; if (tools2 == null) { return { tools: void 0, toolChoice: void 0, toolWarnings }; } const openaiTools2 = []; const namespaceTools = /* @__PURE__ */ new Map(); const resolvedCustomProviderToolNames = customProviderToolNames != null ? customProviderToolNames : /* @__PURE__ */ new Set(); for (const tool2 of tools2) { switch (tool2.type) { case "function": { const openaiOptions = (_a25 = tool2.providerOptions) == null ? void 0 : _a25.openai; const openaiFunctionTool = prepareFunctionTool({ tool: tool2, options: openaiOptions }); const namespace = openaiOptions == null ? void 0 : openaiOptions.namespace; if (namespace == null) { openaiTools2.push(openaiFunctionTool); } else { let namespaceTool = namespaceTools.get(namespace.name); if (namespaceTool == null) { namespaceTool = { type: "namespace", name: namespace.name, description: namespace.description, tools: [] }; namespaceTools.set(namespace.name, namespaceTool); openaiTools2.push(namespaceTool); } else if (namespaceTool.description !== namespace.description) { throw new UnsupportedFunctionalityError({ functionality: `conflicting descriptions for OpenAI tool namespace "${namespace.name}"` }); } namespaceTool.tools.push(openaiFunctionTool); } break; } case "provider": { switch (tool2.id) { case "openai.file_search": { const args = await validateTypes({ value: tool2.args, schema: 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 validateTypes({ value: tool2.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.computer": { openaiTools2.push({ type: "computer" }); break; } case "openai.web_search_preview": { const args = await validateTypes({ value: tool2.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 validateTypes({ value: tool2.args, schema: webSearchArgsSchema }); openaiTools2.push({ type: "web_search", filters: args.filters != null ? { 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 validateTypes({ value: tool2.args, schema: codeInterpreterArgsSchema }); openaiTools2.push({ type: "code_interpreter", container: args.container == null ? { type: "auto", file_ids: void 0 } : typeof args.container === "string" ? args.container : { type: "auto", file_ids: args.container.fileIds } }); break; } case "openai.image_generation": { const args = await validateTypes({ value: tool2.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 validateTypes({ value: tool2.args, schema: mcpArgsSchema }); const mapApprovalFilter = (filter2) => ({ tool_names: filter2.toolNames }); const requireApproval = args.requireApproval; const requireApprovalParam = requireApproval == null ? void 0 : typeof requireApproval === "string" ? requireApproval : requireApproval.never != null ? { 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: requireApprovalParam != null ? requireApprovalParam : "never", server_description: args.serverDescription, server_url: args.serverUrl }); break; } case "openai.custom": { const args = await validateTypes({ value: tool2.args, schema: customArgsSchema }); openaiTools2.push({ type: "custom", name: tool2.name, description: args.description, format: args.format }); resolvedCustomProviderToolNames.add(tool2.name); break; } case "openai.tool_search": { const args = await validateTypes({ value: tool2.args, schema: toolSearchArgsSchema }); openaiTools2.push({ type: "tool_search", ...args.execution != null ? { execution: args.execution } : {}, ...args.description != null ? { description: args.description } : {}, ...args.parameters != null ? { parameters: args.parameters } : {} }); break; } } break; } default: toolWarnings.push({ type: "unsupported", feature: `function tool ${tool2}` }); break; } } if (allowedTools != null) { return { tools: openaiTools2, toolChoice: { type: "allowed_tools", mode: (_b19 = allowedTools.mode) != null ? _b19 : "auto", tools: allowedTools.toolNames.map((name24) => { var _a26; return { type: "function", name: (_a26 = toolNameMapping == null ? void 0 : toolNameMapping.toProviderToolName(name24)) != null ? _a26 : name24 }; }) }, toolWarnings }; } if (toolChoice == null) { 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 = (_c = toolNameMapping == null ? void 0 : toolNameMapping.toProviderToolName(toolChoice.toolName)) != null ? _c : toolChoice.toolName; return { tools: openaiTools2, toolChoice: resolvedToolName === "code_interpreter" || resolvedToolName === "file_search" || resolvedToolName === "image_generation" || resolvedToolName === "web_search_preview" || resolvedToolName === "web_search" || resolvedToolName === "mcp" || resolvedToolName === "apply_patch" || resolvedToolName === "computer" ? { 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 prepareFunctionTool({ tool: tool2, options }) { const deferLoading = options == null ? void 0 : options.deferLoading; return { type: "function", name: tool2.name, description: tool2.description, parameters: tool2.inputSchema, ...tool2.strict != null ? { strict: tool2.strict } : {}, ...deferLoading != null ? { defer_loading: deferLoading } : {} }; } function mapShellEnvironment(environment) { if (environment.type === "containerReference") { const env2 = environment; return { type: "container_reference", container_id: env2.containerId }; } if (environment.type === "containerAuto") { const env2 = environment; return { type: "container_auto", file_ids: env2.fileIds, memory_limit: env2.memoryLimit, network_policy: env2.networkPolicy == null ? void 0 : env2.networkPolicy.type === "disabled" ? { 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 skills == null ? void 0 : skills.map( (skill) => { var _a25, _b19; return skill.type === "skillReference" ? { type: "skill_reference", skill_id: resolveProviderReference({ reference: (_a25 = skill.providerReference) != null ? _a25 : {}, provider: "openai" }), version: (_b19 = skill.version) != null ? _b19 : "latest" } : { type: "inline", name: skill.name, description: skill.description, source: { type: "base64", media_type: skill.source.mediaType, data: skill.source.data } }; } ); } function extractApprovalRequestIdToToolCallIdMapping(prompt) { var _a25, _b19; const mapping = {}; for (const message of prompt) { if (message.role !== "assistant") continue; for (const part of message.content) { if (part.type !== "tool-call") continue; const approvalRequestId = (_b19 = (_a25 = part.providerOptions) == null ? void 0 : _a25.openai) == null ? void 0 : _b19.approvalRequestId; if (approvalRequestId != null) { mapping[approvalRequestId] = part.toolCallId; } } } return mapping; } function mapComputerAction(action) { switch (action.type) { case "click": return { type: "click", button: action.button, x: action.x, y: action.y, ...action.keys != null && { keys: action.keys } }; case "double_click": return { type: "double_click", x: action.x, y: action.y, ...action.keys != null && { keys: action.keys } }; case "drag": return { type: "drag", path: action.path, ...action.keys != null && { keys: action.keys } }; case "keypress": return action; case "move": return { type: "move", x: action.x, y: action.y, ...action.keys != null && { keys: action.keys } }; case "screenshot": return action; case "scroll": return { type: "scroll", x: action.x, y: action.y, scrollX: action.scroll_x, scrollY: action.scroll_y, ...action.keys != null && { keys: action.keys } }; case "type": return action; case "wait": return action; } } function mapComputerCallInput({ action, actions, pending_safety_checks, status }) { var _a25; return { actions: (actions != null ? actions : action != null ? [action] : []).map( mapComputerAction ), pendingSafetyChecks: (_a25 = pending_safety_checks == null ? void 0 : pending_safety_checks.map((safetyCheck) => ({ id: safetyCheck.id, ...safetyCheck.code != null && { code: safetyCheck.code }, ...safetyCheck.message != null && { message: safetyCheck.message } }))) != null ? _a25 : [], status }; } var OpenAIResponsesLanguageModel = class _OpenAIResponsesLanguageModel { constructor(modelId, config2) { this.specificationVersion = "v4"; this.supportedUrls = { "image/*": [/^https?:\/\/.*$/], "application/pdf": [/^https?:\/\/.*$/] }; this.modelId = modelId; this.config = config2; } static [WORKFLOW_SERIALIZE](model) { return serializeModelOptions({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE](options) { return new _OpenAIResponsesLanguageModel(options.modelId, options.config); } get provider() { return this.config.provider; } async getArgs({ maxOutputTokens, temperature, stopSequences, topP, topK, presencePenalty, frequencyPenalty, seed, prompt, reasoning, providerOptions, tools: tools2, toolChoice, responseFormat }) { var _a25, _b19, _c, _d, _e2, _f, _g, _h, _i2, _j, _k, _l; const warnings = []; const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId); if (topK != null) { warnings.push({ type: "unsupported", feature: "topK" }); } if (seed != null) { warnings.push({ type: "unsupported", feature: "seed" }); } if (presencePenalty != null) { warnings.push({ type: "unsupported", feature: "presencePenalty" }); } if (frequencyPenalty != null) { warnings.push({ type: "unsupported", feature: "frequencyPenalty" }); } if (stopSequences != null) { 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 (openaiOptions == null && providerOptionsName !== "openai") { openaiOptions = await parseProviderOptions({ provider: "openai", providerOptions, schema: openaiLanguageModelResponsesOptionsSchema }); } const resolvedReasoningEffort = (_a25 = openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null ? _a25 : isCustomReasoning(reasoning) ? reasoning : void 0; const resolvedReasoningSummary = (openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) !== void 0 ? openaiOptions.reasoningSummary : resolvedReasoningEffort != null && resolvedReasoningEffort !== "none" ? "detailed" : void 0; const isReasoningModel = (_b19 = openaiOptions == null ? void 0 : openaiOptions.forceReasoning) != null ? _b19 : modelCapabilities.isReasoningModel; if ((openaiOptions == null ? void 0 : openaiOptions.conversation) && (openaiOptions == null ? void 0 : openaiOptions.previousResponseId)) { warnings.push({ type: "unsupported", feature: "conversation", details: "conversation and previousResponseId cannot be used together" }); } const toolNameMapping = createToolNameMapping({ tools: tools2, providerToolNames: { "openai.code_interpreter": "code_interpreter", "openai.computer": "computer", "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" } }); const customProviderToolNames = /* @__PURE__ */ new Set(); const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = await prepareResponsesTools({ tools: tools2, toolChoice, allowedTools: (_c = openaiOptions == null ? void 0 : openaiOptions.allowedTools) != null ? _c : void 0, toolNameMapping, customProviderToolNames }); const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({ prompt, toolNameMapping, systemMessageMode: (_d = openaiOptions == null ? void 0 : openaiOptions.systemMessageMode) != null ? _d : isReasoningModel ? "developer" : modelCapabilities.systemMessageMode, providerOptionsName, fileIdPrefixes: this.config.fileIdPrefixes, passThroughUnsupportedFiles: (_e2 = openaiOptions == null ? void 0 : openaiOptions.passThroughUnsupportedFiles) != null ? _e2 : false, store: (_f = openaiOptions == null ? void 0 : openaiOptions.store) != null ? _f : true, hasConversation: (openaiOptions == null ? void 0 : openaiOptions.conversation) != null, hasPreviousResponseId: (openaiOptions == null ? void 0 : openaiOptions.previousResponseId) != null, hasLocalShellTool: hasOpenAITool("openai.local_shell"), hasShellTool: hasOpenAITool("openai.shell"), hasApplyPatchTool: hasOpenAITool("openai.apply_patch"), hasComputerTool: hasOpenAITool("openai.computer"), customProviderToolNames: customProviderToolNames.size > 0 ? customProviderToolNames : void 0 }); warnings.push(...inputWarnings); const strictJsonSchema = (_g = openaiOptions == null ? void 0 : openaiOptions.strictJsonSchema) != null ? _g : true; let include = openaiOptions == null ? void 0 : openaiOptions.include; function addInclude(key) { if (include == null) { include = [key]; } else if (!include.includes(key)) { include = [...include, key]; } } function hasOpenAITool(id) { return (tools2 == null ? void 0 : tools2.find((tool2) => tool2.type === "provider" && tool2.id === id)) != null; } const topLogprobs = typeof (openaiOptions == null ? void 0 : openaiOptions.logprobs) === "number" ? openaiOptions == null ? void 0 : openaiOptions.logprobs : (openaiOptions == null ? void 0 : openaiOptions.logprobs) === true ? TOP_LOGPROBS_MAX : void 0; if (topLogprobs) { addInclude("message.output_text.logprobs"); } const webSearchToolName = (_h = tools2 == null ? void 0 : tools2.find( (tool2) => tool2.type === "provider" && (tool2.id === "openai.web_search" || tool2.id === "openai.web_search_preview") )) == null ? void 0 : _h.name; if (webSearchToolName) { addInclude("web_search_call.action.sources"); } if (hasOpenAITool("openai.code_interpreter")) { addInclude("code_interpreter_call.outputs"); } const store = openaiOptions == null ? void 0 : openaiOptions.store; if (store === false && isReasoningModel) { addInclude("reasoning.encrypted_content"); } const baseArgs = { model: this.modelId, input, temperature, top_p: topP, max_output_tokens: maxOutputTokens, ...((responseFormat == null ? void 0 : responseFormat.type) === "json" || (openaiOptions == null ? void 0 : openaiOptions.textVerbosity)) && { text: { ...(responseFormat == null ? void 0 : responseFormat.type) === "json" && { format: responseFormat.schema != null ? { type: "json_schema", strict: strictJsonSchema, name: (_i2 = responseFormat.name) != null ? _i2 : "response", description: responseFormat.description, schema: responseFormat.schema } : { type: "json_object" } }, ...(openaiOptions == null ? void 0 : openaiOptions.textVerbosity) && { verbosity: openaiOptions.textVerbosity } } }, // provider options: conversation: openaiOptions == null ? void 0 : openaiOptions.conversation, max_tool_calls: openaiOptions == null ? void 0 : openaiOptions.maxToolCalls, metadata: openaiOptions == null ? void 0 : openaiOptions.metadata, parallel_tool_calls: openaiOptions == null ? void 0 : openaiOptions.parallelToolCalls, previous_response_id: openaiOptions == null ? void 0 : openaiOptions.previousResponseId, store, user: openaiOptions == null ? void 0 : openaiOptions.user, instructions: openaiOptions == null ? void 0 : openaiOptions.instructions, service_tier: openaiOptions == null ? void 0 : openaiOptions.serviceTier, include, prompt_cache_key: openaiOptions == null ? void 0 : openaiOptions.promptCacheKey, prompt_cache_options: openaiOptions == null ? void 0 : openaiOptions.promptCacheOptions, prompt_cache_retention: openaiOptions == null ? void 0 : openaiOptions.promptCacheRetention, safety_identifier: openaiOptions == null ? void 0 : openaiOptions.safetyIdentifier, top_logprobs: topLogprobs, truncation: openaiOptions == null ? void 0 : openaiOptions.truncation, // context management (server-side compaction): ...(openaiOptions == null ? void 0 : openaiOptions.contextManagement) && { context_management: openaiOptions.contextManagement.map((cm) => ({ type: cm.type, compact_threshold: cm.compactThreshold })) }, // model-specific settings: ...isReasoningModel && (resolvedReasoningEffort != null || resolvedReasoningSummary != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningMode) != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningContext) != null) && { reasoning: { ...resolvedReasoningEffort != null && { effort: resolvedReasoningEffort }, ...resolvedReasoningSummary != null && { summary: resolvedReasoningSummary }, ...(openaiOptions == null ? void 0 : openaiOptions.reasoningMode) != null && { mode: openaiOptions.reasoningMode }, ...(openaiOptions == null ? void 0 : openaiOptions.reasoningContext) != null && { context: openaiOptions.reasoningContext } } } }; if (isReasoningModel) { if (!(resolvedReasoningEffort === "none" && modelCapabilities.supportsNonReasoningParameters)) { if (baseArgs.temperature != null) { baseArgs.temperature = void 0; warnings.push({ type: "unsupported", feature: "temperature", details: "temperature is not supported for reasoning models" }); } if (baseArgs.top_p != null) { baseArgs.top_p = void 0; warnings.push({ type: "unsupported", feature: "topP", details: "topP is not supported for reasoning models" }); } } } else { if ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null) { warnings.push({ type: "unsupported", feature: "reasoningEffort", details: "reasoningEffort is not supported for non-reasoning models" }); } if ((openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) { warnings.push({ type: "unsupported", feature: "reasoningSummary", details: "reasoningSummary is not supported for non-reasoning models" }); } if ((openaiOptions == null ? void 0 : openaiOptions.reasoningMode) != null) { warnings.push({ type: "unsupported", feature: "reasoningMode", details: "reasoningMode is not supported for non-reasoning models" }); } if ((openaiOptions == null ? void 0 : openaiOptions.reasoningContext) != null) { warnings.push({ type: "unsupported", feature: "reasoningContext", details: "reasoningContext is not supported for non-reasoning models" }); } } if ((openaiOptions == null ? 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 ((openaiOptions == null ? 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 = (_l = (_k = (_j = tools2 == null ? void 0 : tools2.find( (tool2) => tool2.type === "provider" && tool2.id === "openai.shell" )) == null ? void 0 : _j.args) == null ? void 0 : _k.environment) == null ? void 0 : _l.type; const isShellProviderExecuted = shellToolEnvType === "containerAuto" || shellToolEnvType === "containerReference"; return { webSearchToolName, args: { ...baseArgs, tools: openaiTools2, tool_choice: openaiToolChoice }, warnings: [...warnings, ...toolWarnings], store, toolNameMapping, providerOptionsName, isShellProviderExecuted }; } async doGenerate(options) { var _a25, _b19, _c, _d, _e2, _f, _g, _h, _i2, _j, _k, _l, _m, _n3, _o, _p, _q, _r2, _s2, _t2, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F; const { args: body, warnings, webSearchToolName, toolNameMapping, providerOptionsName, isShellProviderExecuted } = await this.getArgs(options); const url2 = this.config.url({ path: "/responses", modelId: this.modelId }); const approvalRequestIdToDummyToolCallIdFromPrompt = extractApprovalRequestIdToToolCallIdMapping(options.prompt); const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({ url: url2, headers: combineHeaders((_b19 = (_a25 = this.config).headers) == null ? void 0 : _b19.call(_a25), options.headers), body, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler( openaiResponsesResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); if (response.error) { throw new APICallError({ message: response.error.message, url: url2, requestBodyValues: body, statusCode: 400, responseHeaders, responseBody: rawResponse, isRetryable: false }); } if (response.output == null) { const detail = (_c = response.incomplete_details) == null ? void 0 : _c.reason; throw new APICallError({ message: detail ? `Responses API returned no output (${detail})` : "Responses API returned no output", url: url2, requestBodyValues: body, statusCode: 500, 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 (part.summary.length === 0) { 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: (_d = part.encrypted_content) != null ? _d : 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 = (_e2 = part.call_id) != null ? _e2 : part.id; const isHosted = part.execution === "server"; 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 = (_g = (_f = part.call_id) != null ? _f : hostedToolSearchCallIds.shift()) != null ? _g : 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: item.outcome.type === "exit" ? { type: "exit", exitCode: item.outcome.exit_code } : { type: "timeout" } })) } }); break; } case "message": { for (const contentPart of part.content) { if (((_i2 = (_h = options.providerOptions) == null ? void 0 : _h[providerOptionsName]) == null ? void 0 : _i2.logprobs) && contentPart.logprobs) { logprobs.push(contentPart.logprobs); } const providerMetadata2 = { itemId: part.id, ...part.phase != null && { 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 (annotation.type === "url_citation") { content.push({ type: "source", sourceType: "url", id: (_l = (_k = (_j = this.config).generateId) == null ? void 0 : _k.call(_j)) != null ? _l : generateId(), url: annotation.url, title: annotation.title }); } else if (annotation.type === "file_citation") { content.push({ type: "source", sourceType: "document", id: (_o = (_n3 = (_m = this.config).generateId) == null ? void 0 : _n3.call(_m)) != null ? _o : generateId(), mediaType: "text/plain", title: annotation.filename, filename: annotation.filename, providerMetadata: { [providerOptionsName]: { type: annotation.type, fileId: annotation.file_id, index: annotation.index } } }); } else if (annotation.type === "container_file_citation") { content.push({ type: "source", sourceType: "document", id: (_r2 = (_q = (_p = this.config).generateId) == null ? void 0 : _q.call(_p)) != null ? _r2 : 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 (annotation.type === "file_path") { content.push({ type: "source", sourceType: "document", id: (_u = (_t2 = (_s2 = this.config).generateId) == null ? void 0 : _t2.call(_s2)) != null ? _u : 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, ...part.namespace != null && { namespace: part.namespace } } } }); 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( webSearchToolName != null ? webSearchToolName : "web_search" ), input: JSON.stringify({}), providerExecuted: true }); content.push({ type: "tool-result", toolCallId: part.id, toolName: toolNameMapping.toCustomToolName( webSearchToolName != null ? webSearchToolName : "web_search" ), result: mapWebSearchOutput(part.action) }); break; } case "mcp_call": { const toolCallId = part.approval_request_id != null ? (_v = approvalRequestIdToDummyToolCallIdFromPrompt[part.approval_request_id]) != null ? _v : 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, ...part.output != null ? { output: part.output } : {}, ...part.error != null ? { error: part.error } : {} }, providerMetadata: { [providerOptionsName]: { itemId: part.id } } }); break; } case "mcp_list_tools": { break; } case "mcp_approval_request": { const approvalRequestId = (_w = part.approval_request_id) != null ? _w : part.id; const dummyToolCallId = (_z = (_y = (_x = this.config).generateId) == null ? void 0 : _y.call(_x)) != null ? _z : 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": { if (part.call_id == null) { 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 } }); break; } hasFunctionCall = true; const toolName = toolNameMapping.toCustomToolName("computer"); content.push({ type: "tool-call", toolCallId: part.call_id, toolName, input: JSON.stringify(mapComputerCallInput(part)), providerMetadata: { [providerOptionsName]: { itemId: part.id } } }); 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: (_B = (_A = part.results) == null ? void 0 : _A.map((result) => ({ attributes: result.attributes, fileId: result.file_id, filename: result.filename, score: result.score, text: result.text }))) != null ? _B : 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; } case "compaction": { content.push({ type: "custom", kind: "openai.compaction", providerMetadata: { [providerOptionsName]: { type: "compaction", itemId: part.id, encryptedContent: part.encrypted_content } } }); break; } } } const providerMetadata = { [providerOptionsName]: { responseId: response.id, ...logprobs.length > 0 ? { logprobs } : {}, ...typeof response.service_tier === "string" ? { serviceTier: response.service_tier } : {}, ...((_C = response.reasoning) == null ? void 0 : _C.context) != null ? { reasoningContext: response.reasoning.context } : {} } }; const usage = response.usage; return { content, finishReason: { unified: mapOpenAIResponseFinishReason({ finishReason: (_D = response.incomplete_details) == null ? void 0 : _D.reason, hasFunctionCall }), raw: (_F = (_E = response.incomplete_details) == null ? void 0 : _E.reason) != null ? _F : void 0 }, usage: convertOpenAIResponsesUsage(usage), request: { body }, response: { id: response.id, timestamp: new Date(response.created_at * 1e3), modelId: response.model, headers: responseHeaders, body: rawResponse }, providerMetadata, warnings }; } async doStream(options) { var _a25, _b19; const { args: body, warnings, webSearchToolName, toolNameMapping, store, providerOptionsName, isShellProviderExecuted } = await this.getArgs(options); const url2 = this.config.url({ path: "/responses", modelId: this.modelId }); const { responseHeaders, value: response } = await postJsonToApi({ url: url2, headers: combineHeaders((_b19 = (_a25 = this.config).headers) == null ? void 0 : _b19.call(_a25), options.headers), body: { ...body, stream: true }, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createEventSourceResponseHandler( openaiResponsesChunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const checkedResponse = await throwIfOpenAIStreamErrorBeforeOutput({ stream: response, getError: (chunk) => isErrorChunk(chunk) || isResponseFailedChunk(chunk) && chunk.response.error != null ? chunk : void 0, isOutputChunk: isResponseOutputChunk, url: url2, requestBodyValues: body, responseHeaders }); const self = this; const approvalRequestIdToDummyToolCallIdFromPrompt = extractApprovalRequestIdToToolCallIdMapping(options.prompt); const approvalRequestIdToDummyToolCallIdFromStream = /* @__PURE__ */ new Map(); let finishReason = { unified: "other", raw: void 0 }; let usage = void 0; const logprobs = []; let responseId = null; const ongoingToolCalls = {}; const ongoingAnnotations = []; let activeMessagePhase; let hasFunctionCall = false; const activeReasoning = {}; let serviceTier; let reasoningContext; const hostedToolSearchCallIds = []; let encounteredStreamError = false; const result = { stream: checkedResponse.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { var _a26, _b23, _c, _d, _e2, _f, _g, _h, _i2, _j, _k, _l, _m, _n3, _o, _p, _q, _r2, _s2, _t2, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O; if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { const error40 = isOpenAIChatCompletionChunk(chunk.rawValue) ? createOpenAIResponsesChatCompletionsMismatchError({ value: chunk.rawValue, cause: chunk.error, url: url2, requestBodyValues: body, responseHeaders }) : chunk.error; finishReason = { unified: "error", raw: void 0 }; controller.enqueue({ type: "error", error: error40 }); return; } const value = chunk.value; if (isResponseOutputItemAddedChunk(value)) { if (value.item.type === "function_call") { ongoingToolCalls[value.output_index] = { toolName: value.item.name, toolCallId: value.item.call_id }; controller.enqueue({ type: "tool-input-start", id: value.item.call_id, toolName: value.item.name }); } else if (value.item.type === "custom_tool_call") { const toolName = toolNameMapping.toCustomToolName( value.item.name ); ongoingToolCalls[value.output_index] = { toolName, toolCallId: value.item.call_id }; controller.enqueue({ type: "tool-input-start", id: value.item.call_id, toolName }); } else if (value.item.type === "web_search_call") { ongoingToolCalls[value.output_index] = { toolName: toolNameMapping.toCustomToolName( webSearchToolName != null ? webSearchToolName : "web_search" ), toolCallId: value.item.id }; controller.enqueue({ type: "tool-input-start", id: value.item.id, toolName: toolNameMapping.toCustomToolName( webSearchToolName != null ? webSearchToolName : "web_search" ), providerExecuted: true }); controller.enqueue({ type: "tool-input-end", id: value.item.id }); controller.enqueue({ type: "tool-call", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName( webSearchToolName != null ? webSearchToolName : "web_search" ), input: JSON.stringify({}), providerExecuted: true }); } else if (value.item.type === "computer_call") { const toolCallId = (_a26 = value.item.call_id) != null ? _a26 : value.item.id; ongoingToolCalls[value.output_index] = { toolName: toolNameMapping.toCustomToolName("computer"), toolCallId }; controller.enqueue({ type: "tool-input-start", id: toolCallId, toolName: toolNameMapping.toCustomToolName("computer") }); } else if (value.item.type === "code_interpreter_call") { ongoingToolCalls[value.output_index] = { toolName: toolNameMapping.toCustomToolName("code_interpreter"), toolCallId: value.item.id, codeInterpreter: { containerId: value.item.container_id } }; controller.enqueue({ type: "tool-input-start", id: value.item.id, toolName: toolNameMapping.toCustomToolName("code_interpreter"), providerExecuted: true }); controller.enqueue({ type: "tool-input-delta", id: value.item.id, delta: `{"containerId":"${value.item.container_id}","code":"` }); } else if (value.item.type === "file_search_call") { controller.enqueue({ type: "tool-call", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("file_search"), input: "{}", providerExecuted: true }); } else if (value.item.type === "image_generation_call") { controller.enqueue({ type: "tool-call", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("image_generation"), input: "{}", providerExecuted: true }); } else if (value.item.type === "tool_search_call") { const toolCallId = value.item.id; const toolName = toolNameMapping.toCustomToolName("tool_search"); const isHosted = value.item.execution === "server"; ongoingToolCalls[value.output_index] = { toolName, toolCallId, toolSearchExecution: (_b23 = value.item.execution) != null ? _b23 : "server" }; if (isHosted) { controller.enqueue({ type: "tool-input-start", id: toolCallId, toolName, providerExecuted: true }); } } else if (value.item.type === "tool_search_output") { } else if (value.item.type === "mcp_call" || value.item.type === "mcp_list_tools" || value.item.type === "mcp_approval_request") { } else if (value.item.type === "apply_patch_call") { const { call_id: callId, operation } = value.item; ongoingToolCalls[value.output_index] = { toolName: toolNameMapping.toCustomToolName("apply_patch"), toolCallId: callId, applyPatch: { // delete_file doesn't have diff hasDiff: operation.type === "delete_file", endEmitted: operation.type === "delete_file" } }; controller.enqueue({ type: "tool-input-start", id: callId, toolName: toolNameMapping.toCustomToolName("apply_patch") }); if (operation.type === "delete_file") { 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 (value.item.type === "shell_call") { ongoingToolCalls[value.output_index] = { toolName: toolNameMapping.toCustomToolName("shell"), toolCallId: value.item.call_id }; } else if (value.item.type === "shell_call_output") { } else if (value.item.type === "message") { ongoingAnnotations.splice(0, ongoingAnnotations.length); activeMessagePhase = (_c = value.item.phase) != null ? _c : void 0; controller.enqueue({ type: "text-start", id: value.item.id, providerMetadata: { [providerOptionsName]: { itemId: value.item.id, ...value.item.phase != null && { phase: value.item.phase } } } }); } else if (isResponseOutputItemAddedChunk(value) && value.item.type === "reasoning") { activeReasoning[value.item.id] = { encryptedContent: value.item.encrypted_content, summaryParts: { 0: "active" } }; controller.enqueue({ type: "reasoning-start", id: `${value.item.id}:0`, providerMetadata: { [providerOptionsName]: { itemId: value.item.id, reasoningEncryptedContent: (_d = value.item.encrypted_content) != null ? _d : null } } }); } } else if (isResponseOutputItemDoneChunk(value)) { if (value.item.type === "message") { const phase = (_e2 = value.item.phase) != null ? _e2 : activeMessagePhase; activeMessagePhase = void 0; controller.enqueue({ type: "text-end", id: value.item.id, providerMetadata: { [providerOptionsName]: { itemId: value.item.id, ...phase != null && { phase }, ...ongoingAnnotations.length > 0 && { annotations: ongoingAnnotations } } } }); } else if (value.item.type === "function_call") { ongoingToolCalls[value.output_index] = void 0; hasFunctionCall = true; controller.enqueue({ type: "tool-input-end", id: value.item.call_id, ...value.item.namespace != null && { providerMetadata: { [providerOptionsName]: { namespace: value.item.namespace } } } }); controller.enqueue({ type: "tool-call", toolCallId: value.item.call_id, toolName: value.item.name, input: value.item.arguments, providerMetadata: { [providerOptionsName]: { itemId: value.item.id, ...value.item.namespace != null && { namespace: value.item.namespace } } } }); } else if (value.item.type === "custom_tool_call") { ongoingToolCalls[value.output_index] = void 0; hasFunctionCall = true; const toolName = toolNameMapping.toCustomToolName( value.item.name ); controller.enqueue({ type: "tool-input-end", id: value.item.call_id }); controller.enqueue({ type: "tool-call", toolCallId: value.item.call_id, toolName, input: JSON.stringify(value.item.input), providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } else if (value.item.type === "web_search_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName( webSearchToolName != null ? webSearchToolName : "web_search" ), result: mapWebSearchOutput(value.item.action) }); } else if (value.item.type === "computer_call") { ongoingToolCalls[value.output_index] = void 0; if (value.item.call_id == null) { controller.enqueue({ type: "tool-input-end", id: value.item.id }); controller.enqueue({ type: "tool-call", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("computer_use"), input: "", providerExecuted: true }); controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("computer_use"), result: { type: "computer_use_tool_result", status: value.item.status } }); return; } hasFunctionCall = true; const toolName = toolNameMapping.toCustomToolName("computer"); const input = JSON.stringify(mapComputerCallInput(value.item)); controller.enqueue({ type: "tool-input-delta", id: value.item.call_id, delta: input }); controller.enqueue({ type: "tool-input-end", id: value.item.call_id }); controller.enqueue({ type: "tool-call", toolCallId: value.item.call_id, toolName, input, providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } else if (value.item.type === "file_search_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("file_search"), result: { queries: value.item.queries, results: (_g = (_f = value.item.results) == null ? void 0 : _f.map((result2) => ({ attributes: result2.attributes, fileId: result2.file_id, filename: result2.filename, score: result2.score, text: result2.text }))) != null ? _g : null } }); } else if (value.item.type === "code_interpreter_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("code_interpreter"), result: { outputs: value.item.outputs } }); } else if (value.item.type === "image_generation_call") { controller.enqueue({ type: "tool-result", toolCallId: value.item.id, toolName: toolNameMapping.toCustomToolName("image_generation"), result: { result: value.item.result } }); } else if (value.item.type === "tool_search_call") { const toolCall = ongoingToolCalls[value.output_index]; const isHosted = value.item.execution === "server"; if (toolCall != null) { const toolCallId = isHosted ? toolCall.toolCallId : (_h = value.item.call_id) != null ? _h : value.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: value.item.arguments, call_id: isHosted ? null : toolCallId }), ...isHosted ? { providerExecuted: true } : {}, providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } ongoingToolCalls[value.output_index] = void 0; } else if (value.item.type === "tool_search_output") { const toolCallId = (_j = (_i2 = value.item.call_id) != null ? _i2 : hostedToolSearchCallIds.shift()) != null ? _j : value.item.id; controller.enqueue({ type: "tool-result", toolCallId, toolName: toolNameMapping.toCustomToolName("tool_search"), result: { tools: value.item.tools }, providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } else if (value.item.type === "mcp_call") { ongoingToolCalls[value.output_index] = void 0; const approvalRequestId = (_k = value.item.approval_request_id) != null ? _k : void 0; const aliasedToolCallId = approvalRequestId != null ? (_m = (_l = approvalRequestIdToDummyToolCallIdFromStream.get( approvalRequestId )) != null ? _l : approvalRequestIdToDummyToolCallIdFromPrompt[approvalRequestId]) != null ? _m : value.item.id : value.item.id; const toolName = `mcp.${value.item.name}`; controller.enqueue({ type: "tool-call", toolCallId: aliasedToolCallId, toolName, input: value.item.arguments, providerExecuted: true, dynamic: true }); controller.enqueue({ type: "tool-result", toolCallId: aliasedToolCallId, toolName, result: { type: "call", serverLabel: value.item.server_label, name: value.item.name, arguments: value.item.arguments, ...value.item.output != null ? { output: value.item.output } : {}, ...value.item.error != null ? { error: value.item.error } : {} }, providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } else if (value.item.type === "mcp_list_tools") { ongoingToolCalls[value.output_index] = void 0; } else if (value.item.type === "apply_patch_call") { const toolCall = ongoingToolCalls[value.output_index]; if ((toolCall == null ? void 0 : toolCall.applyPatch) && !toolCall.applyPatch.endEmitted && value.item.operation.type !== "delete_file") { if (!toolCall.applyPatch.hasDiff) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: escapeJSONDelta(value.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 && value.item.status === "completed") { controller.enqueue({ type: "tool-call", toolCallId: toolCall.toolCallId, toolName: toolNameMapping.toCustomToolName("apply_patch"), input: JSON.stringify({ callId: value.item.call_id, operation: value.item.operation }), providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } ongoingToolCalls[value.output_index] = void 0; } else if (value.item.type === "mcp_approval_request") { ongoingToolCalls[value.output_index] = void 0; const dummyToolCallId = (_p = (_o = (_n3 = self.config).generateId) == null ? void 0 : _o.call(_n3)) != null ? _p : generateId(); const approvalRequestId = (_q = value.item.approval_request_id) != null ? _q : value.item.id; approvalRequestIdToDummyToolCallIdFromStream.set( approvalRequestId, dummyToolCallId ); const toolName = `mcp.${value.item.name}`; controller.enqueue({ type: "tool-call", toolCallId: dummyToolCallId, toolName, input: value.item.arguments, providerExecuted: true, dynamic: true }); controller.enqueue({ type: "tool-approval-request", approvalId: approvalRequestId, toolCallId: dummyToolCallId }); } else if (value.item.type === "local_shell_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-call", toolCallId: value.item.call_id, toolName: toolNameMapping.toCustomToolName("local_shell"), input: JSON.stringify({ action: { type: "exec", command: value.item.action.command, timeoutMs: value.item.action.timeout_ms, user: value.item.action.user, workingDirectory: value.item.action.working_directory, env: value.item.action.env } }), providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } else if (value.item.type === "shell_call") { ongoingToolCalls[value.output_index] = void 0; controller.enqueue({ type: "tool-call", toolCallId: value.item.call_id, toolName: toolNameMapping.toCustomToolName("shell"), input: JSON.stringify({ action: { commands: value.item.action.commands } }), ...isShellProviderExecuted && { providerExecuted: true }, providerMetadata: { [providerOptionsName]: { itemId: value.item.id } } }); } else if (value.item.type === "shell_call_output") { controller.enqueue({ type: "tool-result", toolCallId: value.item.call_id, toolName: toolNameMapping.toCustomToolName("shell"), result: { output: value.item.output.map( (item) => ({ stdout: item.stdout, stderr: item.stderr, outcome: item.outcome.type === "exit" ? { type: "exit", exitCode: item.outcome.exit_code } : { type: "timeout" } }) ) } }); } else if (value.item.type === "reasoning") { const activeReasoningPart = activeReasoning[value.item.id]; const summaryPartIndices = Object.entries( activeReasoningPart.summaryParts ).filter( ([_2, status]) => status === "active" || status === "can-conclude" ).map(([summaryIndex]) => summaryIndex); for (const summaryIndex of summaryPartIndices) { controller.enqueue({ type: "reasoning-end", id: `${value.item.id}:${summaryIndex}`, providerMetadata: { [providerOptionsName]: { itemId: value.item.id, reasoningEncryptedContent: (_r2 = value.item.encrypted_content) != null ? _r2 : null } } }); } delete activeReasoning[value.item.id]; } else if (value.item.type === "compaction") { controller.enqueue({ type: "custom", kind: "openai.compaction", providerMetadata: { [providerOptionsName]: { type: "compaction", itemId: value.item.id, encryptedContent: value.item.encrypted_content } } }); } } else if (isResponseFunctionCallArgumentsDeltaChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall != null) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: value.delta }); } } else if (isResponseCustomToolCallInputDeltaChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall != null) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: value.delta }); } } else if (isResponseApplyPatchCallOperationDiffDeltaChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall == null ? void 0 : toolCall.applyPatch) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: escapeJSONDelta(value.delta) }); toolCall.applyPatch.hasDiff = true; } } else if (isResponseApplyPatchCallOperationDiffDoneChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if ((toolCall == null ? void 0 : toolCall.applyPatch) && !toolCall.applyPatch.endEmitted) { if (!toolCall.applyPatch.hasDiff) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: escapeJSONDelta(value.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(value)) { controller.enqueue({ type: "tool-result", toolCallId: value.item_id, toolName: toolNameMapping.toCustomToolName("image_generation"), result: { result: value.partial_image_b64 }, preliminary: true }); } else if (isResponseCodeInterpreterCallCodeDeltaChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall != null) { controller.enqueue({ type: "tool-input-delta", id: toolCall.toolCallId, delta: escapeJSONDelta(value.delta) }); } } else if (isResponseCodeInterpreterCallCodeDoneChunk(value)) { const toolCall = ongoingToolCalls[value.output_index]; if (toolCall != null) { 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: value.code, containerId: toolCall.codeInterpreter.containerId }), providerExecuted: true }); } } else if (isResponseCreatedChunk(value)) { responseId = value.response.id; controller.enqueue({ type: "response-metadata", id: value.response.id, timestamp: new Date(value.response.created_at * 1e3), modelId: value.response.model }); } else if (isTextDeltaChunk(value)) { controller.enqueue({ type: "text-delta", id: value.item_id, delta: value.delta }); if (((_t2 = (_s2 = options.providerOptions) == null ? void 0 : _s2[providerOptionsName]) == null ? void 0 : _t2.logprobs) && value.logprobs) { logprobs.push(value.logprobs); } } else if (value.type === "response.reasoning_summary_part.added") { if (value.summary_index > 0) { const activeReasoningPart = activeReasoning[value.item_id]; activeReasoningPart.summaryParts[value.summary_index] = "active"; for (const summaryIndex of Object.keys( activeReasoningPart.summaryParts )) { if (activeReasoningPart.summaryParts[summaryIndex] === "can-conclude") { controller.enqueue({ type: "reasoning-end", id: `${value.item_id}:${summaryIndex}`, providerMetadata: { [providerOptionsName]: { itemId: value.item_id } } }); activeReasoningPart.summaryParts[summaryIndex] = "concluded"; } } controller.enqueue({ type: "reasoning-start", id: `${value.item_id}:${value.summary_index}`, providerMetadata: { [providerOptionsName]: { itemId: value.item_id, reasoningEncryptedContent: (_v = (_u = activeReasoning[value.item_id]) == null ? void 0 : _u.encryptedContent) != null ? _v : null } } }); } } else if (value.type === "response.reasoning_summary_text.delta") { controller.enqueue({ type: "reasoning-delta", id: `${value.item_id}:${value.summary_index}`, delta: value.delta, providerMetadata: { [providerOptionsName]: { itemId: value.item_id } } }); } else if (value.type === "response.reasoning_summary_part.done") { if (store) { controller.enqueue({ type: "reasoning-end", id: `${value.item_id}:${value.summary_index}`, providerMetadata: { [providerOptionsName]: { itemId: value.item_id } } }); activeReasoning[value.item_id].summaryParts[value.summary_index] = "concluded"; } else { activeReasoning[value.item_id].summaryParts[value.summary_index] = "can-conclude"; } } else if (isResponseFinishedChunk(value)) { finishReason = { unified: mapOpenAIResponseFinishReason({ finishReason: (_w = value.response.incomplete_details) == null ? void 0 : _w.reason, hasFunctionCall }), raw: (_y = (_x = value.response.incomplete_details) == null ? void 0 : _x.reason) != null ? _y : void 0 }; usage = value.response.usage; if (typeof value.response.service_tier === "string") { serviceTier = value.response.service_tier; } if (((_z = value.response.reasoning) == null ? void 0 : _z.context) != null) { reasoningContext = value.response.reasoning.context; } } else if (isResponseFailedChunk(value)) { const incompleteReason = (_A = value.response.incomplete_details) == null ? void 0 : _A.reason; finishReason = { unified: incompleteReason ? mapOpenAIResponseFinishReason({ finishReason: incompleteReason, hasFunctionCall }) : "error", raw: incompleteReason != null ? incompleteReason : "error" }; usage = (_B = value.response.usage) != null ? _B : void 0; if (((_C = value.response.reasoning) == null ? void 0 : _C.context) != null) { reasoningContext = value.response.reasoning.context; } if (!encounteredStreamError && value.response.error != null) { encounteredStreamError = true; controller.enqueue({ type: "error", error: { type: "response.failed", sequence_number: value.sequence_number, response: { error: value.response.error, incomplete_details: value.response.incomplete_details, service_tier: value.response.service_tier } } }); } } else if (isResponseAnnotationAddedChunk(value)) { ongoingAnnotations.push(value.annotation); if (value.annotation.type === "url_citation") { controller.enqueue({ type: "source", sourceType: "url", id: (_F = (_E = (_D = self.config).generateId) == null ? void 0 : _E.call(_D)) != null ? _F : generateId(), url: value.annotation.url, title: value.annotation.title }); } else if (value.annotation.type === "file_citation") { controller.enqueue({ type: "source", sourceType: "document", id: (_I = (_H = (_G = self.config).generateId) == null ? void 0 : _H.call(_G)) != null ? _I : generateId(), mediaType: "text/plain", title: value.annotation.filename, filename: value.annotation.filename, providerMetadata: { [providerOptionsName]: { type: value.annotation.type, fileId: value.annotation.file_id, index: value.annotation.index } } }); } else if (value.annotation.type === "container_file_citation") { controller.enqueue({ type: "source", sourceType: "document", id: (_L = (_K = (_J = self.config).generateId) == null ? void 0 : _K.call(_J)) != null ? _L : generateId(), mediaType: "text/plain", title: value.annotation.filename, filename: value.annotation.filename, providerMetadata: { [providerOptionsName]: { type: value.annotation.type, fileId: value.annotation.file_id, containerId: value.annotation.container_id } } }); } else if (value.annotation.type === "file_path") { controller.enqueue({ type: "source", sourceType: "document", id: (_O = (_N = (_M = self.config).generateId) == null ? void 0 : _N.call(_M)) != null ? _O : generateId(), mediaType: "application/octet-stream", title: value.annotation.file_id, filename: value.annotation.file_id, providerMetadata: { [providerOptionsName]: { type: value.annotation.type, fileId: value.annotation.file_id, index: value.annotation.index } } }); } } else if (isErrorChunk(value)) { encounteredStreamError = true; finishReason = { unified: "error", raw: "error" }; controller.enqueue({ type: "error", error: value }); } }, flush(controller) { const providerMetadata = { [providerOptionsName]: { responseId, ...logprobs.length > 0 ? { logprobs } : {}, ...serviceTier !== void 0 ? { serviceTier } : {}, ...reasoningContext !== void 0 ? { reasoningContext } : {} } }; controller.enqueue({ type: "finish", finishReason, usage: convertOpenAIResponsesUsage(usage), providerMetadata }); } }) ), request: { body }, response: { headers: responseHeaders } }; return result; } }; function isTextDeltaChunk(chunk) { return chunk.type === "response.output_text.delta"; } function isOpenAIChatCompletionChunk(value) { const chunk = asRecord2(value); return chunk != null && Array.isArray(chunk.choices) && typeof chunk.type !== "string"; } function createOpenAIResponsesChatCompletionsMismatchError({ value, cause, url: url2, requestBodyValues, responseHeaders }) { return new APICallError({ message: "Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.", url: url2, requestBodyValues, responseHeaders, responseBody: JSON.stringify(value), cause, data: value, isRetryable: false }); } function asRecord2(value) { return typeof value === "object" && value != null ? value : void 0; } function isResponseOutputItemDoneChunk(chunk) { return chunk.type === "response.output_item.done"; } function isResponseFinishedChunk(chunk) { return chunk.type === "response.completed" || chunk.type === "response.incomplete"; } function isResponseFailedChunk(chunk) { return chunk.type === "response.failed"; } function isResponseCreatedChunk(chunk) { return chunk.type === "response.created"; } function isResponseFunctionCallArgumentsDeltaChunk(chunk) { return chunk.type === "response.function_call_arguments.delta"; } function isResponseCustomToolCallInputDeltaChunk(chunk) { return chunk.type === "response.custom_tool_call_input.delta"; } function isResponseImageGenerationCallPartialImageChunk(chunk) { return chunk.type === "response.image_generation_call.partial_image"; } function isResponseCodeInterpreterCallCodeDeltaChunk(chunk) { return chunk.type === "response.code_interpreter_call_code.delta"; } function isResponseCodeInterpreterCallCodeDoneChunk(chunk) { return chunk.type === "response.code_interpreter_call_code.done"; } function isResponseApplyPatchCallOperationDiffDeltaChunk(chunk) { return chunk.type === "response.apply_patch_call_operation_diff.delta"; } function isResponseApplyPatchCallOperationDiffDoneChunk(chunk) { return chunk.type === "response.apply_patch_call_operation_diff.done"; } function isResponseOutputItemAddedChunk(chunk) { return chunk.type === "response.output_item.added"; } function isResponseAnnotationAddedChunk(chunk) { return chunk.type === "response.output_text.annotation.added"; } function isErrorChunk(chunk) { return chunk.type === "error"; } function isResponseOutputChunk(chunk) { return !(chunk.type === "response.created" || chunk.type === "response.failed" || chunk.type === "error" || chunk.type === "unknown_chunk"); } function mapWebSearchOutput(action) { var _a25; if (action == null) { return {}; } switch (action.type) { case "search": return { action: { type: "search", query: (_a25 = action.query) != null ? _a25 : void 0, ...action.queries != null && { queries: action.queries } }, // include sources when provided by the Responses API (behind include flag) ...action.sources != null && { 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 = lazySchema( () => zodSchema( external_exports.object({ instructions: external_exports.string().nullish(), speed: external_exports.number().min(0.25).max(4).default(1).nullish() }) ) ); var OpenAISpeechModel = class _OpenAISpeechModel { constructor(modelId, config2) { this.modelId = modelId; this.config = config2; this.specificationVersion = "v4"; } static [WORKFLOW_SERIALIZE](model) { return serializeModelOptions({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE](options) { return new _OpenAISpeechModel(options.modelId, options.config); } get provider() { return this.config.provider; } async getArgs({ text: text2, 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: text2, 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 value = speechModelOptions[key]; if (value !== void 0) { requestBody[key] = value; } } } 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(options) { var _a25, _b19, _c, _d, _e2; const currentDate = (_c = (_b19 = (_a25 = this.config._internal) == null ? void 0 : _a25.currentDate) == null ? void 0 : _b19.call(_a25)) != null ? _c : /* @__PURE__ */ new Date(); const { requestBody, warnings } = await this.getArgs(options); const { value: audio, responseHeaders, rawValue: rawResponse } = await postJsonToApi({ url: this.config.url({ path: "/audio/speech", modelId: this.modelId }), headers: combineHeaders((_e2 = (_d = this.config).headers) == null ? void 0 : _e2.call(_d), options.headers), body: requestBody, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createBinaryResponseHandler(), abortSignal: options.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 = lazySchema( () => zodSchema( external_exports.object({ text: external_exports.string(), language: external_exports.string().nullish(), duration: external_exports.number().nullish(), words: external_exports.array( external_exports.object({ word: external_exports.string(), start: external_exports.number(), end: external_exports.number() }) ).nullish(), segments: external_exports.array( external_exports.object({ id: external_exports.number(), seek: external_exports.number(), start: external_exports.number(), end: external_exports.number(), text: external_exports.string(), tokens: external_exports.array(external_exports.number()), temperature: external_exports.number(), avg_logprob: external_exports.number(), compression_ratio: external_exports.number(), no_speech_prob: external_exports.number() }) ).nullish() }) ) ); var openAITranscriptionModelOptions = lazySchema( () => zodSchema( external_exports.object({ /** * Additional information to include in the transcription response. */ include: external_exports.array(external_exports.string()).optional(), /** * The language of the input audio in ISO-639-1 format. */ language: external_exports.string().optional(), /** * An optional text to guide the model's style or continue a previous audio segment. */ prompt: external_exports.string().optional(), /** * The sampling temperature, between 0 and 1. * @default 0 */ temperature: external_exports.number().min(0).max(1).default(0).optional(), /** * The timestamp granularities to populate for this transcription. * @default ['segment'] */ timestampGranularities: external_exports.array(external_exports.enum(["word", "segment"])).default(["segment"]).optional(), /** * Options for streaming transcription models such as `gpt-realtime-whisper`. */ streaming: external_exports.object({ /** * Latency/accuracy tradeoff for realtime transcription. */ delay: external_exports.enum(["minimal", "low", "medium", "high", "xhigh"]).optional(), /** * Additional fields to include in realtime transcription events. */ include: external_exports.array(external_exports.string()).optional() }).optional() }) ) ); function isRealtimeTranscriptionModelId(modelId) { return modelId === "gpt-realtime-whisper" || modelId.startsWith("gpt-realtime-whisper-"); } 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 _OpenAITranscriptionModel { constructor(modelId, config2) { this.modelId = modelId; this.config = config2; this.specificationVersion = "v4"; } static [WORKFLOW_SERIALIZE](model) { return serializeModelOptions({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE](options) { return new _OpenAITranscriptionModel(options.modelId, options.config); } 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 fileExtension2 = mediaTypeToExtension(mediaType); formData.append( "file", new File([blob], "audio", { type: mediaType }), `audio.${fileExtension2}` ); if (this.modelId === "whisper-1") { formData.append("response_format", "verbose_json"); } if (openAIOptions) { const isGpt4oTranscribeModel = [ "gpt-4o-transcribe", "gpt-4o-mini-transcribe" ].includes(this.modelId); const transcriptionModelOptions = { include: openAIOptions.include, language: openAIOptions.language, prompt: openAIOptions.prompt, // https://platform.openai.com/docs/api-reference/audio/createTranscription#audio_createtranscription-response_format // prefer verbose_json to get segments for models that support it ...this.modelId !== "whisper-1" && { response_format: isGpt4oTranscribeModel ? "json" : "verbose_json" }, temperature: openAIOptions.temperature, timestamp_granularities: openAIOptions.timestampGranularities }; for (const [key, value] of Object.entries(transcriptionModelOptions)) { if (value != null) { if (Array.isArray(value)) { for (const item of value) { formData.append(`${key}[]`, String(item)); } } else { formData.append(key, String(value)); } } } } return { formData, warnings }; } async doGenerate(options) { var _a25, _b19, _c, _d, _e2, _f, _g, _h, _i2, _j; if (isRealtimeTranscriptionModelId(this.modelId)) { throw new UnsupportedFunctionalityError({ functionality: `non-streaming transcription with ${this.modelId}` }); } const currentDate = (_c = (_b19 = (_a25 = this.config._internal) == null ? void 0 : _a25.currentDate) == null ? void 0 : _b19.call(_a25)) != null ? _c : /* @__PURE__ */ new Date(); const { formData, warnings } = await this.getArgs(options); const { value: response, responseHeaders, rawValue: rawResponse } = await postFormDataToApi({ url: this.config.url({ path: "/audio/transcriptions", modelId: this.modelId }), headers: combineHeaders((_e2 = (_d = this.config).headers) == null ? void 0 : _e2.call(_d), options.headers), formData, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler( openaiTranscriptionResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const language = response.language != null && response.language in languageMap ? languageMap[response.language] : void 0; return { text: response.text, segments: (_i2 = (_h = (_f = response.segments) == null ? void 0 : _f.map((segment2) => ({ text: segment2.text, startSecond: segment2.start, endSecond: segment2.end }))) != null ? _h : (_g = response.words) == null ? void 0 : _g.map((word) => ({ text: word.word, startSecond: word.start, endSecond: word.end }))) != null ? _i2 : [], language, durationInSeconds: (_j = response.duration) != null ? _j : void 0, warnings, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders, body: rawResponse } }; } async doStream(options) { var _a25, _b19, _c, _d, _e2, _f, _g; if (!isRealtimeTranscriptionModelId(this.modelId)) { throw new UnsupportedFunctionalityError({ functionality: `streaming transcription with ${this.modelId}` }); } const currentDate = (_c = (_b19 = (_a25 = this.config._internal) == null ? void 0 : _a25.currentDate) == null ? void 0 : _b19.call(_a25)) != null ? _c : /* @__PURE__ */ new Date(); const openAIOptions = await parseProviderOptions({ provider: "openai", providerOptions: options.providerOptions, schema: openAITranscriptionModelOptions }); const warnings = []; const rawOpenAIOptions = (_e2 = (_d = options.providerOptions) == null ? void 0 : _d.openai) != null ? _e2 : {}; for (const option of [ "include", "prompt", "temperature", "timestampGranularities" ]) { if (rawOpenAIOptions[option] != null) { warnings.push({ type: "unsupported", feature: `providerOptions.openai.${option}`, details: `OpenAI streaming transcription does not support ${option}.` }); } } const headers = combineHeaders((_g = (_f = this.config).headers) == null ? void 0 : _g.call(_f), options.headers); const sessionUpdate = buildOpenAIRealtimeTranscriptionSession({ modelId: this.modelId, inputAudioFormat: options.inputAudioFormat, providerOptions: openAIOptions }); return { request: { body: sessionUpdate }, response: { timestamp: currentDate, modelId: this.modelId }, stream: createOpenAIRealtimeTranscriptionStream({ webSocket: this.config.webSocket, url: toWebSocketUrl( this.config.url({ path: "/realtime?intent=transcription", modelId: this.modelId }) ), headers, sessionUpdate, language: openAIOptions == null ? void 0 : openAIOptions.language, warnings, audio: options.audio, abortSignal: options.abortSignal, includeRawChunks: options.includeRawChunks }) }; } }; function createOpenAIRealtimeTranscriptionStream({ webSocket, url: url2, headers, sessionUpdate, language, warnings, audio, abortSignal, includeRawChunks }) { let finished = false; let cleanup = () => { }; return new ReadableStream({ start: (controller) => { const realtimeConnection = getOpenAIRealtimeConnection(headers); let audioReader; let connection; cleanup = (closeCode) => { if (audioReader != null) { void audioReader.cancel().catch(() => { }); } else { void audio.cancel().catch(() => { }); } connection == null ? void 0 : connection.close(closeCode); }; const finishWithError = (error40) => { if (finished) return; finished = true; cleanup(); controller.error(error40); }; const finish = (text2, id) => { if (finished) return; finished = true; if (id != null) { controller.enqueue({ type: "transcript-final", id, text: text2 }); } controller.enqueue({ type: "finish", text: text2, segments: [], language }); controller.close(); cleanup(1e3); }; const sendAudio = async (socket) => { audioReader = audio.getReader(); try { while (true) { const { done, value } = await audioReader.read(); if (done || finished) break; socket.send( JSON.stringify({ type: "input_audio_buffer.append", audio: convertToBase64(value) }) ); await waitForWebSocketBufferDrain(socket); } } finally { audioReader.releaseLock(); audioReader = void 0; } if (!finished) { socket.send(JSON.stringify({ type: "input_audio_buffer.commit" })); } }; connection = connectToWebSocket({ url: url2, protocols: realtimeConnection.protocols, headers: realtimeConnection.headers, webSocket, abortSignal, onAbort: finishWithError, onProcessingError: finishWithError, onOpen: (socket) => { controller.enqueue({ type: "stream-start", warnings }); socket.send(JSON.stringify(sessionUpdate)); void sendAudio(socket).catch(finishWithError); }, onMessageText: async (text2) => { var _a25, _b19, _c, _d; const parsed = await safeParseJSON({ text: text2 }); if (!parsed.success) return; const raw = parsed.value; if (includeRawChunks) { controller.enqueue({ type: "raw", rawValue: raw }); } switch (raw.type) { case "conversation.item.input_audio_transcription.delta": { controller.enqueue({ type: "transcript-delta", id: raw.item_id, delta: (_a25 = raw.delta) != null ? _a25 : "" }); break; } case "conversation.item.input_audio_transcription.completed": { finish((_b19 = raw.transcript) != null ? _b19 : "", raw.item_id); break; } case "error": { finishWithError( new Error((_d = (_c = raw.error) == null ? void 0 : _c.message) != null ? _d : "OpenAI realtime error") ); break; } } }, onSocketError: () => { finishWithError(new Error("OpenAI realtime transcription error")); }, onClose: () => { if (finished) return; finished = true; cleanup(); controller.close(); } }); }, cancel: () => { if (finished) return; finished = true; cleanup(); } }); } function buildOpenAIRealtimeTranscriptionSession({ modelId, inputAudioFormat, providerOptions }) { var _a25, _b19; return { type: "session.update", session: { type: "transcription", audio: { input: { format: { type: inputAudioFormat.type, ...inputAudioFormat.rate != null ? { rate: inputAudioFormat.rate } : {} }, transcription: { model: modelId, ...(providerOptions == null ? void 0 : providerOptions.language) != null ? { language: providerOptions.language } : {}, ...((_a25 = providerOptions == null ? void 0 : providerOptions.streaming) == null ? void 0 : _a25.delay) != null ? { delay: providerOptions.streaming.delay } : {} }, turn_detection: null } }, ...((_b19 = providerOptions == null ? void 0 : providerOptions.streaming) == null ? void 0 : _b19.include) != null ? { include: providerOptions.streaming.include } : {} } }; } function getOpenAIRealtimeConnection(headers) { var _a25; let authorization; for (const [key, value] of Object.entries(headers)) { if (key.toLowerCase() === "authorization" && value != null) { authorization = value; } } const token2 = (_a25 = authorization == null ? void 0 : authorization.match(/^bearer\s+(.+)$/i)) == null ? void 0 : _a25[1]; if (token2 == null) { return { protocols: ["realtime"], headers }; } return { protocols: ["realtime", `openai-insecure-api-key.${token2}`], headers: Object.fromEntries( Object.entries(headers).filter( ([key]) => key.toLowerCase() !== "authorization" ) ) }; } var openaiSkillResponseSchema = lazySchema( () => zodSchema( external_exports.object({ id: external_exports.string(), name: external_exports.string().nullish(), description: external_exports.string().nullish(), default_version: external_exports.string().nullish(), latest_version: external_exports.string().nullish(), created_at: external_exports.number(), updated_at: external_exports.number().nullish() }) ) ); var openaiSkillVersionResponseSchema = lazySchema( () => zodSchema( external_exports.object({ id: external_exports.string(), version: external_exports.string().nullish(), name: external_exports.string().nullish(), description: external_exports.string().nullish() }) ) ); var OpenAISkills = class { constructor(config2) { this.config = config2; this.specificationVersion = "v4"; } get provider() { return this.config.provider; } async uploadSkill(params) { const warnings = []; if (params.displayTitle != null) { warnings.push({ type: "unsupported", feature: "displayTitle" }); } const formData = new FormData(); for (const file2 of params.files) { const content = convertInlineFileDataToUint8Array(file2.data); formData.append("files[]", new Blob([content]), file2.path); } const { value: response } = await postFormDataToApi({ url: this.config.url({ path: "/skills" }), headers: combineHeaders(this.config.headers()), formData, failedResponseHandler: openaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler( openaiSkillResponseSchema ), fetch: this.config.fetch }); return { providerReference: { openai: response.id }, ...response.name != null ? { name: response.name } : {}, ...response.description != null ? { description: response.description } : {}, ...response.latest_version != null ? { latestVersion: response.latest_version } : {}, providerMetadata: { openai: { ...response.default_version != null ? { defaultVersion: response.default_version } : {}, ...response.created_at != null ? { createdAt: response.created_at } : {}, ...response.updated_at != null ? { updatedAt: response.updated_at } : {} } }, warnings }; } }; var VERSION4 = true ? "4.0.16" : "0.0.0-test"; function createOpenAI(options = {}) { var _a25, _b19; const baseURL = (_a25 = withoutTrailingSlash( validateBaseURL( loadOptionalSetting({ settingValue: options.baseURL, environmentVariableName: "OPENAI_BASE_URL" }) ) )) != null ? _a25 : "https://api.openai.com/v1"; const providerName = (_b19 = options.name) != null ? _b19 : "openai"; const getHeaders = () => withUserAgentSuffix( { Authorization: `Bearer ${loadApiKey({ apiKey: options.apiKey, environmentVariableName: "OPENAI_API_KEY", description: "OpenAI" })}`, "OpenAI-Organization": options.organization, "OpenAI-Project": options.project, ...options.headers }, `ai-sdk/openai/${VERSION4}` ); const createChatModel = (modelId) => new OpenAIChatLanguageModel(modelId, { provider: `${providerName}.chat`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, { provider: `${providerName}.completion`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, { provider: `${providerName}.embedding`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createImageModel = (modelId) => new OpenAIImageModel(modelId, { provider: `${providerName}.image`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, { provider: `${providerName}.transcription`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch, webSocket: options.webSocket }); const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, { provider: `${providerName}.speech`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch }); const createFiles = () => new OpenAIFiles({ provider: `${providerName}.files`, baseURL, headers: getHeaders, fetch: options.fetch }); const createSkills = () => new OpenAISkills({ provider: `${providerName}.skills`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.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) => { return new OpenAIResponsesLanguageModel(modelId, { provider: `${providerName}.responses`, url: ({ path }) => `${baseURL}${path}`, headers: getHeaders, fetch: options.fetch, // Soft-deprecated. TODO: remove in v8 fileIdPrefixes: ["file-"] }); }; const createRealtimeModel = (modelId) => new OpenAIRealtimeModel(modelId, { provider: `${providerName}.realtime`, baseURL, headers: getHeaders, fetch: options.fetch }); const experimentalRealtimeFactory = Object.assign( (modelId) => createRealtimeModel(modelId), { getToken: async (tokenOptions) => { const model = createRealtimeModel(tokenOptions.model); const secret = await model.doCreateClientSecret({ sessionConfig: tokenOptions.sessionConfig, expiresAfterSeconds: tokenOptions.expiresAfterSeconds }); return { token: secret.token, url: secret.url, expiresAt: secret.expiresAt }; } } ); const provider = function(modelId) { return createLanguageModel(modelId); }; provider.specificationVersion = "v4"; 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.files = createFiles; provider.skills = createSkills; provider.experimental_realtime = experimentalRealtimeFactory; provider.tools = openaiTools; return provider; } var openai = createOpenAI(); // src/orchestrator/llm-debug.ts var reqSeq = 0; function isEnabled() { try { return typeof localStorage !== "undefined" && localStorage.getItem("ANT_COPILOT_DEBUG") === "1"; } catch { return false; } } function modelIdOf(model) { return model?.modelId ?? "(unknown model)"; } function logLlmRequestOnce(source, payload) { if (!isEnabled()) return; reqSeq += 1; console.groupCollapsed(`[Copilot LLM] req #${reqSeq} \xB7 ${source}`); console.debug("model:", modelIdOf(payload.model)); console.log(payload.prompt ?? ""); console.groupEnd(); } // src/tools/llm-interpret.ts async function interpretWithLlm(ctx, prompt) { if (!ctx.llmApiKey) return null; try { const llm = createOpenAI({ apiKey: ctx.llmApiKey, baseURL: ctx.llmBaseUrl || void 0 }); const model = llm.chat(ctx.llmModel || "kimi-k3"); logLlmRequestOnce("llm-interpret", { model, prompt }); const result = await generateText({ model, prompt }); return result.text || null; } catch (err2) { console.warn("[llm-interpret] LLM \u89E3\u8BFB\u5931\u8D25\uFF0C\u56DE\u9000\u5230\u539F\u59CB\u6570\u636E:", err2); return null; } } // src/tools/analyze.building.ts var analyzeBuildingContextSchema = external_exports2.custom(); function summarizeComfort(res) { if (!res || typeof res !== "object") return JSON.stringify(res ?? null); const keys = ["totalComfortableHours", "heatingHours", "coolingHours", "heatingDegreeDays", "coolingDegreeDays"]; const picked = {}; let found = false; for (const k of keys) { if (res[k] !== void 0) { picked[k] = res[k]; found = true; } } if (!found && res.free_running) return summarizeComfort(res.free_running); return JSON.stringify(found ? picked : res, null, 2); } function summarizePassive(res) { if (!res || typeof res !== "object") return JSON.stringify(res ?? null); const simplifiedStrategies = {}; if (res.strategies) { for (const key in res.strategies) { const s2 = res.strategies[key] || {}; simplifiedStrategies[key] = { additionalComfortHours: s2.additionalComfortHours, heatingReduction: s2.heatingReduction, coolingReduction: s2.coolingReduction, estimatedEnergySavings: s2.estimatedEnergySavings, description: s2.description }; } return JSON.stringify({ strategies: simplifiedStrategies }, null, 2); } return JSON.stringify(res, null, 2); } function pickEnergyData(simResults) { if (!simResults || typeof simResults !== "object") return { baseline: null, design: null }; return { baseline: simResults.baselineResult ?? null, design: simResults.proposalResult ?? simResults.energyResult ?? null }; } function buildComparisonContext(baseline, design) { if (!baseline || !design) return ""; const bHeating = baseline.setpoint?.total_heating_demand ?? 0; const bCooling = baseline.setpoint?.total_cooling_demand ?? 0; const bTotal = bHeating + bCooling; const dHeating = design.setpoint?.total_heating_demand ?? design.totalHeatingDemand ?? 0; const dCooling = design.setpoint?.total_cooling_demand ?? design.totalCoolingDemand ?? 0; const dTotal = dHeating + dCooling; const savings = bTotal > 0 ? ((bTotal - dTotal) / bTotal * 100).toFixed(1) : 0; return ` COMPARATIVE ANALYSIS (Baseline vs Design): - Baseline EUI: ${bTotal.toFixed(2)} kWh (Heating ${bHeating.toFixed(2)} / Cooling ${bCooling.toFixed(2)}) - Design EUI: ${dTotal.toFixed(2)} kWh (Heating ${dHeating.toFixed(2)} / Cooling ${dCooling.toFixed(2)}) - Estimated Savings: ${savings}% `; } function buildOverviewPrompt(summaryContext) { return ` You are an expert Sustainable Design Consultant. Provide a high-level "Project Overview" based on the following analysis results. Synthesize the findings into a coherent narrative about the building's performance. IMPORTANT: If comparative data is provided (Baseline vs Design), you MUST explicitly evaluate the improvements or regressions. Data: ${JSON.stringify(summaryContext, null, 2)} **Format**: - **Executive Summary**: 1-2 sentences (Include savings % if available). - **Climate Suitability**: Evaluate if the design fits the climate context. - **Performance Comparison**: Baseline vs Design analysis. - **Key Strengths**: Bullet points. - **Critical Issues**: Bullet points (highlight high EUI or comfort risks). - **Recommendations**: Strategic advice. `; } function createAnalyzeBuilding() { return tool({ description: '\u5206\u6790\u5EFA\u7B51\u6027\u80FD\u2014\u2014**\u88AB\u52A8\u5F0F\u7B56\u7565\uFF08passive\uFF09\u4E0E\u7EFC\u5408\u6982\u89C8\uFF08overview\uFF09**\u3002\u8BA1\u7B97\u5728\u5BBF\u4E3B\u5E94\u7528\u5185\u6267\u884C\uFF0C\u672C\u5DE5\u5177\u8D1F\u8D23\u7F16\u6392\u4E0E\u7ED3\u679C\u89E3\u8BFB\u3002\u80FD\u8017\uFF08energy\uFF09\u4E0E\u70ED\u8212\u9002\uFF08comfort\uFF09**\u5DF2\u6536\u655B\u5230\u6A21\u62DF\u5DE5\u5177**\uFF1A\u4E24\u8005\u8D70\u7684\u662F\u540C\u4E00\u4E2A\u5BBF\u4E3B computeAnalysis \u56DE\u8C03\uFF0C\u5206\u5F00\u5217\u4F1A\u5F97\u5230"\u540C\u4E00\u95EE\u9898\u4E24\u5957\u6570"\u3002\u53D6\u54EA\u4E2A\u5DE5\u5177\u6309\u5F62\u6001\u5B9A\u2014\u2014\u6D4F\u89C8\u5668\u5BBF\u4E3B\uFF08ant-model \u9762\u677F\uFF09\u7528 `run_simulation(type="energy"|"comfort")`\uFF1BMCP / \u65E0\u5BBF\u4E3B\u5F62\u6001\u7528 `simulate(kind="energy"|"comfort")`\u3002\u672C\u5DE5\u5177\u6536\u5230\u8FD9\u4E24\u7C7B\u4F1A\u76F4\u63A5\u91CD\u5B9A\u5411\u3001\u4E0D\u91CD\u590D\u8BA1\u7B97\u3002', inputSchema: external_exports2.object({ analysis_type: external_exports2.enum(["comfort", "passive", "energy", "overview"]).describe("\u5206\u6790\u7C7B\u578B\u3002passive=\u88AB\u52A8\u5F0F\u7B56\u7565\uFF1Boverview=\u7EFC\u5408\u6982\u89C8\uFF08\u5185\u90E8\u542B\u80FD\u8017/\u8212\u9002/\u88AB\u52A8\u5F0F\uFF0C\u4E00\u6B21\u51FA\u62A5\u544A\uFF09\u3002energy/comfort \u5DF2\u5F03\u7528\u2014\u2014\u8BF7\u6539\u7528 simulate\uFF0C\u672C\u5DE5\u5177\u547D\u4E2D\u5373\u91CD\u5B9A\u5411\u3002"), action: external_exports2.enum(["run", "report"]).optional().default("run").describe("run=\u6267\u884C\u6A21\u62DF\uFF08\u80FD\u8017\u4F18\u5148\u590D\u7528\u7F13\u5B58\uFF09\uFF1Breport=\u4EC5\u8BFB\u53D6\u5DF2\u6709\u7ED3\u679C\u751F\u6210\u62A5\u544A\u3002overview \u5FFD\u7565\u6B64\u53C2\u6570") }), contextSchema: analyzeBuildingContextSchema, execute: (async (params, { context }) => { const { analysis_type, action = "run" } = params; if (analysis_type === "energy" || analysis_type === "comfort") { return { status: "redirected", analysis_type, // 工具名按形态:浏览器宿主走宿主注入的 run_simulation;MCP/无宿主形态走 simulate。 // 只报一个名字会让另一形态的调用方去调不存在的工具(本收敛第一版就踩了这个坑)。 message: `\u300C${analysis_type}\u300D\u5DF2\u6536\u655B\u5230\u6A21\u62DF\u5DE5\u5177\uFF0C\u672C\u5DE5\u5177\u4E0D\u518D\u91CD\u590D\u8BA1\u7B97\u3002\u6D4F\u89C8\u5668\u5BBF\u4E3B\uFF08ant-model \u9762\u677F\uFF09\u7528 run_simulation(type="${analysis_type}")\uFF08\u5BBF\u4E3B\u6CE8\u5165\uFF09\uFF1BMCP / \u65E0\u5BBF\u4E3B\u5F62\u6001\u7528 simulate(kind="${analysis_type}")\uFF08Studio \u6267\u884C\u5668\u4F18\u5148\uFF0C\u79BB\u7EBF\u53EF\u9000\u5316\u4E3A\u8FDB\u7A0B\u5185\u5F15\u64CE\uFF09\u3002`, use_instead: { browser_host: { tool: "run_simulation", params: { type: analysis_type } }, mcp: { tool: "simulate", params: { kind: analysis_type } } } }; } const compute = context.computeAnalysis; const getResults = context.getSimulationResults; if (!compute) { return { status: "unavailable", message: "\u5BBF\u4E3B\u672A\u6CE8\u5165 computeAnalysis \u80FD\u529B\uFF0C\u65E0\u6CD5\u6267\u884C\u5EFA\u7B51\u6027\u80FD\u5206\u6790\u3002" }; } try { switch (analysis_type) { case "passive": { const pResult = await compute("passive"); return { status: "success", analysis_type, message: `Passive strategy analysis completed. Summary: ${summarizePassive(pResult)}`, data: pResult }; } case "overview": { const [cRes, pRes] = await Promise.all([compute("comfort"), compute("passive")]); const cached2 = getResults ? pickEnergyData(getResults()) : { baseline: null, design: null }; let energyData = cached2.design; if (!energyData) { energyData = await compute("energy"); } const comparisonText = buildComparisonContext(cached2.baseline, energyData) || "No comparison available (Analysis Only)"; const summaryContext = { comfort: JSON.parse(summarizeComfort(cRes)), passive: JSON.parse(summarizePassive(pRes)), energy: energyData?.setpoint ?? energyData ?? "No energy data generated.", comparison: comparisonText }; const interpretation = await interpretWithLlm(context, buildOverviewPrompt(summaryContext)); return { status: "success", analysis_type, message: interpretation ?? "Analyses completed, but AI summary unavailable. See data.", data: { comfort: cRes, passive: pRes, energy: energyData } }; } default: return { status: "error", message: `Unknown analysis type: ${analysis_type}` }; } } catch (err2) { return { status: "error", analysis_type, message: `\u5206\u6790\u5931\u8D25: ${err2?.message ?? String(err2)}` }; } }) }); } // src/tools/query.simulation.db.ts function toBoundedJson(data, maxBytes = 24 * 1024) { let text2; try { text2 = JSON.stringify(data, null, 2); } catch { text2 = String(data); } if (text2.length <= maxBytes) return text2; return text2.slice(0, maxBytes) + ` ... [\u622A\u65AD\uFF0C\u539F\u59CB ${text2.length} \u5B57\u7B26]`; } function summarizeForLlm(data, depth = 0) { if (data === null || data === void 0) return data; if (typeof data !== "object") return data; if (depth > 6) return "[\u6DF1\u5EA6\u8D85\u9650\u7701\u7565]"; if (Array.isArray(data)) { if (data.length > 8 && data.every((v2) => typeof v2 === "number")) { const nums = data; const sum = nums.reduce((a3, b5) => a3 + b5, 0); return { _series: true, count: nums.length, min: +Math.min(...nums).toFixed(2), max: +Math.max(...nums).toFixed(2), mean: +(sum / nums.length).toFixed(2), sum: +sum.toFixed(2) }; } if (data.length > 5) { return { _count: data.length, _sample: data.slice(0, 3).map((v2) => summarizeForLlm(v2, depth + 1)), _note: `\u5171 ${data.length} \u6761\uFF0C\u4EC5\u663E\u793A\u524D 3 \u6761\u6837\u672C` }; } return data.map((v2) => summarizeForLlm(v2, depth + 1)); } const out = {}; for (const [k, v2] of Object.entries(data)) out[k] = summarizeForLlm(v2, depth + 1); return out; } function buildAnalysisPrompt(aspect, dataText, userQuery) { return ` You are an expert Building Performance Analyst. The user queried the building's cached simulation results (aspect: ${aspect}). ${userQuery ? `The user's question is: "${userQuery}" \u2014 focus your answer on it.` : "Provide a concise evaluation of the results."} Data: ${dataText} Evaluate the key metrics (flag good / acceptable / poor where a reference range is commonly known), and give actionable suggestions. Keep the answer concise (max 3-4 paragraphs) with bullet points. `; } var querySimulationDbContextSchema = external_exports2.custom(); function createQuerySimulationDb() { return tool({ description: "\u67E5\u8BE2\u5EFA\u7B51\u6A21\u62DF\u7ED3\u679C\u7F13\u5B58\u2014\u2014\u80FD\u8017\uFF08baseline/proposal\uFF09\u3001\u70ED\u8212\u9002\u3001\u592A\u9633\u8F90\u5C04\u3001\u901A\u98CE\u3001\u91C7\u5149\u3001\u53C2\u6570\u626B\u63CF\u7ED3\u679C\u3002\u8FD4\u56DE\u7EDF\u8BA1\u5316\u6570\u636E\uFF08\u957F\u6570\u5217\u538B\u7F29\u4E3A count/min/max/mean/sum\uFF0C\u957F\u5217\u8868\u53EA\u7559\u6837\u672C\uFF09\uFF0C\u4E0D\u542B\u539F\u59CB\u6570\u636E\u3002\u6570\u636E\u6765\u81EA\u5BBF\u4E3B\u672C\u5730\u7F13\u5B58\uFF0C\u4E0D\u89E6\u53D1\u65B0\u6A21\u62DF\uFF1B\u9700\u8981\u91CD\u65B0\u8BA1\u7B97\u8BF7\u7528 simulate\uFF08\u80FD\u8017/\u8212\u9002/\u91C7\u5149/\u65E5\u7167/\u901A\u98CE\u7B49\uFF09\uFF0C\u88AB\u52A8\u5F0F\u7B56\u7565\u4E0E\u7EFC\u5408\u6982\u89C8\u7528 analyze_building\u3002", inputSchema: external_exports2.object({ aspect: external_exports2.enum(["all", "energy", "comfort", "solar", "ventilation", "daylight"]).optional().default("all").describe("\u67E5\u8BE2\u7684\u6027\u80FD\u7EF4\u5EA6\u3002all=\u5168\u90E8\uFF1B\u53EA\u9700\u8981\u5355\u4E00\u7EF4\u5EA6\u65F6\u7A84\u5316\u53EF\u52A0\u5FEB\u54CD\u5E94"), detail: external_exports2.enum(["data", "report", "analysis"]).optional().default("report").describe("\u8FD4\u56DE\u7EA7\u522B\uFF1Adata=\u4EC5\u7EDF\u8BA1\u6570\u636E\uFF08\u6700\u5FEB\uFF0C\u6570\u5217\u5DF2\u538B\u7F29\u4E3A\u7EDF\u8BA1\u6307\u6807\uFF09\uFF1Breport/analysis=\u9644 AI \u89E3\u8BFB\uFF08analysis \u4F1A\u7ED3\u5408 query \u805A\u7126\uFF09"), query: external_exports2.string().optional().describe("\u7528\u6237\u95EE\u9898\uFF0C\u7528\u4E8E\u805A\u7126 AI \u89E3\u8BFB\uFF08\u4EC5 detail=analysis \u65F6\u4F7F\u7528\uFF09") }), contextSchema: querySimulationDbContextSchema, execute: (async (params, { context }) => { const queryCache = context.querySimulationCache; if (!queryCache) { return { status: "unavailable", message: "\u5BBF\u4E3B\u672A\u6CE8\u5165 querySimulationCache \u80FD\u529B\uFF0C\u65E0\u6CD5\u67E5\u8BE2\u6A21\u62DF\u7ED3\u679C\u7F13\u5B58\u3002" }; } const aspect = params.aspect || "all"; const detail = params.detail || "report"; try { const data = await queryCache({ aspect, query: params.query }); if (data == null || typeof data === "object" && !Array.isArray(data) && Object.keys(data).length === 0) { return { status: "no_data", aspect, message: "\u672A\u627E\u5230\u7F13\u5B58\u7684\u6A21\u62DF\u7ED3\u679C\uFF0C\u8BF7\u5148\u8FD0\u884C\u76F8\u5E94\u6A21\u62DF\u3002" }; } if (detail === "data") { return { status: "success", aspect, data: summarizeForLlm(data), data_note: "\u5DF2\u7EDF\u8BA1\u5316\uFF1A\u957F\u6570\u5217\u538B\u7F29\u4E3A\u7EDF\u8BA1\u6307\u6807\uFF08count/min/max/mean/sum\uFF09\uFF0C\u957F\u5217\u8868\u53EA\u7559\u6837\u672C\u3002\u539F\u59CB\u6570\u636E\u7531\u5BBF\u4E3B\u4FA7\u4FDD\u7559\uFF0CLLM \u4E0D\u53EF\u89C1" }; } const summary = summarizeForLlm(data); const dataText = toBoundedJson(summary); const interpretation = await interpretWithLlm(context, buildAnalysisPrompt(aspect, dataText, params.query)); return { status: "success", aspect, message: interpretation ?? `Simulation cache query results (aspect: ${aspect}): ${dataText}`, data: summary }; } catch (err2) { return { status: "error", aspect, message: `\u67E5\u8BE2\u6A21\u62DF\u7F13\u5B58\u5931\u8D25: ${err2?.message ?? String(err2)}` }; } }) }); } // src/core/DesignParamRegistry.ts var DesignParamRegistry = class { params = /* @__PURE__ */ new Map(); /** 注册或更新一个参数 */ set(key, value, source, options) { this.params.set(key, { key, value, source, unit: options?.unit, type: options?.type, timestamp: Date.now() }); } /** 读取参数值 */ get(key) { return this.params.get(key)?.value; } /** 获取参数完整条目(含 source) */ getEntry(key) { return this.params.get(key); } /** 批量读取多个参数 */ getMany(keys) { const result = {}; for (const k of keys) { const v2 = this.params.get(k)?.value; if (v2 !== void 0) result[k] = v2; } return result; } /** 校验一组参数是否都已注册 */ check(keys) { const missing = []; const available = []; for (const k of keys) { if (this.params.has(k)) { available.push(k); } else { missing.push(k); } } return { ok: missing.length === 0, missing, available }; } /** 溯源:查看某个参数的完整来源链 */ trace(key) { const entry = this.params.get(key); if (!entry) return null; return `${key} = ${JSON.stringify(entry.value)} (\u7531 ${entry.source} \u5728 ${new Date(entry.timestamp).toISOString()} \u8BA1\u7B97)`; } /** 生成文本快照(供 LLM 上下文参考) */ snapshot() { if (this.params.size === 0) return "## \u5F53\u524D\u8BBE\u8BA1\u53C2\u6570\n\uFF08\u65E0\u53C2\u6570\uFF09"; const lines = ["## \u5F53\u524D\u8BBE\u8BA1\u53C2\u6570"]; for (const [key, entry] of this.params) { const unit = entry.unit ? ` ${entry.unit}` : ""; lines.push(`- ${key}: ${JSON.stringify(entry.value)}${unit} [\u6765\u6E90: ${entry.source}]`); } return lines.join("\n"); } /** 序列化为 JSON(用于持久化) */ toJSON() { return Array.from(this.params.values()); } /** 从 JSON 恢复(用于持久化加载) */ fromJSON(entries) { for (const e5 of entries) { this.params.set(e5.key, e5); } } /** 当前注册参数数量 */ get size() { return this.params.size; } /** 清空 */ clear() { this.params.clear(); } }; // src/core/RoomManifest.ts function stableId(name24, type, floor) { const raw = floor ? `${name24}|${type}|${floor}` : `${name24}|${type}`; let hash = 0; for (let i4 = 0; i4 < raw.length; i4++) { const ch2 = raw.charCodeAt(i4); hash = (hash << 5) - hash + ch2; hash |= 0; } const hex = Math.abs(hash).toString(16).padStart(6, "0"); return floor ? hex.slice(-6) : hex.slice(0, 6); } function inferType(name24) { if (/主卧|主卧室/.test(name24)) return "master_bedroom"; if (/次卧|卧室|客房|儿童房|老人房/.test(name24)) return "bedroom"; if (/客餐厅|起居餐厅/.test(name24)) return "living_dining"; if (/客厅|起居室/.test(name24)) return "living"; if (/餐厅/.test(name24)) return "dining"; if (/厨房|厨/.test(name24)) return "kitchen"; if (/卫生间|厕所|洗手|浴室|卫$/.test(name24)) return "bathroom"; if (/书房/.test(name24)) return "study"; if (/玄关|门厅|前室/.test(name24)) return "foyer"; if (/走廊|过道|走道|交通|电梯厅|楼梯/.test(name24)) return "circulation"; if (/阳台|露台/.test(name24)) return "balcony"; if (/储藏|储物|库房|设备|机房/.test(name24)) return "storage"; if (/会议/.test(name24)) return "meeting"; if (/办公/.test(name24)) return "office"; if (/前台|接待/.test(name24)) return "reception"; if (/天井|庭院|中庭|void|室外/.test(name24)) return "void"; return "unknown"; } var RoomManifest = class { rooms = /* @__PURE__ */ new Map(); /** 从 area-budget 的 breakdown 播种:{ floorId: { roomName: area, ... } } */ seedFromBreakdown(breakdown, source) { for (const [floorId, roomMap] of Object.entries(breakdown)) { for (const [name24, area] of Object.entries(roomMap)) { const type = inferType(name24); if (type === "void" || type === "unknown") continue; const id = stableId(name24, type, floorId); if (!this.rooms.has(id)) { this.rooms.set(id, { id, name: name24, type, plannedArea: area, floor: floorId, source, status: "planned" }); } } } } /** 从 structured rooms 数组播种:[{name, type, area?, floor?}] */ seedFromRooms(rooms, source) { for (const r4 of rooms) { if (r4.type === "void" || r4.type === "unknown") continue; const id = stableId(r4.name, r4.type, r4.floor); if (!this.rooms.has(id)) { this.rooms.set(id, { id, name: r4.name, type: r4.type, plannedArea: r4.area ?? 0, floor: r4.floor, source, status: "planned" }); } else { const existing = this.rooms.get(id); if (r4.area && r4.area > 0) existing.plannedArea = r4.area; if (r4.floor) existing.floor = r4.floor; existing.source = source; } } } /** 添加或更新房间 */ upsert(name24, type, options) { const id = stableId(name24, type, options?.floor); const existing = this.rooms.get(id); if (existing) { if (options?.area !== void 0) existing.plannedArea = options.area; if (options?.floor) existing.floor = options.floor; if (options?.source) existing.source = options.source; return existing; } const entry = { id, name: name24, type, plannedArea: options?.area ?? 0, floor: options?.floor, source: options?.source ?? "manual", status: "planned" }; this.rooms.set(id, entry); return entry; } /** 移除房间 */ remove(id) { return this.rooms.delete(id); } /** 获取指定房间 */ get(id) { return this.rooms.get(id); } /** 按名称查找 */ findByName(name24) { for (const r4 of this.rooms.values()) { if (r4.name === name24) return r4; } return void 0; } /** * 按 AML 空间(带 dote-bounds/geometry 足迹)把对应清单房间置为 placed。 * 先按稳定 id 精确匹配,再按 name 兜底;未命中保持原状态。 * @returns 本次被置为 placed 的房间数 */ markPlacedFromAml(rooms) { let changed = 0; for (const r4 of rooms) { const entry = this.rooms.get(r4.id) ?? (r4.name ? this.findByName(r4.name) : void 0); if (entry && entry.status === "planned") { entry.status = "placed"; changed++; } } return changed; } /** 获取所有房间 */ getAll() { return Array.from(this.rooms.values()); } /** 按楼层 */ getByFloor(floorId) { return this.getAll().filter((r4) => r4.floor === floorId); } /** 按类型 */ getByType(type) { return this.getAll().filter((r4) => r4.type === type); } /** 数量 */ get size() { return this.rooms.size; } /** 对比 AML 中的房间 vs 清单 */ diffAgainstAml(amlRooms) { const amlSet = new Map(amlRooms.map((r4) => [r4.id, r4])); const amlNamePool = /* @__PURE__ */ new Map(); for (const r4 of amlRooms) { amlNamePool.set(r4.name, (amlNamePool.get(r4.name) ?? 0) + 1); } const matched = []; const missingFromAml = []; const extraInAml = []; for (const entry of this.rooms.values()) { if (entry.type === "void") continue; if (amlSet.has(entry.id)) { matched.push(entry); continue; } const remaining = amlNamePool.get(entry.name) ?? 0; if (remaining > 0) { amlNamePool.set(entry.name, remaining - 1); matched.push(entry); } else { missingFromAml.push(entry); } } for (const r4 of amlRooms) { if (r4.type === "void") continue; if (!this.rooms.has(r4.id) && !this.findByName(r4.name)) { extraInAml.push({ id: r4.id, name: r4.name, type: r4.type || "" }); } } return { matched, missingFromAml, extraInAml }; } /** 结构化房间清单文本 */ snapshot() { if (this.rooms.size === 0) return "## \u623F\u95F4\u6E05\u5355\n\uFF08\u65E0\u623F\u95F4\uFF09"; const lines = ["## \u623F\u95F4\u6E05\u5355\uFF08\u5171 " + this.rooms.size + " \u95F4\uFF09"]; const byFloor = /* @__PURE__ */ new Map(); for (const r4 of this.rooms.values()) { const floor = r4.floor || "\u5F85\u5206\u914D"; if (!byFloor.has(floor)) byFloor.set(floor, []); byFloor.get(floor).push(r4); } for (const [floor, rooms] of byFloor) { lines.push(` ### ${floor}`); for (const r4 of rooms) { lines.push(`- ${r4.name}\uFF08${r4.type}\uFF09${r4.plannedArea}\u33A1 [ID: ${r4.id}, \u72B6\u6001: ${r4.status}]`); } } return lines.join("\n"); } /** 序列化 */ toJSON() { return this.getAll(); } /** 反序列化恢复 */ fromJSON(entries) { for (const e5 of entries) { this.rooms.set(e5.id, e5); } } }; // src/core/ContextManager.ts var StaticSource = class { constructor(key, text2) { this.key = key; this.text = text2; } key; text; render() { return this.text; } hash() { return String(this.text.length + "_" + (this.text.length > 0 ? this.text.charCodeAt(0) : 0)); } }; var DynamicSource = class { constructor(key, formatter) { this.key = key; this.formatter = formatter; } key; formatter; current = ""; render() { return this.formatter(this.current); } hash() { return String(this.current.length) + "_" + this.current; } update(value) { this.current = value; } }; var ContextManager = class { sources = /* @__PURE__ */ new Map(); baselineBuilt = false; /** 注册一个静态 source(冻结后不变) */ registerStatic(key, text2, frozen = true) { this.sources.set(key, { source: new StaticSource(key, text2), frozen, lastHash: "" }); } /** 注册一个动态 source(可更新) */ registerDynamic(key, formatter, frozenAfterFirst = false) { this.sources.set(key, { source: new DynamicSource(key, formatter), frozen: frozenAfterFirst, lastHash: "" }); } /** 获取指定静态 source 的渲染内容(即使已被冻结) */ getStaticContent(key) { const entry = this.sources.get(key); if (!entry) return void 0; return entry.source.render(); } /** * 替换静态 source 的内容并同步哈希(reconcile 不产生伪增量段落)。 * 用于会话中途整体重建某段(如匹配 Skill 切换后的 base_rules)—— * 调用方随后经 getStaticContent 取到的即是新内容,无需再等增量更新段。 */ replaceStatic(key, text2) { const source = new StaticSource(key, text2); const entry = this.sources.get(key); if (!entry) { this.sources.set(key, { source, frozen: true, lastHash: source.hash() }); return; } entry.source = source; entry.lastHash = source.hash(); } /** 注册或更新动态 source:如果存在则更新,否则注册并更新 */ registerOrUpdateDynamic(key, formatter, value, frozenAfterFirst = false) { const existing = this.sources.get(key); if (existing && existing.source instanceof DynamicSource) { existing.source.update(value); } else if (existing) { return; } else { this.registerDynamic(key, formatter, frozenAfterFirst); this.update(key, value); } } /** 更新动态 source 的值 */ update(key, value) { const entry = this.sources.get(key); if (!entry || !(entry.source instanceof DynamicSource)) return; entry.source.update(value); } /** 编译基线:所有 source 按注册顺序拼接 */ buildBaseline() { this.baselineBuilt = true; const parts = []; for (const [key, entry] of this.sources) { const text2 = entry.source.render(); if (text2) parts.push(text2); entry.lastHash = entry.source.hash(); if (entry.frozen && entry.source instanceof DynamicSource) { entry.source = new StaticSource(key, entry.source.render()); entry.lastHash = entry.source.hash(); } } return parts.join("\n\n"); } /** 在 safe boundary 检测变化,返回增量更新段落列表 */ reconcile() { const updates = []; for (const [key, entry] of this.sources) { const newHash = entry.source.hash(); if (newHash !== entry.lastHash) { entry.lastHash = newHash; const text2 = entry.source.render(); if (text2) { updates.push(`\u2501\u2501\u2501 [\u66F4\u65B0: ${key}] \u2501\u2501\u2501 ${text2}`); } if (entry.frozen && entry.source instanceof DynamicSource) { entry.source = new StaticSource(key, entry.source.render()); } } } return updates; } /** * 快照:导出每个 source 当前渲染文本(供会话 checkpoint 持久化)。 * 动态 source 也以"渲染后文本"落盘,恢复时按静态重建——formatter 是闭包无法序列化, * 但恢复后 render() 输出与快照一致,LLM 看到的上下文不丢失。 */ snapshot() { const sources = []; for (const [key, entry] of this.sources) { sources.push({ key, text: entry.source.render(), frozen: entry.frozen }); } return { version: 1, sources }; } /** 恢复快照:清空现有 sources,按静态 source 重建并同步哈希(恢复后 reconcile 无伪增量) */ restore(snapshot) { if (!snapshot || snapshot.version !== 1 || !Array.isArray(snapshot.sources)) return; this.sources.clear(); for (const item of snapshot.sources) { if (typeof item?.key !== "string") continue; this.sources.set(item.key, { source: new StaticSource(item.key, typeof item.text === "string" ? item.text : ""), frozen: item.frozen !== false, lastHash: "" }); } for (const entry of this.sources.values()) { entry.lastHash = entry.source.hash(); } this.baselineBuilt = true; } }; // src/core/memory/SessionMemory.ts var SESSION_MEMORY_MAX_ENTRIES = 200; var SESSION_MEMORY_DEFAULT_LIMIT = 12; function isValidMemoryEntry(e5) { if (!e5 || typeof e5 !== "object") return false; const o3 = e5; return typeof o3.id === "string" && typeof o3.sessionId === "string" && typeof o3.text === "string" && typeof o3.createdAt === "number" && ["design-change", "decision", "error", "summary", "note"].includes(o3.kind); } var SessionMemoryStore = class { entries = []; get size() { return this.entries.length; } /** 追加一条记忆;超容量淘汰最旧。 */ add(entry) { const full = { ...entry, id: entry.id || `mem_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`, createdAt: entry.createdAt ?? Date.now() }; this.entries.push(full); if (this.entries.length > SESSION_MEMORY_MAX_ENTRIES) { this.entries.splice(0, this.entries.length - SESSION_MEMORY_MAX_ENTRIES); } return full; } /** 追加(带简单去重:最近 limit 条内 kind+text 相同则跳过,避免重复刷屏) */ addIfNew(entry, limit = 8) { const recent = this.entries.slice(-limit); if (recent.some((e5) => e5.kind === entry.kind && e5.text === entry.text)) return null; return this.add(entry); } /** 按条件取最近 N 条(默认取最新 12 条) */ list(opts = {}) { let out = this.entries; if (opts.kinds?.length) out = out.filter((e5) => opts.kinds.includes(e5.kind)); if (opts.since !== void 0) out = out.filter((e5) => e5.createdAt >= opts.since); return out.slice(-(opts.limit ?? SESSION_MEMORY_DEFAULT_LIMIT)); } clear() { this.entries = []; } toJSON() { return this.entries; } /** 从宿主持久化数据恢复(过滤非法条目,截断容量) */ fromJSON(data) { if (!Array.isArray(data)) return; this.entries = data.filter(isValidMemoryEntry).slice(-SESSION_MEMORY_MAX_ENTRIES); } }; // src/tools/shared-state.ts var SESSION_DECISIONS_MAX_ENTRIES = 60; var SESSION_STATE_TTL_MS = 2 * 60 * 60 * 1e3; var SESSION_STATE_MAX_ENTRIES = 100; var _sessionStateStore = /* @__PURE__ */ new Map(); function _evictExpired(now2) { for (const [id, entry] of _sessionStateStore) { if (now2 - entry.lastActiveAt > SESSION_STATE_TTL_MS) { _sessionStateStore.delete(id); } } } function _evictOldestIfFull() { if (_sessionStateStore.size < SESSION_STATE_MAX_ENTRIES) return; let oldestId; let oldestAt = Infinity; for (const [id, entry] of _sessionStateStore) { if (entry.lastActiveAt < oldestAt) { oldestAt = entry.lastActiveAt; oldestId = id; } } if (oldestId !== void 0) _sessionStateStore.delete(oldestId); } function getSessionStateParts(sessionId) { const now2 = Date.now(); _evictExpired(now2); const existing = _sessionStateStore.get(sessionId); if (existing) { existing.lastActiveAt = now2; return existing.parts; } _evictOldestIfFull(); const entry = { parts: { toolContext: { lastResults: /* @__PURE__ */ new Map() }, registry: new DesignParamRegistry(), roomManifest: new RoomManifest(), memory: new SessionMemoryStore() }, lastActiveAt: now2 }; _sessionStateStore.set(sessionId, entry); return entry.parts; } function exportSessionState(sessionId) { const entry = _sessionStateStore.get(sessionId); if (!entry) return null; const p2 = entry.parts; try { const snapshot = { version: 1, toolContext: Object.fromEntries(p2.toolContext.lastResults), registry: p2.registry.toJSON(), roomManifest: p2.roomManifest.toJSON(), memory: p2.memory.toJSON(), ...p2.contextManager ? { contextManager: p2.contextManager.snapshot() } : {}, ...p2.modelVersion !== void 0 ? { modelVersion: p2.modelVersion } : {}, ...p2.flow ? { flow: p2.flow } : {}, ...p2.pendingFlowGates ? { pendingFlowGates: p2.pendingFlowGates } : {}, ...p2.pendingAskUserCandidateMap ? { pendingAskUserCandidateMap: p2.pendingAskUserCandidateMap } : {}, ...p2.pendingApplyCandidate ? { pendingApplyCandidate: p2.pendingApplyCandidate } : {}, ...p2.pendingCandidateGate ? { pendingCandidateGate: p2.pendingCandidateGate } : {}, ...p2.decisions ? { decisions: p2.decisions } : {} }; return JSON.stringify(snapshot); } catch { return null; } } function importSessionState(sessionId, json3) { let snapshot; try { snapshot = JSON.parse(json3); } catch { return false; } if (!snapshot || snapshot.version !== 1) return false; const parts = getSessionStateParts(sessionId); parts.toolContext.lastResults = new Map(Object.entries(snapshot.toolContext ?? {})); if (Array.isArray(snapshot.registry)) parts.registry.fromJSON(snapshot.registry); if (Array.isArray(snapshot.roomManifest)) parts.roomManifest.fromJSON(snapshot.roomManifest); if (Array.isArray(snapshot.memory)) parts.memory.fromJSON(snapshot.memory); if (snapshot.contextManager) { const cm = new ContextManager(); cm.restore(snapshot.contextManager); parts.contextManager = cm; } if (snapshot.modelVersion !== void 0) parts.modelVersion = snapshot.modelVersion; if (snapshot.flow && typeof snapshot.flow === "object" && snapshot.flow.done) { parts.flow = { done: snapshot.flow.done, ...snapshot.flow.vars ? { vars: snapshot.flow.vars } : {}, ...snapshot.flow.requirements ? { requirements: snapshot.flow.requirements } : {} }; } if (Array.isArray(snapshot.pendingFlowGates)) { parts.pendingFlowGates = snapshot.pendingFlowGates; } if (Array.isArray(snapshot.pendingAskUserCandidateMap)) { parts.pendingAskUserCandidateMap = snapshot.pendingAskUserCandidateMap; } if (snapshot.pendingApplyCandidate && typeof snapshot.pendingApplyCandidate === "object" && typeof snapshot.pendingApplyCandidate.candidateIndex === "number" && typeof snapshot.pendingApplyCandidate.amlRef === "string") { parts.pendingApplyCandidate = snapshot.pendingApplyCandidate; } if (snapshot.pendingCandidateGate && typeof snapshot.pendingCandidateGate === "object" && typeof snapshot.pendingCandidateGate.requested === "number" && typeof snapshot.pendingCandidateGate.produced === "number") { parts.pendingCandidateGate = snapshot.pendingCandidateGate; } if (Array.isArray(snapshot.decisions)) { const valid = snapshot.decisions.filter((d2) => !!d2 && typeof d2 === "object" && typeof d2.question === "string" && typeof d2.choice === "string"); parts.decisions = valid.slice(-SESSION_DECISIONS_MAX_ENTRIES); } return true; } function createToolEnv(overrides = {}) { return { toolContext: { lastResults: /* @__PURE__ */ new Map() }, registry: new DesignParamRegistry(), roomManifest: new RoomManifest(), llmApiKey: "", llmBaseUrl: "", ...overrides }; } // src/core/memory/memory-store.ts var MEMORY_STORE_DEFAULT_DB_NAME = "ant-copilot-memory"; var IDB_OBJECT_STORE = "kv"; function createMemoryMemoryStore() { const map2 = /* @__PURE__ */ new Map(); return { async get(key) { return map2.get(key); }, async set(key, value) { map2.set(key, value); }, async delete(key) { map2.delete(key); }, async list(prefix) { const out = []; for (const [key, value] of map2) { if (key.startsWith(prefix)) out.push({ key, value }); } out.sort((a3, b5) => a3.key < b5.key ? -1 : a3.key > b5.key ? 1 : 0); return out; } }; } function idbRequestToPromise(req) { return new Promise((resolve3, reject) => { req.onsuccess = () => resolve3(req.result); req.onerror = () => reject(req.error ?? new Error("IndexedDB request failed")); }); } function createIndexedDbMemoryStore(dbName = MEMORY_STORE_DEFAULT_DB_NAME) { if (typeof indexedDB === "undefined") { throw new Error( "createIndexedDbMemoryStore \u4EC5\u5728\u6D4F\u89C8\u5668\u73AF\u5883\u53EF\u7528\uFF08indexedDB \u672A\u5B9A\u4E49\uFF09\u3002Node / \u6D4B\u8BD5\u573A\u666F\u8BF7\u4F7F\u7528 createMemoryMemoryStore()\uFF0C\u6216 createDefaultMemoryStore() \u81EA\u52A8\u9009\u62E9\u3002" ); } let dbPromise = null; const openDb = () => { if (!dbPromise) { dbPromise = new Promise((resolve3, reject) => { const req = indexedDB.open(dbName, 1); req.onupgradeneeded = () => { const db = req.result; if (!db.objectStoreNames.contains(IDB_OBJECT_STORE)) { db.createObjectStore(IDB_OBJECT_STORE); } }; req.onsuccess = () => resolve3(req.result); req.onerror = () => reject(req.error ?? new Error(`IndexedDB \u6253\u5F00\u5931\u8D25: ${dbName}`)); }); } return dbPromise; }; const withStore = async (mode, fn2) => { const db = await openDb(); const tx = db.transaction(IDB_OBJECT_STORE, mode); return idbRequestToPromise(fn2(tx.objectStore(IDB_OBJECT_STORE))); }; return { async get(key) { const value = await withStore("readonly", (s2) => s2.get(key)); return value === void 0 ? void 0 : value; }, async set(key, value) { await withStore("readwrite", (s2) => s2.put(value, key)); }, async delete(key) { await withStore("readwrite", (s2) => s2.delete(key)); }, async list(prefix) { const range = IDBKeyRange.bound(prefix, `${prefix}\uFFFF`); const db = await openDb(); const tx = db.transaction(IDB_OBJECT_STORE, "readonly"); const store = tx.objectStore(IDB_OBJECT_STORE); const [keys, values] = await Promise.all([ idbRequestToPromise(store.getAllKeys(range)), idbRequestToPromise(store.getAll(range)) ]); return keys.map((key, i4) => ({ key: String(key), value: values[i4] })); } }; } function createNamespacedMemoryStore(base, namespace) { const prefix = `${namespace}:`; return { get: (key) => base.get(prefix + key), set: (key, value) => base.set(prefix + key, value), delete: (key) => base.delete(prefix + key), list: async (p2) => { const rows = await base.list(prefix + p2); return rows.map((r4) => ({ key: r4.key.slice(prefix.length), value: r4.value })); } }; } function createDefaultMemoryStore(namespace) { const base = typeof indexedDB !== "undefined" ? createIndexedDbMemoryStore() : createMemoryMemoryStore(); return namespace ? createNamespacedMemoryStore(base, namespace) : base; } // src/core/memory/layered-memory.ts var SESSION_PREFIX = "session:"; var PROJECT_PREFIX = "project:"; var GLOBAL_PREFIX = "global:"; var LayeredMemory = class { store; constructor(store) { this.store = store ?? createDefaultMemoryStore(); } // ── 会话级:SessionStateParts 快照 ───────────────────────────────── /** * 持久化指定会话的状态快照(供刷新 / 重启后恢复)。 * 会话不存在(从未有状态或已删除)返回 false,不写存储。 */ async saveSessionSnapshot(sessionId) { const json3 = exportSessionState(sessionId); if (json3 === null) return false; await this.store.set(`${SESSION_PREFIX}${sessionId}`, json3); return true; } /** * 恢复指定会话的状态快照。无快照或快照非法返回 false(不抛异常)。 * 语义同 importSessionState:复用既有 parts 对象,逐字段覆盖。 */ async restoreSessionSnapshot(sessionId) { const json3 = await this.store.get(`${SESSION_PREFIX}${sessionId}`); if (typeof json3 !== "string") return false; return importSessionState(sessionId, json3); } /** 删除指定会话的持久化快照(不动内存态) */ async deleteSessionSnapshot(sessionId) { await this.store.delete(`${SESSION_PREFIX}${sessionId}`); } /** 列出已持久化快照的会话 ID 列表 */ async listSessionSnapshots() { const rows = await this.store.list(SESSION_PREFIX); return rows.map((r4) => r4.key.slice(SESSION_PREFIX.length)); } // ── 项目级:设计决策 / 偏好 / 经验(key: projectId 维度) ─────────── /** 写入项目级记忆条目 */ async setProjectEntry(projectId, key, value) { await this.store.set(`${PROJECT_PREFIX}${projectId}:${key}`, value); } /** 读取项目级记忆条目;不存在返回 undefined */ async getProjectEntry(projectId, key) { return this.store.get(`${PROJECT_PREFIX}${projectId}:${key}`); } /** 删除项目级记忆条目 */ async deleteProjectEntry(projectId, key) { await this.store.delete(`${PROJECT_PREFIX}${projectId}:${key}`); } /** 列出项目全部记忆条目(key 剥离项目前缀,按 key 字典序) */ async listProjectEntries(projectId) { const prefix = `${PROJECT_PREFIX}${projectId}:`; const rows = await this.store.list(prefix); return rows.map((r4) => ({ key: r4.key.slice(prefix.length), value: r4.value })); } // ── 跨会话:长期经验沉淀(全局 / 用户维度) ───────────────────────── /** 写入全局经验条目 */ async setGlobalEntry(key, value) { await this.store.set(`${GLOBAL_PREFIX}${key}`, value); } /** 读取全局经验条目;不存在返回 undefined */ async getGlobalEntry(key) { return this.store.get(`${GLOBAL_PREFIX}${key}`); } /** 删除全局经验条目 */ async deleteGlobalEntry(key) { await this.store.delete(`${GLOBAL_PREFIX}${key}`); } /** 列出全部全局经验条目(key 剥离 `global:` 前缀,按 key 字典序) */ async listGlobalEntries() { const rows = await this.store.list(GLOBAL_PREFIX); return rows.map((r4) => ({ key: r4.key.slice(GLOBAL_PREFIX.length), value: r4.value })); } }; // src/core/memory/design-brief.ts var DESIGN_BRIEF_LOG_HEADING = "## \u5BF9\u8BDD\u4E8B\u4EF6\u8BB0\u5F55\uFF08\u81EA\u52A8\u7EF4\u62A4\uFF0C\u6700\u8FD1 15 \u6761\uFF09"; function stripDesignBriefAutoLog(notes) { if (!notes) return ""; const idx = notes.indexOf(DESIGN_BRIEF_LOG_HEADING); return (idx >= 0 ? notes.slice(0, idx) : notes).trim(); } var DESIGN_BRIEF_KEY = "design-brief"; var BRIEF_FIELD_LABELS = [ ["building_type", "\u5EFA\u7B51\u7C7B\u578B"], ["positioning", "\u5B9A\u4F4D"], ["target_users", "\u76EE\u6807\u5BA2\u7FA4"], ["site_context", "\u533A\u4F4D\u4E0E\u573A\u5730"], ["hard_constraints", "\u786C\u7EA6\u675F"], ["preferences", "\u4E1A\u4E3B\u504F\u597D"] ]; var FRONTMATTER_KEYS = BRIEF_FIELD_LABELS.map(([k]) => k); function serializeDesignBrief(brief) { const lines = ["---"]; for (const k of FRONTMATTER_KEYS) { const v2 = brief[k]; if (typeof v2 === "string" && v2.trim()) { lines.push(`${k}: ${v2.trim().replace(/\s*\n+\s*/g, "\uFF1B")}`); } } lines.push(`updated_at: ${new Date(brief.updated_at ?? Date.now()).toISOString()}`); lines.push("---"); const notes = typeof brief.notes === "string" ? brief.notes.trim() : ""; return notes ? `${lines.join("\n")} ${notes} ` : `${lines.join("\n")} `; } function parseDesignBrief(doc) { if (typeof doc !== "string" || !doc.trim()) return null; const m3 = doc.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/); if (!m3) return null; const brief = {}; for (const line2 of m3[1].split(/\r?\n/)) { const kv = line2.match(/^(\w+):\s*(.*)$/); if (!kv) continue; const [, key, raw] = kv; const value = raw.trim(); if (!value) continue; if (key === "updated_at") { const t4 = Date.parse(value); if (Number.isFinite(t4)) brief.updated_at = t4; } else if (FRONTMATTER_KEYS.includes(key)) { brief[key] = value; } } const body = doc.slice(m3[0].length).trim(); if (body) brief.notes = body; return Object.keys(brief).some((k) => k !== "updated_at") ? brief : null; } function designBriefChannelFrom(state) { return { projectId: state.projectId, getBriefDoc: state.getCurrentSources ? async () => (await state.getCurrentSources())?.brief : void 0, setBriefDoc: state.setCurrentSources ? (doc) => state.setCurrentSources({ brief: doc }) : void 0 }; } var _mem = null; function layeredMemory() { return _mem ??= new LayeredMemory(); } async function readLocalDoc(projectId) { const v2 = await layeredMemory().getProjectEntry(projectId, DESIGN_BRIEF_KEY); if (typeof v2 === "string" && v2.trim()) return v2; if (v2 && typeof v2 === "object") { const doc = serializeDesignBrief(v2); await layeredMemory().setProjectEntry(projectId, DESIGN_BRIEF_KEY, doc); return doc; } return null; } async function loadDesignBrief(channel) { if (channel.getBriefDoc) { const doc = await channel.getBriefDoc(); const brief = doc ? parseDesignBrief(doc) : null; if (brief) return brief; } if (channel.projectId) { const local = await readLocalDoc(channel.projectId); if (local) return parseDesignBrief(local); } return null; } async function saveDesignBrief(channel, brief) { const doc = serializeDesignBrief({ ...brief, updated_at: Date.now() }); if (channel.setBriefDoc) await channel.setBriefDoc(doc); if (channel.projectId) await layeredMemory().setProjectEntry(channel.projectId, DESIGN_BRIEF_KEY, doc); } async function deleteDesignBrief(channel) { if (channel.setBriefDoc) await channel.setBriefDoc(""); if (channel.projectId) await layeredMemory().deleteProjectEntry(channel.projectId, DESIGN_BRIEF_KEY); } function renderDesignBrief(brief) { if (!brief) return ""; const lines = BRIEF_FIELD_LABELS.filter(([k]) => typeof brief[k] === "string" && String(brief[k]).trim()).map(([k, label]) => `- ${label}\uFF1A${String(brief[k]).trim()}`); if (lines.length === 0) return ""; const out = [ "## \u8BBE\u8BA1\u4EFB\u52A1\u4E66\uFF08\u9879\u76EE\u7EA7\u5DF2\u786E\u8BA4\u7EA6\u675F\u2014\u2014\u6240\u6709\u8BBE\u8BA1\u51B3\u7B56\u5FC5\u987B\u9075\u5B88\uFF0C\u4FEE\u6539\u9700\u7ECF\u7528\u6237\u786E\u8BA4\uFF09", ...lines ]; const notes = stripDesignBriefAutoLog(brief.notes); if (notes) { out.push("", `\u8865\u5145\u8BF4\u660E\uFF1A${notes}`); } return out.join("\n"); } async function ensureSessionDesignBrief(sessionId, channel) { const parts = sessionId ? getSessionStateParts(sessionId) : void 0; if (parts && parts.designBrief !== void 0) return parts.designBrief; const brief = await loadDesignBrief(channel); if (parts) parts.designBrief = brief; return brief; } async function ensureSessionDesignBriefForParts(parts, channel) { if (parts && parts.designBrief !== void 0) return parts.designBrief; const brief = await loadDesignBrief(channel); if (parts) parts.designBrief = brief; return brief; } function writeSessionDesignBriefCache(sessionId, brief) { if (!sessionId) return; getSessionStateParts(sessionId).designBrief = brief; } function writeSessionDesignBriefCacheForParts(parts, brief) { if (parts) parts.designBrief = brief; } // src/tools/query.knowledge.ts var queryKnowledgeContextSchema = external_exports2.custom(); function fmt(n5) { return String(Math.round(n5 * 1e4) / 1e4); } function classifyValueInRange(value, thresholds, direction) { if (direction === "optimal") { if (thresholds.length !== 5) return null; const [t02, t12, t23, t33, t4] = thresholds; if (value < t02) return { band: "extreme_low", bandLabel: "\u6781\u4F4E", detail: `\u4F4E\u4E8E\u4E0B\u9650 ${fmt(t02)}\uFF0C\u5DEE ${fmt(t02 - value)}` }; if (value < t12) return { band: "low", bandLabel: "\u504F\u4F4E", detail: `\u533A\u95F4 [${fmt(t02)}, ${fmt(t12)})` }; if (value <= t23) return { band: "optimal", bandLabel: "\u6700\u4F73", detail: `\u533A\u95F4 [${fmt(t12)}, ${fmt(t23)}]` }; if (value <= t33) return { band: "high", bandLabel: "\u504F\u9AD8", detail: `\u533A\u95F4 (${fmt(t23)}, ${fmt(t33)}]` }; if (value <= t4) return { band: "extreme_high", bandLabel: "\u6781\u9AD8", detail: `\u533A\u95F4 (${fmt(t33)}, ${fmt(t4)}]` }; return { band: "out_of_limit", bandLabel: "\u8D85\u9650", detail: `\u8D85\u51FA\u4E0A\u9650 ${fmt(t4)}\uFF0C\u5DEE ${fmt(value - t4)}` }; } if (thresholds.length !== 4) return null; const [t0, t1, t22, t32] = thresholds; if (direction === "lowerIsBetter") { if (value < t0) return { band: "better_than_range", bandLabel: "\u4F18\u4E8E\u53C2\u8003\u533A\u95F4", detail: `\u4F4E\u4E8E good \u4E0B\u9650 ${fmt(t0)}` }; if (value <= t1) return { band: "good", bandLabel: "good\uFF08\u4F18\uFF09", detail: `\u533A\u95F4 [${fmt(t0)}, ${fmt(t1)}]` }; if (value <= t22) return { band: "acceptable", bandLabel: "acceptable\uFF08\u53EF\u63A5\u53D7\uFF09", detail: `\u533A\u95F4 (${fmt(t1)}, ${fmt(t22)}]` }; if (value <= t32) return { band: "poor", bandLabel: "poor\uFF08\u5DEE\uFF09", detail: `\u533A\u95F4 (${fmt(t22)}, ${fmt(t32)}]` }; return { band: "beyond_range", bandLabel: "\u8D85\u51FA\u53C2\u8003\u533A\u95F4", detail: `\u8D85\u51FA poor \u4E0A\u9650 ${fmt(t32)}\uFF0C\u5DEE ${fmt(value - t32)}` }; } if (value < t0) return { band: "below_range", bandLabel: "\u4F4E\u4E8E\u53C2\u8003\u4E0B\u9650", detail: `\u4F4E\u4E8E poor \u4E0B\u9650 ${fmt(t0)}\uFF0C\u5DEE ${fmt(t0 - value)}` }; if (value < t1) return { band: "poor", bandLabel: "poor\uFF08\u5DEE\uFF09", detail: `\u533A\u95F4 [${fmt(t0)}, ${fmt(t1)})` }; if (value < t22) return { band: "acceptable", bandLabel: "acceptable\uFF08\u53EF\u63A5\u53D7\uFF09", detail: `\u533A\u95F4 [${fmt(t1)}, ${fmt(t22)})` }; if (value <= t32) return { band: "good", bandLabel: "good\uFF08\u4F18\uFF09", detail: `\u533A\u95F4 [${fmt(t22)}, ${fmt(t32)}]` }; return { band: "better_than_range", bandLabel: "\u4F18\u4E8E\u53C2\u8003\u533A\u95F4", detail: `\u9AD8\u4E8E good \u4E0A\u9650 ${fmt(t32)}` }; } var DIRECTION_LABELS = { lowerIsBetter: "\u8D8A\u5C0F\u8D8A\u597D", higherIsBetter: "\u8D8A\u5927\u8D8A\u597D", optimal: "\u6700\u9002\u8303\u56F4" }; var SCENARIO_MODULES = { chat: ["strategy"], simulation: ["parameter"], general: ["case", "strategy"] }; function pick2(obj, keys) { const out = {}; for (const k of keys) { if (obj && obj[k] !== void 0) out[k] = obj[k]; } return out; } function summarizeStrategy(s2) { return pick2(s2, [ "id", "name", "category", "description", "applicableBuildingTypes", "applicableClimateZones", "relatedMetricIds", "parameterIds", "standardIds", "expectedImpact" ]); } function summarizeParameter(p2) { return pick2(p2, [ "id", "name", "category", "subCategory", "description", "constraint", "defaultValue", "sweepRangeRows", "aiHints", "sensitivity", "sweepPriority", "relatedMetricIds" ]); } function summarizeCase(c2) { return pick2(c2, [ "id", "title", "buildingType", "climateZone", "buildingFunction", "description", "metricValues", "strategyIds", "standardIds" ]); } var MODULE_SUMMARIZERS = { strategy: summarizeStrategy, parameter: summarizeParameter, case: summarizeCase }; function matchesQuery(entry, query) { const q2 = query.toLowerCase(); const fields = [entry?.name, entry?.nameEn, entry?.title, entry?.description, entry?.category, entry?.subCategory]; if (fields.some((f2) => typeof f2 === "string" && f2.toLowerCase().includes(q2))) return true; if (Array.isArray(entry?.tags) && entry.tags.some((t4) => typeof t4 === "string" && t4.toLowerCase().includes(q2))) return true; return false; } function createQueryKnowledge() { return tool({ description: '\u67E5\u8BE2\u7ED3\u6784\u5316\u5EFA\u7B51\u77E5\u8BC6\u5E93\uFF08\u6027\u80FD\u6307\u6807\u3001\u6A21\u62DF\u53C2\u6570\u3001\u6807\u51C6\u3001\u7B56\u7565\u3001\u6848\u4F8B\uFF09\u3002search=\u6309\u5173\u952E\u8BCD\u5B9A\u4F4D\u6761\u76EE\uFF08\u8FD4\u56DE id+module \u6E05\u5355\uFF0C\u53EF\u9644 scenario/module \u8FC7\u6EE4\uFF09\uFF1Bget=\u6309 module+id \u53D6\u6761\u76EE\u5168\u6587\uFF08\u6307\u6807\u542B\u53C2\u8003\u533A\u95F4\u8868/\u89E3\u8BFB/\u6765\u6E90\u6807\u51C6\uFF0C\u53C2\u6570\u542B\u7EA6\u675F\u4E0E\u626B\u63CF\u8303\u56F4\uFF09\uFF1Bcompare=\u628A\u6A21\u62DF\u7ED3\u679C\u6570\u503C\u4E0E\u6307\u6807\u53C2\u8003\u9608\u503C\u6BD4\u5BF9\u5224\u5B9A\u8FBE\u6807\u6863\u4F4D\uFF08\u9700\u6307\u6807 id \u4E0E\u6570\u503C\uFF0C\u53EF\u9644 buildingType/climateZone/roomFunction \u4E0A\u4E0B\u6587\u7CBE\u786E\u9009\u884C\uFF09\uFF1Bcollect=\u6309\u8BED\u5883\u6279\u91CF\u7EC4\u88C5\u77E5\u8BC6\u5305\u6CE8\u5165\u4E0A\u4E0B\u6587\u2014\u2014scenario=chat \u53D6\u8BBE\u8BA1\u7B56\u7565\u8868\uFF08\u5BF9\u8BDD\u54A8\u8BE2\uFF09\u3001scenario=simulation \u53D6\u6A21\u62DF\u53C2\u6570\u8868\uFF08\u8C03\u7528 parameter_sweep/\u6A21\u62DF\u5DE5\u5177\u524D\u67E5\u7EA6\u675F/\u626B\u63CF\u8303\u56F4/aiHints\uFF09\u3001scenario=general \u53D6\u6848\u4F8B+\u7B56\u7565\uFF08\u7EFC\u5408\u7814\u5224/\u65B9\u6848\u5BF9\u6807\uFF09\uFF0C\u53EF\u9644 query \u8FC7\u6EE4\uFF08\u5982"\u56F4\u62A4\u7ED3\u6784"\uFF09\u3002\u4E0D\u786E\u5B9A\u6761\u76EE id \u65F6\u5148 search\uFF1B\u5224\u5B9A\u6A21\u62DF\u7ED3\u679C\u662F\u5426\u8FBE\u6807\u65F6\u5148\u53D6\u6A21\u62DF\u503C\u518D compare\u3002', inputSchema: external_exports2.object({ action: external_exports2.enum(["search", "get", "compare", "collect"]).describe("search=\u5B9A\u4F4D\u6761\u76EE\uFF1Bget=\u53D6\u6761\u76EE\u5168\u6587\uFF1Bcompare=\u6570\u503C vs \u53C2\u8003\u9608\u503C\u5224\u5B9A\uFF1Bcollect=\u6309\u8BED\u5883\u6279\u91CF\u7EC4\u88C5\u77E5\u8BC6\u5305"), scenario: external_exports2.enum(["chat", "simulation", "general"]).optional().describe("\u8BED\u5883\uFF1Achat=\u5BF9\u8BDD\u54A8\u8BE2\uFF08\u7B56\u7565\u8868\uFF09\uFF1Bsimulation=\u6A21\u62DF\u8C03\u7528\uFF08\u53C2\u6570\u8868\uFF09\uFF1Bgeneral=\u7EFC\u5408\u7814\u5224\uFF08\u6848\u4F8B+\u7B56\u7565\uFF09\u3002collect \u5FC5\u586B\uFF0Csearch \u53EF\u9009\u4F5C\u8FC7\u6EE4\u5668"), query: external_exports2.string().optional().describe("search/collect \u7528\uFF1A\u68C0\u7D22\u5173\u952E\u8BCD\uFF08\u6307\u6807\u540D/\u53C2\u6570\u540D/\u6807\u51C6\u53F7/\u7C7B\u522B\u7B49\uFF09"), maxResults: external_exports2.number().optional().describe("search/collect \u7528\uFF1A\u6700\u591A\u8FD4\u56DE\u6761\u6570\uFF08\u7F3A\u7701 5\uFF09"), module: external_exports2.string().optional().describe("get \u7528\uFF1A\u6761\u76EE\u6A21\u5757\uFF08metric/parameter/standard/strategy/case/rag\uFF09\uFF1Bsearch \u53EF\u9009\u4F5C\u7CBE\u786E\u6A21\u5757\u8FC7\u6EE4"), id: external_exports2.string().optional().describe("get/compare \u7528\uFF1A\u6761\u76EE id\uFF08compare \u4EC5\u652F\u6301 metric\uFF09"), value: external_exports2.number().optional().describe("compare \u7528\uFF1A\u5F85\u5224\u5B9A\u6570\u503C\uFF08\u6A21\u62DF\u7ED3\u679C\u503C\uFF09"), buildingType: external_exports2.string().optional().describe("compare \u7528\uFF08\u53EF\u9009\uFF09\uFF1A\u5EFA\u7B51\u7C7B\u578B\u4E0A\u4E0B\u6587\uFF0C\u7CBE\u786E\u9009\u62E9\u9608\u503C\u884C"), climateZone: external_exports2.string().optional().describe("compare \u7528\uFF08\u53EF\u9009\uFF09\uFF1A\u6C14\u5019\u5206\u533A\u4E0A\u4E0B\u6587"), roomFunction: external_exports2.string().optional().describe("compare \u7528\uFF08\u53EF\u9009\uFF09\uFF1A\u623F\u95F4\u529F\u80FD\u4E0A\u4E0B\u6587") }), contextSchema: queryKnowledgeContextSchema, execute: (async (params, { context: env }) => { try { if (params.action === "search") { const fn3 = env.searchKnowledgeBaseFn; if (!fn3) return { status: "unavailable", message: "\u5BBF\u4E3B\u672A\u6CE8\u5165 searchKnowledgeBaseFn \u80FD\u529B\uFF0C\u65E0\u6CD5\u68C0\u7D22\u77E5\u8BC6\u5E93\u3002" }; if (!params.query) return { status: "error", message: "search \u9700\u8981 query \u53C2\u6570\u3002" }; let hits = await fn3(params.query, params.maxResults); const modules = params.module ? [params.module] : params.scenario ? SCENARIO_MODULES[params.scenario] : null; if (modules && hits) hits = hits.filter((h2) => modules.includes(h2.module)); if (!hits || hits.length === 0) { return { status: "success", message: `\u672A\u627E\u5230\u4E0E\u300C${params.query}\u300D\u5339\u914D\u7684\u77E5\u8BC6\u6761\u76EE\u3002`, hits: [] }; } return { status: "success", hits, message: `\u627E\u5230 ${hits.length} \u6761\u5019\u9009\u6761\u76EE\u3002\u7528 get(module, id) \u53D6\u6761\u76EE\u5168\u6587\uFF1B\u6307\u6807\u6570\u503C\u5224\u5B9A\u7528 compare(id, value)\u3002` }; } if (params.action === "get") { const fn3 = env.getKnowledgeEntryFn; if (!fn3) return { status: "unavailable", message: "\u5BBF\u4E3B\u672A\u6CE8\u5165 getKnowledgeEntryFn \u80FD\u529B\uFF0C\u65E0\u6CD5\u8BFB\u53D6\u77E5\u8BC6\u6761\u76EE\u3002" }; if (!params.module || !params.id) return { status: "error", message: "get \u9700\u8981 module \u548C id \u53C2\u6570\u3002" }; const entry = await fn3(params.module, params.id); if (entry === null || entry === void 0) { return { status: "not_found", message: `\u672A\u627E\u5230\u77E5\u8BC6\u6761\u76EE\uFF08module=${params.module}, id=${params.id}\uFF09\u3002\u53EF\u5148 search \u5B9A\u4F4D\u6B63\u786E\u7684 id\u3002` }; } return { status: "success", module: params.module, id: params.id, entry }; } if (params.action === "collect") { const fn3 = env.listKnowledgeEntriesFn; if (!fn3) return { status: "unavailable", message: "\u5BBF\u4E3B\u672A\u6CE8\u5165 listKnowledgeEntriesFn \u80FD\u529B\uFF0C\u65E0\u6CD5\u6279\u91CF\u63D0\u53D6\u77E5\u8BC6\u3002" }; if (!params.scenario) return { status: "error", message: "collect \u9700\u8981 scenario \u53C2\u6570\uFF08chat=\u5BF9\u8BDD\u54A8\u8BE2\u2192\u7B56\u7565\u8868\uFF1Bsimulation=\u6A21\u62DF\u8C03\u7528\u2192\u53C2\u6570\u8868\uFF1Bgeneral=\u7EFC\u5408\u7814\u5224\u2192\u6848\u4F8B+\u7B56\u7565\uFF09\u3002" }; const modules = SCENARIO_MODULES[params.scenario]; const limit = params.maxResults ?? 20; const out = {}; let total = 0; for (const mod of modules) { const entries = await fn3(mod); const summarize = MODULE_SUMMARIZERS[mod] ?? ((e5) => pick2(e5, ["id", "name", "title", "description"])); let list = (entries || []).map(summarize); if (params.query) list = list.filter((e5) => matchesQuery(e5, params.query)); list = list.slice(0, limit); if (list.length > 0) out[mod] = list; total += list.length; } if (total === 0) { return { status: "success", scenario: params.scenario, modules: {}, message: `\u8BED\u5883 ${params.scenario} \u4E0B\u672A\u627E\u5230\u5339\u914D\u6761\u76EE${params.query ? `\uFF08query=${params.query}\uFF09` : ""}\u3002` }; } return { status: "success", scenario: params.scenario, modules: out, message: `\u5DF2\u6309\u300C${params.scenario}\u300D\u8BED\u5883\u7EC4\u88C5 ${total} \u6761\u77E5\u8BC6\u6458\u8981\uFF08${Object.keys(out).join(" + ")}\uFF09\u3002\u4EE5\u4E0A\u6761\u76EE\u53EF\u76F4\u63A5\u4F5C\u4E3A\u5F53\u524D\u8BED\u5883\u7684\u80CC\u666F\u77E5\u8BC6\u4F7F\u7528\uFF1B\u9700\u8981\u67D0\u6761\u5B8C\u6574\u5185\u5BB9\u65F6 get(module, id)\u3002` }; } const fn2 = env.resolveKnowledgeThresholdsFn; if (!fn2) return { status: "unavailable", message: "\u5BBF\u4E3B\u672A\u6CE8\u5165 resolveKnowledgeThresholdsFn \u80FD\u529B\uFF0C\u65E0\u6CD5\u6BD4\u5BF9\u53C2\u8003\u9608\u503C\u3002" }; if (!params.id) return { status: "error", message: "compare \u9700\u8981 id \u53C2\u6570\uFF08\u6307\u6807\u6761\u76EE id\uFF0C\u53EF\u5148 search \u5B9A\u4F4D\uFF09\u3002" }; if (typeof params.value !== "number" || !Number.isFinite(params.value)) { return { status: "error", message: "compare \u9700\u8981\u6709\u6548\u7684\u6570\u503C\u53C2\u6570 value\u3002" }; } let context = params.buildingType || params.climateZone || params.roomFunction ? { buildingType: params.buildingType, climateZone: params.climateZone, roomFunction: params.roomFunction } : void 0; if (!context) { const channel = designBriefChannelFrom(env); const brief = env.sessionParts ? await ensureSessionDesignBriefForParts(env.sessionParts, channel) : await ensureSessionDesignBrief(env.sessionId, channel); if (brief?.building_type) context = { buildingType: brief.building_type }; } const resolved = await fn2(params.id, context); if (!resolved) { return { status: "not_found", message: `\u6307\u6807\u300C${params.id}\u300D\u4E0D\u5B58\u5728\u6216\u65E0\u53C2\u8003\u9608\u503C\u8868\uFF08\u53EF\u80FD\u547D\u4E2D\u884C\u4E0E\u4E0A\u4E0B\u6587\u4E0D\u5339\u914D\uFF09\u3002\u53EF\u5148 search/get \u786E\u8BA4\u6307\u6807 id \u4E0E\u53EF\u7528\u4E0A\u4E0B\u6587\u3002` }; } const classified = classifyValueInRange(params.value, resolved.thresholds, resolved.direction); if (!classified) { return { status: "error", message: `\u6307\u6807\u300C${params.id}\u300D\u7684\u9608\u503C\u6570\u636E\u683C\u5F0F\u5F02\u5E38\uFF08\u65B9\u5411 ${resolved.direction}\uFF0C\u9608\u503C ${resolved.thresholds.length} \u4E2A\u8FB9\u754C\uFF09\u3002` }; } const unit = resolved.unit ? ` ${resolved.unit}` : ""; const verdict = `${resolved.metricName}=${params.value}${unit}\uFF08${DIRECTION_LABELS[resolved.direction]}\uFF09\uFF1A${classified.bandLabel}\uFF0C${classified.detail}\u3002\u53C2\u8003\u9608\u503C [${resolved.thresholds.map(fmt).join(", ")}]` + (resolved.standardId ? `\uFF0C\u6807\u51C6\u6765\u6E90 ${resolved.standardId}` : ""); return { status: "success", metric: { id: resolved.metricId, name: resolved.metricName, unit: resolved.unit }, value: params.value, direction: resolved.direction, band: classified.band, bandLabel: classified.bandLabel, thresholds: resolved.thresholds, ...resolved.standardId ? { standardId: resolved.standardId } : {}, verdict }; } catch (err2) { return { status: "error", message: `\u77E5\u8BC6\u5E93\u67E5\u8BE2\u5931\u8D25: ${err2?.message ?? String(err2)}` }; } }) }); } // src/gsa/adjacency.ts async function analyzeAdjacency(aml, options) { const url2 = `${options?.gsaUrl || "http://localhost:8000"}/api/v1/analyze-adjacency`; try { const res = await fetch(url2, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ aml }), signal: AbortSignal.timeout(3e4) }); if (!res.ok) { const text2 = await res.text().catch(() => ""); throw new Error(`HTTP ${res.status}: ${text2.slice(0, 200)}`); } const response = await res.json(); if (response.error) { throw new Error(response.error); } return { adjacency_pairs: response.adjacency_pairs || [], circulation_flows: response.circulation_flows || [], total_pairs: response.total_pairs, total_flows: response.total_flows }; } catch (err2) { throw new Error(`GSA \u90BB\u63A5\u5206\u6790\u5931\u8D25: ${err2.message || String(err2)}`); } } // src/tools/query.spatial.graph.ts function matchRoom(pair, side, idOrName) { const id = pair[side]; const name24 = (side === "from" ? pair.from_name : pair.to_name) || ""; const q2 = idOrName.toLowerCase(); return id === idOrName || name24.toLowerCase() === q2 || name24.toLowerCase().includes(q2); } function pairsOf(pairs, idOrName) { return pairs.filter((p2) => matchRoom(p2, "from", idOrName) || matchRoom(p2, "to", idOrName)); } function formatPair(p2) { const len = p2.shared_length_m != null ? ` (${p2.shared_length_m.toFixed(2)}m)` : ""; const type = p2.type && p2.type !== "adjacent" ? ` [${p2.type}]` : ""; return `${p2.from_name || p2.from} <-> ${p2.to_name || p2.to}${type}${len}`; } var querySpatialGraphContextSchema = external_exports2.custom(); function createQuerySpatialGraph() { return tool({ description: "\u67E5\u8BE2\u5EFA\u7B51\u7A7A\u95F4\u62D3\u6251\u2014\u2014\u623F\u95F4\u90BB\u63A5\u5173\u7CFB\uFF08\u6570\u636E\u6E90\uFF1AGSA \u90BB\u63A5\u5206\u6790\uFF09\u3002neighbors=\u5217\u51FA\u67D0\u623F\u95F4\u7684\u76F8\u90BB\u623F\u95F4\uFF1Bcheck_adjacency=\u5224\u65AD\u4E24\u4E2A\u623F\u95F4\u662F\u5426\u76F8\u90BB\uFF1Bgraph_summary=\u5168\u697C\u90BB\u63A5\u5173\u7CFB\u6C47\u603B\uFF08\u542B\u95E8/\u6D41\u7EBF\uFF09\u3002", inputSchema: external_exports2.object({ query_type: external_exports2.enum(["neighbors", "check_adjacency", "graph_summary"]).describe("\u67E5\u8BE2\u7C7B\u578B"), target_room_id: external_exports2.string().optional().describe("\u76EE\u6807\u623F\u95F4 ID \u6216\u540D\u79F0\uFF08neighbors / check_adjacency \u5FC5\u586B\uFF09"), secondary_room_id: external_exports2.string().optional().describe("\u7B2C\u4E8C\u4E2A\u623F\u95F4 ID \u6216\u540D\u79F0\uFF08check_adjacency \u5FC5\u586B\uFF09"), gsaUrl: external_exports2.string().optional().describe("GSA \u670D\u52A1\u5730\u5740\uFF08\u9ED8\u8BA4 http://localhost:8000\uFF09") }), contextSchema: querySpatialGraphContextSchema, execute: (async (params, { context }) => { if (!context.getCurrentAml) { return { status: "unavailable", message: "\u5BBF\u4E3B\u672A\u6CE8\u5165 getCurrentAml \u80FD\u529B\uFF0C\u65E0\u6CD5\u67E5\u8BE2\u7A7A\u95F4\u62D3\u6251\u3002" }; } const { query_type, target_room_id, secondary_room_id } = params; try { const aml = await context.getCurrentAml(); if (!aml) { return { status: "no_data", message: "\u5F53\u524D\u6CA1\u6709 AML \u6570\u636E\u3002\u8BF7\u5148\u751F\u6210\u6216\u52A0\u8F7D\u65B9\u6848\u3002" }; } const { adjacency_pairs, circulation_flows } = await analyzeAdjacency(aml, { gsaUrl: params.gsaUrl }); context.toolContext?.lastResults?.set("query-spatial-graph", { adjacency_pairs, circulation_flows }); if (query_type === "graph_summary") { if (adjacency_pairs.length === 0) { return { status: "success", message: "The building has no detected room adjacencies." }; } const lines = adjacency_pairs.map((p2) => `- ${formatPair(p2)}`); let message = `Graph Summary (Room Adjacencies): ${lines.join("\n")}`; if (circulation_flows.length > 0) { const flowLines = circulation_flows.map((p2) => `- ${p2.from_name || p2.from} -> ${p2.to_name || p2.to} [${p2.type || "flow"}]`); message += ` Circulation Flows: ${flowLines.join("\n")}`; } return { status: "success", message, data: { adjacency_pairs, circulation_flows } }; } if (!target_room_id) { return { status: "error", message: `target_room_id is required for ${query_type}.` }; } const targetPairs = pairsOf(adjacency_pairs, target_room_id); if (targetPairs.length === 0) { return { status: "error", message: `Room '${target_room_id}' not found or has no adjacencies.` }; } if (query_type === "neighbors") { const neighbors = targetPairs.map((p2) => { const isFrom = matchRoom(p2, "from", target_room_id) && !matchRoom(p2, "to", target_room_id); const other = isFrom ? p2.to : p2.from; const otherName = isFrom ? p2.to_name : p2.from_name; return { id: other, name: otherName || other, type: p2.type || "adjacent", shared_length_m: p2.shared_length_m }; }); const names = neighbors.map((n5) => `${n5.name} (${n5.id.substring(0, 6)})`).join(", "); return { status: "success", message: `Room ${target_room_id} is adjacent to: ${names}.`, data: neighbors }; } if (!secondary_room_id) { return { status: "error", message: "secondary_room_id is required for check_adjacency." }; } const hit = targetPairs.find( (p2) => matchRoom(p2, "from", target_room_id) && matchRoom(p2, "to", secondary_room_id) || matchRoom(p2, "to", target_room_id) && matchRoom(p2, "from", secondary_room_id) ); const aName = (targetPairs[0].from_name && matchRoom(targetPairs[0], "from", target_room_id) ? targetPairs[0].from_name : targetPairs[0].to_name) || target_room_id; return { status: "success", message: hit ? `Yes, ${aName} and ${secondary_room_id} are adjacent (${hit.type || "adjacent"}).` : `No, ${aName} and ${secondary_room_id} do NOT touch.`, data: { adjacent: !!hit, pair: hit } }; } catch (err2) { return { status: "error", message: `\u7A7A\u95F4\u62D3\u6251\u67E5\u8BE2\u5931\u8D25: ${err2?.message ?? String(err2)}` }; } }) }); } // src/gsa/envelope.ts async function envelopeStats(aml, options) { const url2 = `${options?.gsaUrl || "http://localhost:8000"}/api/v1/envelope-stats`; try { const res = await fetch(url2, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ aml, include_internal: options?.includeInternal ?? false }), signal: AbortSignal.timeout(3e4) }); if (!res.ok) { const text2 = await res.text().catch(() => ""); throw new Error(`HTTP ${res.status}: ${text2.slice(0, 200)}`); } const response = await res.json(); if (response.error) { throw new Error(response.error); } return { rooms: response.rooms || [], totals: response.totals }; } catch (err2) { throw new Error(`GSA \u56F4\u62A4\u7ED3\u6784\u7EDF\u8BA1\u5931\u8D25: ${err2.message || String(err2)}`); } } // src/tools/envelope.stats.ts var envelopeStatsContextSchema = external_exports2.custom(); function createEnvelopeStats() { return tool({ description: '\u67E5\u8BE2\u6BCF\u4E2A\u623F\u95F4\u7684\u56F4\u62A4\u7ED3\u6784\u7EDF\u8BA1\u2014\u2014\u5916\u5899\u9762\u79EF\u3001\u7A97\u9762\u79EF\u3001\u5B9E\u9645\u7A97\u5899\u6BD4(WWR)\u3001\u5404\u671D\u5411\u5899\u9762\u4E0E\u7A97\u5217\u8868\uFF08\u6570\u636E\u6E90\uFF1AGSA envelope-stats\uFF09\u3002\u56DE\u7B54"\u8FD9\u4E2A\u623F\u95F4\u671D\u54EA/\u7A97\u5899\u6BD4\u591A\u5C11/\u5916\u5899\u9762\u79EF"\u7C7B\u95EE\u9898\u65F6\u4F7F\u7528\u3002', inputSchema: external_exports2.object({ room_id: external_exports2.string().optional().describe("\u53EA\u770B\u6307\u5B9A\u623F\u95F4\uFF08ID \u6216\u540D\u79F0\uFF09\uFF1B\u7F3A\u7701\u8F93\u51FA\u5168\u90E8\u623F\u95F4 + \u5168\u697C\u6C47\u603B"), include_internal: external_exports2.boolean().optional().describe("\u662F\u5426\u9644\u5E26\u5185\u5899\u5217\u8868\uFF08\u9ED8\u8BA4 false\uFF09"), gsaUrl: external_exports2.string().optional().describe("GSA \u670D\u52A1\u5730\u5740\uFF08\u9ED8\u8BA4 http://localhost:8000\uFF09") }), contextSchema: envelopeStatsContextSchema, execute: (async (params, { context }) => { if (!context.getCurrentAml) { return { status: "unavailable", message: "\u5BBF\u4E3B\u672A\u6CE8\u5165 getCurrentAml \u80FD\u529B\uFF0C\u65E0\u6CD5\u67E5\u8BE2\u56F4\u62A4\u7ED3\u6784\u3002" }; } try { const aml = await context.getCurrentAml(); if (!aml) { return { status: "no_data", message: "\u5F53\u524D\u6CA1\u6709 AML \u6570\u636E\u3002\u8BF7\u5148\u751F\u6210\u6216\u52A0\u8F7D\u65B9\u6848\u3002" }; } const result = await envelopeStats(aml, { gsaUrl: params.gsaUrl, includeInternal: params.include_internal }); context.toolContext?.lastResults?.set("envelope-stats", result); if (params.room_id) { const q2 = params.room_id.toLowerCase(); const room = result.rooms.find((r4) => r4.id === params.room_id || (r4.name || "").toLowerCase() === q2 || (r4.name || "").toLowerCase().includes(q2)); if (!room) { return { status: "error", message: `Room '${params.room_id}' not found.` }; } return { status: "success", data: room }; } return { status: "success", data: { totals: result.totals, rooms: result.rooms.map((r4) => ({ id: r4.id, name: r4.name, floor: r4.floor, area: r4.area, envelope_area: r4.envelope_area, window_area: r4.window_area, wwr_actual: r4.wwr_actual, orientations: (r4.walls || []).map((w3) => w3.orientation).filter(Boolean) })) } }; } catch (err2) { return { status: "error", message: `\u56F4\u62A4\u7ED3\u6784\u7EDF\u8BA1\u5931\u8D25: ${err2?.message ?? String(err2)}` }; } }) }); } // src/gsa/validate.ts async function validateModel(aml, options) { const url2 = `${options?.gsaUrl || "http://localhost:8000"}/api/v1/validate`; try { const res = await fetch(url2, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ aml, ...options?.checks ? { checks: options.checks } : {}, ...options?.minPassageWidth !== void 0 ? { min_passage_width: options.minPassageWidth } : {}, ...options?.compileLevel ? { compile_level: options.compileLevel } : {} }), signal: AbortSignal.timeout(3e4) }); if (!res.ok) { const text2 = await res.text().catch(() => ""); throw new Error(`HTTP ${res.status}: ${text2.slice(0, 200)}`); } const response = await res.json(); if (response.error) { throw new Error(response.error); } return { valid: response.valid ?? (response.issues || []).length === 0, issues: response.issues || [], summary: response.summary }; } catch (err2) { throw new Error(`GSA \u6A21\u578B\u6821\u9A8C\u5931\u8D25: ${err2.message || String(err2)}`); } } // src/tools/flow-engine.ts var flowContextSchema = external_exports2.custom(); function ensureFlow(parts) { if (!parts.flow) parts.flow = { done: {} }; return parts.flow; } function getFlowVar(parts, key) { const v2 = parts?.flow?.vars?.[key]; return typeof v2 === "string" ? v2 : void 0; } function getFlowRequirement(parts, key) { return parts?.flow?.requirements?.[key]; } function levelFromDesignStep(designStep) { return !designStep || designStep <= 2 ? "massing" : designStep <= 4 ? "structure" : "full"; } var COMPILE_STAGES = ["massing", "structure", "full"]; function resolveCompileStage(parts, explicit, designStep) { if (explicit && COMPILE_STAGES.includes(explicit)) return explicit; const v2 = getFlowVar(parts, "stage"); if (v2 && COMPILE_STAGES.includes(v2)) return v2; return levelFromDesignStep(designStep); } function getPath(obj, path) { let cur = obj; for (const key of path.split(".")) { if (cur == null || typeof cur !== "object") return void 0; cur = cur[key]; } return cur; } function recordNodeDone(parts, nodeId, detail, outcome) { const flow = ensureFlow(parts); const prev = flow.done[nodeId]; flow.done[nodeId] = { at: Date.now(), // 幂等覆盖保留已累计的计数覆盖(coverage 节点逐户出图记录不因重复调用丢失) ...prev?.covered && prev.covered.length > 0 ? { covered: prev.covered } : {}, ...detail ? { detail } : {}, ...outcome ? { outcome } : {} }; const node = parts.flowDef?.find((n5) => n5.id === nodeId); if (node?.sets) { const allowed = node.outcome_field ? outcome !== void 0 && (node.sets_when ?? []).includes(outcome) : true; if (allowed) { if (!flow.vars) flow.vars = {}; Object.assign(flow.vars, node.sets); } } } function allowSideEffects(node, outcome) { return !node.outcome_field || outcome !== void 0 && (node.sets_when ?? []).includes(outcome); } function safeRegExp(src) { try { return new RegExp(src); } catch { return null; } } function stashFlowGateQuestions(parts, questions) { parts.pendingFlowGates = questions.filter((q2) => typeof q2.question === "string" && q2.question).map((q2) => ({ question: q2.question, ...q2.gate ? { gate: q2.gate } : {}, ...(q2.options ?? []).some((o3) => o3 && typeof o3.label === "string" && o3.label) ? { options: (q2.options ?? []).filter((o3) => o3 && typeof o3.label === "string" && o3.label).map((o3) => ({ label: o3.label, ...o3.key ? { key: o3.key } : {}, ...o3.value !== void 0 ? { value: o3.value } : {} })) } : {} })); } function stashAskUserCandidateMap(parts, questions) { const candidates = parts.toolContext?.lastResults?.get("generate-candidates")?.candidates; if (!Array.isArray(candidates) || candidates.length === 0) return; const refRe = /^\$ref:generate-candidates\.candidates\.(\d+)\.preview_svg$/; const matchIndex = (svg) => { if (typeof svg !== "string" || !svg) return void 0; const m3 = svg.trim().match(refRe); if (m3) { const n5 = Number(m3[1]); return candidates[n5] ? n5 : void 0; } const idx = candidates.findIndex((c2) => typeof c2.preview_svg === "string" && c2.preview_svg === svg.trim()); return idx >= 0 ? idx : void 0; }; const mapped = questions.filter((q2) => typeof q2.question === "string" && q2.question).map((q2) => ({ question: q2.question, options: (q2.options ?? []).filter((o3) => typeof o3.label === "string" && o3.label).map((o3) => ({ label: o3.label, ...matchIndex(o3.svg) !== void 0 ? { candidateIndex: matchIndex(o3.svg) } : {} })) })).filter((q2) => q2.options.some((o3) => o3.candidateIndex !== void 0)); if (mapped.length > 0) parts.pendingAskUserCandidateMap = mapped; } function candidateFingerprintOf(candidates) { if (!Array.isArray(candidates) || candidates.length === 0) return []; return candidates.map((c2, i4) => { const recipe = typeof c2.stats?.recipe === "string" && c2.stats.recipe ? c2.stats.recipe : ""; const id = typeof c2.id === "string" && c2.id ? c2.id : `c${i4}`; return recipe ? `${recipe}:${id}` : id; }); } var CANDIDATE_VARIANT_FIELDS = [ "core_scale", "core_bias", "corridor_delta", "zone_template", "zone_rotation" ]; function candidateVariantKeyOf(c2) { const variant = c2?.stats?.variant; if (!variant || typeof variant !== "object" || Array.isArray(variant)) return void 0; const entries = []; for (const k of CANDIDATE_VARIANT_FIELDS) { const v2 = variant[k]; if (v2 !== void 0) entries.push(`${k}=${JSON.stringify(v2)}`); } return JSON.stringify(entries); } function recordScriptSuccess(parts, scriptName) { const node = parts.flowDef?.find((n5) => n5.kind === "script" && n5.id === scriptName); if (!node) return; recordNodeDone(parts, node.id); } function recordToolSuccess(parts, toolName, detail, result, params) { const node = parts.flowDef?.find((n5) => n5.kind === "tool" && n5.tool === toolName && (!n5.match || Object.entries(n5.match).every(([k, v2]) => getPath(params, k) === v2))); if (!node) return; const outcome = node.outcome_field && result !== void 0 ? ((v2) => v2 === void 0 || v2 === null ? void 0 : String(v2))(getPath(result, node.outcome_field)) : void 0; recordNodeDone(parts, node.id, detail, outcome); const flow = ensureFlow(parts); const rec = flow.done[node.id]; if (node.coverage && params !== void 0 && params !== null) { const id = getPath(params, node.coverage.id_param); if (id !== void 0 && id !== null) { const idStr = String(id); if (idStr && !rec.covered?.includes(idStr)) rec.covered = [...rec.covered ?? [], idStr]; } } if (allowSideEffects(node, outcome) && node.collect && result !== void 0) { const items = getPath(result, node.collect.from); if (Array.isArray(items)) { const re2 = node.collect.name_re ? safeRegExp(node.collect.name_re) : null; const ids = []; for (const item of items) { const name24 = item && typeof item === "object" ? String(item.name ?? "") : String(item); const trimmed = name24.trim(); if (trimmed && (!re2 || re2.test(trimmed)) && !ids.includes(trimmed)) ids.push(trimmed); } if (ids.length > 0) { if (!flow.vars) flow.vars = {}; flow.vars[node.collect.key] = ids; } } } } function assertCandidateGateOpen(parts, params) { const gate = parts.pendingCandidateGate; if (!gate) return null; if (!params || typeof params !== "object") return null; const aml = params.aml; if (typeof aml !== "string" || !aml.startsWith("$ref:generate-candidates")) return null; const acceptHint = gate.produced === 1 ? "\u5019\u9009\u88C1\u51B3\u5361\u4F1A\u7ED9\u51FA\u300C\u91C7\u7528\u73B0\u6709 1 \u7248 / \u91CD\u65B0\u751F\u6210\u8865\u9F50\u300D\u9009\u9879\uFF0C\u7531\u7528\u6237\u62CD\u677F\u540E\u81EA\u52A8\u7F16\u8BD1" : `\u6BD4\u9009\u5361\u5DF2\u5217\u51FA ${gate.produced} \u4E2A\u5019\u9009\uFF1A\u7528\u6237\u5728\u5176\u4E2D\u9009\u5B9A\u8981\u91C7\u7528\u7684\u65B9\u6848\u5373\u81EA\u52A8\u7F16\u8BD1\uFF08\u82E5\u90FD\u4E0D\u6EE1\u610F\u53EF\u8981\u6C42\u91CD\u65B0\u751F\u6210\u8865\u9F50 ${gate.requested} \u4E2A\uFF09\uFF1B\u4E0D\u9700\u8981\u7B2C\u4E8C\u5F20\u88C1\u51B3\u5361`; return [ `\u5019\u9009\u6BD4\u9009\u95F8\u95E8\u672A\u901A\u8FC7\uFF1A\u7528\u6237\u8981\u6C42 ${gate.requested} \u4E2A\u5019\u9009\uFF08\u5F53\u524D\u5B9E\u9645 ${gate.produced} \u4E2A\uFF09\uFF0C\u5C1A\u672A\u7ECF\u7528\u6237\u88C1\u51B3\u3002`, `\u7981\u6B62\u76F4\u63A5 apply_design \u5F15\u7528\u5019\u9009 AML\u2014\u2014${acceptHint}\uFF1B\u672C\u8F6E\u4E0D\u8981\u518D\u8C03\u7528 apply_design\uFF0C\u7ED3\u675F\u5E76\u7B49\u5F85\u7528\u6237\u9009\u62E9\u3002` ].join(""); } function wrapApplyDesignWithFlow(applyDesignTool) { return { ...applyDesignTool, contextSchema: applyDesignTool?.contextSchema ?? flowContextSchema, execute: async (params, opts) => { const parts = opts?.context?.sessionParts; if (!parts) return applyDesignTool.execute(params, opts); const blocked = assertCandidateGateOpen(parts, params); if (blocked) return { status: "error", error: blocked }; return applyDesignTool.execute(params, opts); } }; } function updateCandidateGate(parts, requested, produced, unitId) { const needGate = produced > 1 || requested > 1 && produced > 0; if (needGate) { parts.pendingCandidateGate = { requested, produced, at: Date.now(), ...unitId ? { unitId } : {} }; } else { parts.pendingCandidateGate = void 0; } } function maybeCarryOverCandidateSelection(parts, requested, produced, unitId) { const cached2 = parts.toolContext?.lastResults?.get("generate-candidates"); const candidates = Array.isArray(cached2?.candidates) ? cached2.candidates : []; if (candidates.length === 0) return null; const fingerprint = candidateFingerprintOf(candidates); if (fingerprint.length === 0) return null; const list = parts.decisions; if (!list || list.length === 0) return null; const last = [...list].reverse().find((d2) => d2?.candidateIndex !== void 0); if (!last || last.candidateIndex === void 0) return null; if (last.candidateRequested !== requested || last.candidateProduced !== produced) return null; if ((last.unitId || "") !== (unitId || "")) return null; const closeGate = () => { parts.pendingCandidateGate = void 0; parts.pendingAskUserCandidateMap = void 0; }; if (Array.isArray(last.candidateFingerprint) && last.candidateFingerprint.length === fingerprint.length && last.candidateFingerprint.every((f2, i4) => f2 === fingerprint[i4])) { const aml = candidates[last.candidateIndex]?.aml; if (typeof aml === "string" && aml) { closeGate(); return [ "\u5019\u9009\u96C6\u4E0E\u51B3\u7B56\u53F0\u8D26\u4E2D\u6700\u8FD1\u4E00\u6B21\u5DF2\u88C1\u51B3\u5B8C\u5168\u4E00\u81F4", `\uFF08${last.choice}\uFF0C\u65B9\u6848 ${last.candidateIndex + 1}\uFF09`, "\uFF0C\u6BD4\u9009\u95F8\u95E8\u5DF2\u81EA\u52A8\u5173\u95ED\uFF1A\u76F4\u63A5\u5F15\u7528\u8BE5\u5019\u9009\u7684 aml_ref \u8C03\u7528 apply_design \u7F16\u8BD1\u5373\u53EF\uFF0C", "\u4E0D\u8981\u518D\u53D1\u8D77\u5019\u9009\u6BD4\u9009\u3001\u4E0D\u8981\u518D\u91CD\u590D\u8BE2\u95EE\u201C\u9009\u54EA\u4E2A\u201D\u3002" ].join(""); } return null; } const lastVariantKey = last.candidateVariantKey; if (lastVariantKey !== void 0) { const idx = candidates.findIndex((c2) => candidateVariantKeyOf(c2) === lastVariantKey); if (idx >= 0) { const aml = candidates[idx]?.aml; if (typeof aml === "string" && aml) { closeGate(); return [ "\u5019\u9009\u96C6\u6709\u66F4\u65B0\uFF0C\u4F46\u4F60\u4E0A\u6B21\u88C1\u51B3\u7684\u53D8\u4F53\u89C4\u683C\u4ECD\u5728", `\uFF08${last.choice}\uFF0C\u5BF9\u5E94\u672C\u6279\u65B9\u6848 ${idx + 1}\uFF09`, "\uFF0C\u6BD4\u9009\u95F8\u95E8\u5DF2\u81EA\u52A8\u6CBF\u7528\u5173\u95ED\uFF1A\u76F4\u63A5\u5F15\u7528\u8BE5\u5019\u9009\u7684 aml_ref \u8C03\u7528 apply_design \u7F16\u8BD1\u5373\u53EF\uFF0C", "\u4E0D\u8981\u518D\u53D1\u8D77\u5019\u9009\u6BD4\u9009\u3001\u4E0D\u8981\u518D\u91CD\u590D\u8BE2\u95EE\u201C\u9009\u54EA\u4E2A\u201D\u3002" ].join(""); } } } return null; } function wrapAskUserWithFlow(askUserTool) { return { ...askUserTool, contextSchema: askUserTool?.contextSchema ?? flowContextSchema, execute: async (params, opts) => { const parts = opts?.context?.sessionParts; if (!parts) return askUserTool.execute(params, opts); const r4 = await askUserTool.execute(params, opts); if (r4?._ask_user && Array.isArray(params?.questions)) { stashFlowGateQuestions(parts, params.questions); stashAskUserCandidateMap(parts, params.questions); } return r4; } }; } function wrapRunScriptWithFlow(runScriptTool) { return { ...runScriptTool, contextSchema: runScriptTool?.contextSchema ?? flowContextSchema, execute: async (params, opts) => { const parts = opts?.context?.sessionParts; if (!parts) return runScriptTool.execute(params, opts); const r4 = await runScriptTool.execute(params, opts); if (r4 && !r4.error && typeof params?.script === "string") recordScriptSuccess(parts, params.script); return r4; } }; } function residentialUnitProgramOf(req) { const program = req?.program; return program && typeof program === "object" && !Array.isArray(program) && program.kind === "residential-unit" ? program : void 0; } function applyLayoutPriorityToProgram(program, priority) { if (priority !== "south_first" && priority !== "privacy_corridor") return program; const counts = program.counts && typeof program.counts === "object" && !Array.isArray(program.counts) ? { ...program.counts } : {}; const bedroomN = Math.max(0, Math.floor(Number(counts.bedroom) || 0)); const livingN = Math.max(0, Math.floor(Number(counts.living) || 0)); if (bedroomN === 0 && livingN === 0) return program; const next = { ...program }; const mergeScoring = (defaults) => { const scoring = program.scoring && typeof program.scoring === "object" && !Array.isArray(program.scoring) ? { ...program.scoring } : {}; for (const [k, v2] of Object.entries(defaults)) { if (typeof scoring[k] !== "number") scoring[k] = v2; } return scoring; }; if (priority === "south_first") { const orientations = program.orientations && typeof program.orientations === "object" && !Array.isArray(program.orientations) ? { ...program.orientations } : {}; if (livingN > 0 && typeof orientations.living !== "string") orientations.living = "S"; for (let i4 = 1; i4 <= bedroomN; i4++) { const key = `bedroom${i4}`; if (typeof orientations[key] !== "string") orientations[key] = "S"; } if (Object.keys(orientations).length > 0) next.orientations = orientations; next.scoring = mergeScoring({ facade: 3 }); return next; } if (livingN > 0 && bedroomN > 0) { if (!(Number(counts.hallway) > 0)) counts.hallway = 1; next.counts = counts; const relations = Array.isArray(program.relations) ? [...program.relations] : []; for (let i4 = 1; i4 <= bedroomN; i4++) { const b5 = `bedroom${i4}`; const hasBetween = relations.some((rel) => rel && typeof rel === "object" && rel.kind === "between" && (rel.a === "living" && rel.b === b5 || rel.a === b5 && rel.b === "living") && rel.via === "hallway"); if (!hasBetween) relations.push({ kind: "between", a: "living", b: b5, via: "hallway" }); } next.relations = relations; } next.scoring = mergeScoring({ functional: 2, connectivity: 0.5 }); return next; } function wrapGenerateCandidatesWithFlow(generateCandidatesTool) { return { ...generateCandidatesTool, contextSchema: generateCandidatesTool?.contextSchema ?? flowContextSchema, execute: async (params, opts) => { const parts = opts?.context?.sessionParts; if (!parts) return generateCandidatesTool.execute(params, opts); const hasGenRequest = params && typeof params === "object" && params.request && typeof params.request === "object" && !!params.request.program; if (hasGenRequest) { const layoutPriority = getFlowRequirement(parts, "layout_priority"); if (typeof layoutPriority === "string") { const program = residentialUnitProgramOf(params.request); if (program) { const nextProgram = applyLayoutPriorityToProgram(program, layoutPriority); if (nextProgram !== program) { params = { ...params, request: { ...params.request, program: nextProgram } }; } } } const required2 = getFlowRequirement(parts, "candidates"); const candidates = typeof required2 === "number" ? Number.isInteger(required2) && required2 > 0 ? Math.floor(required2) : void 0 : typeof required2 === "string" && /^\d+$/.test(required2) ? Number(required2) : void 0; if (candidates !== void 0 && candidates > 0) { params = { ...params, request: { ...params.request, candidates } }; } } const r4 = await generateCandidatesTool.execute(params, opts); if (r4 && !r4.error && Array.isArray(r4.candidates) && r4.candidates.length > 0) { const unit = params && typeof params === "object" && typeof params.unit_id === "string" && params.unit_id ? `${params.unit_id}\uFF1A` : ""; recordToolSuccess(parts, "generate_candidates", `${unit}${r4.candidates.length} \u5019\u9009\u5DF2\u751F\u6210`, r4, params); const requested = typeof r4.requested_candidates === "number" ? Math.max(1, Math.floor(r4.requested_candidates)) : r4.candidates.length; const unitId = params && typeof params === "object" && typeof params.unit_id === "string" ? params.unit_id : void 0; updateCandidateGate(parts, requested, r4.candidates.length, unitId); const carryOver = maybeCarryOverCandidateSelection( parts, requested, r4.candidates.length, unitId ); if (carryOver) { return { ...r4, carry_over_applied: true, hint: `${typeof r4.hint === "string" && r4.hint ? r4.hint + " " : ""}${carryOver}` }; } } return r4; } }; } // node_modules/js-yaml/dist/js-yaml.mjs var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED"); var MERGE_KEY = /* @__PURE__ */ Symbol("MERGE_KEY"); function defineScalarTag(tagName, options) { return { tagName, nodeKind: "scalar", implicit: options.implicit ?? false, matchByTagPrefix: options.matchByTagPrefix ?? false, implicitFirstChars: options.implicitFirstChars ?? null, resolve: options.resolve, identify: options.identify ?? null, represent: options.represent ?? ((data) => String(data)), representTagName: options.representTagName ?? null }; } function defineSequenceTag(tagName, options) { const carrierIsResult = options.finalize === void 0; return { tagName, nodeKind: "sequence", implicit: false, matchByTagPrefix: options.matchByTagPrefix ?? false, create: options.create, addItem: options.addItem, finalize: options.finalize ?? ((carrier) => carrier), carrierIsResult, identify: options.identify ?? null, represent: options.represent ?? ((data) => data), representTagName: options.representTagName ?? null }; } function defineMappingTag(tagName, options) { const carrierIsResult = options.finalize === void 0; return { tagName, nodeKind: "mapping", implicit: false, matchByTagPrefix: options.matchByTagPrefix ?? false, create: options.create, addPair: options.addPair, has: options.has, keys: options.keys, get: options.get, finalize: options.finalize ?? ((carrier) => carrier), carrierIsResult, identify: options.identify ?? null, represent: options.represent ?? ((data) => data), representTagName: options.representTagName ?? null }; } var strTag = defineScalarTag("tag:yaml.org,2002:str", { resolve: (source) => source, identify: (data) => typeof data === "string" }); var NULL_VALUES$1 = [ "", "~", "null", "Null", "NULL" ]; var nullCoreTag = defineScalarTag("tag:yaml.org,2002:null", { implicit: true, implicitFirstChars: [ "", "~", "n", "N" ], resolve: (source) => { if (NULL_VALUES$1.indexOf(source) !== -1) return null; return NOT_RESOLVED; }, identify: (object4) => object4 === null, represent: () => "null" }); var nullJsonTag = defineScalarTag("tag:yaml.org,2002:null", { implicit: true, implicitFirstChars: ["n"], resolve: (source, isExplicit) => { if (source === "null" || isExplicit && source === "") return null; return NOT_RESOLVED; }, identify: (object4) => object4 === null, represent: () => "null" }); var NULL_VALUES = [ "", "~", "null", "Null", "NULL" ]; var nullYaml11Tag = defineScalarTag("tag:yaml.org,2002:null", { implicit: true, implicitFirstChars: [ "", "~", "n", "N" ], resolve: (source) => { if (NULL_VALUES.indexOf(source) !== -1) return null; return NOT_RESOLVED; }, identify: (object4) => object4 === null, represent: () => "null" }); var TRUE_VALUES$2 = [ "true", "True", "TRUE" ]; var FALSE_VALUES$2 = [ "false", "False", "FALSE" ]; var boolCoreTag = defineScalarTag("tag:yaml.org,2002:bool", { implicit: true, implicitFirstChars: [ "t", "T", "f", "F" ], resolve: (source) => { if (TRUE_VALUES$2.indexOf(source) !== -1) return true; if (FALSE_VALUES$2.indexOf(source) !== -1) return false; return NOT_RESOLVED; }, identify: (object4) => Object.prototype.toString.call(object4) === "[object Boolean]", represent: (object4) => object4 ? "true" : "false" }); var TRUE_VALUES$1 = ["true"]; var FALSE_VALUES$1 = ["false"]; var boolJsonTag = defineScalarTag("tag:yaml.org,2002:bool", { implicit: true, implicitFirstChars: ["t", "f"], resolve: (source) => { if (TRUE_VALUES$1.indexOf(source) !== -1) return true; if (FALSE_VALUES$1.indexOf(source) !== -1) return false; return NOT_RESOLVED; }, identify: (object4) => Object.prototype.toString.call(object4) === "[object Boolean]", represent: (object4) => object4 ? "true" : "false" }); var TRUE_VALUES = [ "true", "True", "TRUE", "y", "Y", "yes", "Yes", "YES", "on", "On", "ON" ]; var FALSE_VALUES = [ "false", "False", "FALSE", "n", "N", "no", "No", "NO", "off", "Off", "OFF" ]; var boolYaml11Tag = defineScalarTag("tag:yaml.org,2002:bool", { implicit: true, implicitFirstChars: [ "y", "Y", "n", "N", "t", "T", "f", "F", "o", "O" ], resolve: (source) => { if (TRUE_VALUES.indexOf(source) !== -1) return true; if (FALSE_VALUES.indexOf(source) !== -1) return false; return NOT_RESOLVED; }, identify: (object4) => Object.prototype.toString.call(object4) === "[object Boolean]", represent: (object4) => object4 ? "true" : "false" }); var YAML_INTEGER_IMPLICIT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:0o[0-7]+|0x[0-9a-fA-F]+|[-+]?[0-9]+)$"); var YAML_INTEGER_EXPLICIT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$"); function parseYamlInteger$2(source) { let value = source; let sign = 1; if (value[0] === "-" || value[0] === "+") { if (value[0] === "-") sign = -1; value = value.slice(1); } if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2); if (value.startsWith("0o")) return sign * parseInt(value.slice(2), 8); if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16); return sign * parseInt(value, 10); } function resolveYamlInteger$2(source, isExplicit) { if (isExplicit) { if (!YAML_INTEGER_EXPLICIT_PATTERN$1.test(source)) return NOT_RESOLVED; } else if (!YAML_INTEGER_IMPLICIT_PATTERN$1.test(source)) return NOT_RESOLVED; const result = parseYamlInteger$2(source); return Number.isFinite(result) ? result : NOT_RESOLVED; } var intCoreTag = defineScalarTag("tag:yaml.org,2002:int", { implicit: true, implicitFirstChars: [ "-", "+", ..."0123456789" ], resolve: resolveYamlInteger$2, identify: (object4) => Number.isInteger(object4) && !Object.is(object4, -0) && object4.toString(10).indexOf("e") < 0, represent: (object4) => object4.toString(10) }); var YAML_INTEGER_IMPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^-?(?:0|[1-9][0-9]*)$"); var YAML_INTEGER_EXPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$"); function parseYamlInteger$1(source) { let value = source; let sign = 1; if (value[0] === "-" || value[0] === "+") { if (value[0] === "-") sign = -1; value = value.slice(1); } if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2); if (value.startsWith("0o")) return sign * parseInt(value.slice(2), 8); if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16); return sign * parseInt(value, 10); } function resolveYamlInteger$1(source, isExplicit) { if (isExplicit) { if (!YAML_INTEGER_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED; } else if (!YAML_INTEGER_IMPLICIT_PATTERN.test(source)) return NOT_RESOLVED; const result = parseYamlInteger$1(source); return Number.isFinite(result) ? result : NOT_RESOLVED; } var intJsonTag = defineScalarTag("tag:yaml.org,2002:int", { implicit: true, implicitFirstChars: ["-", ..."0123456789"], resolve: resolveYamlInteger$1, identify: (object4) => Number.isInteger(object4) && !Object.is(object4, -0) && object4.toString(10).indexOf("e") < 0, represent: (object4) => object4.toString(10) }); var YAML_INTEGER_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?0x[0-9a-fA-F_]+|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+|[-+]?(?:0|[1-9][0-9_]*))$"); function parseYamlInteger(source) { let value = source.replace(/_/g, ""); let sign = 1; if (value[0] === "-" || value[0] === "+") { if (value[0] === "-") sign = -1; value = value.slice(1); } if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2); if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16); if (value.includes(":")) { let result = 0; for (const part of value.split(":")) result = result * 60 + Number(part); return sign * result; } if (value !== "0" && value[0] === "0") return sign * parseInt(value, 8); return sign * parseInt(value, 10); } function resolveYamlInteger(source) { if (!YAML_INTEGER_PATTERN.test(source)) return NOT_RESOLVED; const result = parseYamlInteger(source); return Number.isFinite(result) ? result : NOT_RESOLVED; } var intYaml11Tag = defineScalarTag("tag:yaml.org,2002:int", { implicit: true, implicitFirstChars: [ "-", "+", ..."0123456789" ], resolve: resolveYamlInteger, identify: (object4) => Number.isInteger(object4) && !Object.is(object4, -0) && object4.toString(10).indexOf("e") < 0, represent: (object4) => object4.toString(10) }); var YAML_FLOAT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); var YAML_FLOAT_SPECIAL_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); function resolveYamlFloat$2(source) { if (!YAML_FLOAT_PATTERN$1.test(source)) return NOT_RESOLVED; let value = source.toLowerCase(); const sign = value[0] === "-" ? -1 : 1; if ("+-".includes(value[0])) value = value.slice(1); if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; if (value === ".nan") return NaN; const result = sign * parseFloat(value); if (Number.isFinite(result) || YAML_FLOAT_SPECIAL_PATTERN$1.test(source)) return result; return NOT_RESOLVED; } function representYamlFloat$2(object4) { if (isNaN(object4)) return ".nan"; if (object4 === Number.POSITIVE_INFINITY) return ".inf"; if (object4 === Number.NEGATIVE_INFINITY) return "-.inf"; if (Object.is(object4, -0)) return "-0.0"; const result = object4.toString(10); return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result; } var floatCoreTag = defineScalarTag("tag:yaml.org,2002:float", { implicit: true, implicitFirstChars: [ "-", "+", ".", ..."0123456789" ], resolve: resolveYamlFloat$2, identify: (object4) => typeof object4 === "number" && (!Number.isInteger(object4) || Object.is(object4, -0) || object4.toString(10).indexOf("e") >= 0), represent: representYamlFloat$2 }); var YAML_FLOAT_IMPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$"); var YAML_FLOAT_EXPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); function resolveYamlFloat$1(source, isExplicit) { if (isExplicit) { if (!YAML_FLOAT_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED; let value = source.toLowerCase(); const sign = value[0] === "-" ? -1 : 1; if ("+-".includes(value[0])) value = value.slice(1); if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; if (value === ".nan") return NaN; const result2 = sign * parseFloat(value); return Number.isFinite(result2) ? result2 : NOT_RESOLVED; } if (!YAML_FLOAT_IMPLICIT_PATTERN.test(source)) return NOT_RESOLVED; const result = Number(source); if (Number.isFinite(result)) return result; return NOT_RESOLVED; } function representYamlFloat$1(object4) { if (isNaN(object4)) return ".nan"; if (object4 === Number.POSITIVE_INFINITY) return ".inf"; if (object4 === Number.NEGATIVE_INFINITY) return "-.inf"; if (Object.is(object4, -0)) return "-0.0"; const result = object4.toString(10); return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result; } var floatJsonTag = defineScalarTag("tag:yaml.org,2002:float", { implicit: true, implicitFirstChars: ["-", ..."0123456789"], resolve: resolveYamlFloat$1, identify: (object4) => typeof object4 === "number" && (!Number.isInteger(object4) || Object.is(object4, -0) || object4.toString(10).indexOf("e") >= 0), represent: representYamlFloat$1 }); var YAML_FLOAT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?(?:(?:[0-9][0-9_]*)?\\.[0-9_]*)(?:[eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); var YAML_FLOAT_SPECIAL_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); function resolveYamlFloat(source) { if (!YAML_FLOAT_PATTERN.test(source)) return NOT_RESOLVED; let value = source.toLowerCase().replace(/_/g, ""); const sign = value[0] === "-" ? -1 : 1; if ("+-".includes(value[0])) value = value.slice(1); if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; if (value === ".nan") return NaN; let result = 0; if (value.includes(":")) { for (const part of value.split(":")) result = result * 60 + Number(part); result *= sign; } else result = sign * parseFloat(value); if (Number.isFinite(result) || YAML_FLOAT_SPECIAL_PATTERN.test(source)) return result; return NOT_RESOLVED; } function representYamlFloat(object4) { if (isNaN(object4)) return ".nan"; if (object4 === Number.POSITIVE_INFINITY) return ".inf"; if (object4 === Number.NEGATIVE_INFINITY) return "-.inf"; if (Object.is(object4, -0)) return "-0.0"; const result = object4.toString(10); return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result; } var floatYaml11Tag = defineScalarTag("tag:yaml.org,2002:float", { implicit: true, implicitFirstChars: [ "-", "+", ".", ..."0123456789" ], resolve: resolveYamlFloat, identify: (object4) => typeof object4 === "number" && (!Number.isInteger(object4) || Object.is(object4, -0) || object4.toString(10).indexOf("e") >= 0), represent: representYamlFloat }); var mergeTag = defineScalarTag("tag:yaml.org,2002:merge", { implicit: true, implicitFirstChars: ["<"], resolve: (source, isExplicit) => { if (source === "<<" || isExplicit && source === "") return MERGE_KEY; return NOT_RESOLVED; } }); var BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/; function resolveYamlBinary(source) { const input = source.replace(/\s/g, ""); if (input.length % 4 !== 0 || !BASE64_PATTERN.test(input)) return NOT_RESOLVED; const binary = atob(input); const result = new Uint8Array(binary.length); for (let index = 0; index < binary.length; index++) result[index] = binary.charCodeAt(index); return result; } function representYamlBinary(object4) { let binary = ""; for (let index = 0; index < object4.length; index++) binary += String.fromCharCode(object4[index]); return btoa(binary); } var binaryTag = defineScalarTag("tag:yaml.org,2002:binary", { resolve: resolveYamlBinary, identify: (object4) => Object.prototype.toString.call(object4) === "[object Uint8Array]", represent: representYamlBinary }); var YAML_DATE_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"); var YAML_TIMESTAMP_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"); function makeUtcDate(year, month, day, hour = 0, minute = 0, second = 0, fraction = 0) { const date5 = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); date5.setUTCFullYear(year, month, day); return date5; } function resolveYamlTimestamp(source) { let match = YAML_DATE_REGEXP.exec(source); if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(source); if (match === null) return NOT_RESOLVED; const year = +match[1]; const month = +match[2] - 1; const day = +match[3]; if (!match[4]) { const date6 = makeUtcDate(year, month, day); if (date6.getUTCFullYear() !== year || date6.getUTCMonth() !== month || date6.getUTCDate() !== day) return NOT_RESOLVED; return date6; } const hour = +match[4]; const minute = +match[5]; const second = +match[6]; let fraction = 0; if (hour > 23 || minute > 59 || second > 59) return NOT_RESOLVED; if (match[7]) { let value = match[7].slice(0, 3); while (value.length < 3) value += "0"; fraction = +value; } const date5 = makeUtcDate(year, month, day, hour, minute, second, fraction); if (date5.getUTCFullYear() !== year || date5.getUTCMonth() !== month || date5.getUTCDate() !== day) return NOT_RESOLVED; if (match[9]) { const offsetHour = +match[10]; const offsetMinute = +(match[11] || 0); if (offsetHour > 23 || offsetMinute > 59) return NOT_RESOLVED; const offset = (offsetHour * 60 + offsetMinute) * 6e4; date5.setTime(date5.getTime() - (match[9] === "-" ? -offset : offset)); } return date5; } var timestampTag = defineScalarTag("tag:yaml.org,2002:timestamp", { implicit: true, implicitFirstChars: [..."0123456789"], resolve: resolveYamlTimestamp, identify: (object4) => object4 instanceof Date, represent: (object4) => object4.toISOString() }); var seqTag = defineSequenceTag("tag:yaml.org,2002:seq", { create: () => [], addItem: (container, item) => { container.push(item); }, identify: Array.isArray }); function isPlainObject3(data) { if (data === null || typeof data !== "object" || Array.isArray(data)) return false; const prototype = Object.getPrototypeOf(data); return prototype === null || prototype === Object.prototype; } function pick3(object4, keys) { const result = {}; for (const key of keys) if (object4[key] !== void 0) result[key] = object4[key]; return result; } var omapTag = defineSequenceTag("tag:yaml.org,2002:omap", { create: () => ({ list: [], seen: /* @__PURE__ */ new Set() }), addItem: (carrier, item) => { let key; if (item instanceof Map) { if (item.size !== 1) return "cannot resolve an ordered map item"; key = item.keys().next().value; } else if (isPlainObject3(item)) { const itemKeys = Object.keys(item); if (itemKeys.length !== 1) return "cannot resolve an ordered map item"; key = itemKeys[0]; } else return "cannot resolve an ordered map item"; if (carrier.seen.has(key)) return "duplicate key in ordered map"; carrier.seen.add(key); carrier.list.push(item); return ""; }, finalize: (carrier) => carrier.list }); var pairsTag = defineSequenceTag("tag:yaml.org,2002:pairs", { create: () => [], addItem: (container, item) => { if (item instanceof Map) { if (item.size !== 1) return "cannot resolve a pairs item"; container.push(item.entries().next().value); return ""; } if (Object.prototype.toString.call(item) !== "[object Object]") return "cannot resolve a pairs item"; const object4 = item; const keys = Object.keys(object4); if (keys.length !== 1) return "cannot resolve a pairs item"; container.push([keys[0], object4[keys[0]]]); return ""; } }); var mapTag = defineMappingTag("tag:yaml.org,2002:map", { create: () => ({}), identify: isPlainObject3, represent: (o3) => { const map2 = /* @__PURE__ */ new Map(); for (const key of Object.keys(o3)) map2.set(key, o3[key]); return map2; }, addPair: (container, key, value) => { if (key !== null && typeof key === "object") return "object-based map does not support complex keys"; const normalizedKey = String(key); if (normalizedKey === "__proto__") Object.defineProperty(container, normalizedKey, { value, enumerable: true, configurable: true, writable: true }); else container[normalizedKey] = value; return ""; }, has: (container, key) => { if (key !== null && typeof key === "object") return false; return Object.prototype.hasOwnProperty.call(container, String(key)); }, keys: (container) => Object.keys(container), get: (container, key) => { const normalizedKey = String(key); if (!Object.prototype.hasOwnProperty.call(container, normalizedKey)) return null; return container[normalizedKey]; } }); var setTag = defineMappingTag("tag:yaml.org,2002:set", { create: () => /* @__PURE__ */ new Set(), identify: (data) => data instanceof Set, represent: (data) => { const map2 = /* @__PURE__ */ new Map(); for (const key of data) map2.set(key, null); return map2; }, addPair: (container, key, value) => { if (value !== null) return "cannot resolve a set item"; container.add(key); return ""; }, has: (container, key) => container.has(key), keys: (container) => container.keys(), get: () => null }); function createTagDefinitionMap() { return { scalar: /* @__PURE__ */ Object.create(null), sequence: /* @__PURE__ */ Object.create(null), mapping: /* @__PURE__ */ Object.create(null) }; } function createTagDefinitionListMap() { return { scalar: [], sequence: [], mapping: [] }; } function compileTags(tags) { const result = []; for (const tag of tags) { let index = result.length; for (let previousIndex = 0; previousIndex < result.length; previousIndex++) { const previous = result[previousIndex]; if (previous.nodeKind === tag.nodeKind && previous.tagName === tag.tagName && previous.matchByTagPrefix === tag.matchByTagPrefix) { index = previousIndex; break; } } result[index] = tag; } return result; } var Schema = class Schema2 { tags; implicitScalarTags; implicitScalarByFirstChar; implicitScalarAnyFirstChar; defaultScalarTag; defaultSequenceTag; defaultMappingTag; exact; prefix; constructor(tags) { const compiledTags = compileTags(tags); const implicitScalarTags = []; const exact = createTagDefinitionMap(); const prefix = createTagDefinitionListMap(); for (const tag of compiledTags) { if (tag.nodeKind === "scalar" && tag.implicit) { if (tag.matchByTagPrefix) throw new Error("Implicit scalar tags cannot match by tag prefix"); implicitScalarTags.push(tag); } switch (tag.nodeKind) { case "scalar": if (tag.matchByTagPrefix) prefix.scalar.push(tag); else exact.scalar[tag.tagName] = tag; break; case "sequence": if (tag.matchByTagPrefix) prefix.sequence.push(tag); else exact.sequence[tag.tagName] = tag; break; case "mapping": if (tag.matchByTagPrefix) prefix.mapping.push(tag); else exact.mapping[tag.tagName] = tag; break; } } const implicitScalarAnyFirstChar = implicitScalarTags.filter((tag) => tag.implicitFirstChars === null); const keys = /* @__PURE__ */ new Set(); for (const tag of implicitScalarTags) if (tag.implicitFirstChars !== null) for (const key of tag.implicitFirstChars) keys.add(key); const implicitScalarByFirstChar = /* @__PURE__ */ new Map(); for (const key of keys) implicitScalarByFirstChar.set(key, implicitScalarTags.filter((tag) => tag.implicitFirstChars === null || tag.implicitFirstChars.indexOf(key) !== -1)); const defaultScalarTag = exact.scalar["tag:yaml.org,2002:str"]; if (!defaultScalarTag) throw new Error("schema does not define the default scalar tag (tag:yaml.org,2002:str)"); this.tags = compiledTags; this.implicitScalarTags = implicitScalarTags; this.implicitScalarByFirstChar = implicitScalarByFirstChar; this.implicitScalarAnyFirstChar = implicitScalarAnyFirstChar; this.defaultScalarTag = defaultScalarTag; this.defaultSequenceTag = exact.sequence["tag:yaml.org,2002:seq"]; this.defaultMappingTag = exact.mapping["tag:yaml.org,2002:map"]; this.exact = exact; this.prefix = prefix; } withTags(...tags) { let flatTags = []; for (const tag of tags) flatTags = flatTags.concat(tag); return new Schema2([...this.tags, ...flatTags]); } }; var FAILSAFE_SCHEMA = new Schema([ strTag, seqTag, mapTag ]); var JSON_SCHEMA = new Schema([ ...FAILSAFE_SCHEMA.tags, nullJsonTag, boolJsonTag, intJsonTag, floatJsonTag ]); var CORE_SCHEMA = new Schema([ ...FAILSAFE_SCHEMA.tags, nullCoreTag, boolCoreTag, intCoreTag, floatCoreTag ]); var YAML11_SCHEMA = new Schema([ ...FAILSAFE_SCHEMA.tags, nullYaml11Tag, boolYaml11Tag, intYaml11Tag, floatYaml11Tag, timestampTag, mergeTag, binaryTag, omapTag, pairsTag, setTag ]); var realMapTag = defineMappingTag("tag:yaml.org,2002:map", { create: () => /* @__PURE__ */ new Map(), addPair: (container, key, value) => { container.set(key, value); return ""; }, has: (container, key) => container.has(key), keys: (container) => container.keys(), get: (container, key) => container.get(key), identify: (data) => data instanceof Map || isPlainObject3(data), represent: (data) => { if (data instanceof Map) return data; const map2 = /* @__PURE__ */ new Map(); const obj = data; for (const key of Object.keys(obj)) map2.set(key, obj[key]); return map2; } }); function normalizeKey(key) { if (Array.isArray(key)) { const array3 = Array.prototype.slice.call(key); for (let index = 0; index < array3.length; index++) { if (Array.isArray(array3[index])) return null; if (typeof array3[index] === "object" && Object.prototype.toString.call(array3[index]) === "[object Object]") array3[index] = "[object Object]"; } return String(array3); } if (typeof key === "object" && Object.prototype.toString.call(key) === "[object Object]") return "[object Object]"; return String(key); } var legacyMapTag = defineMappingTag("tag:yaml.org,2002:map", { create: () => ({}), identify: isPlainObject3, represent: (o3) => { const map2 = /* @__PURE__ */ new Map(); for (const key of Object.keys(o3)) map2.set(key, o3[key]); return map2; }, addPair: (container, key, value) => { const normalizedKey = normalizeKey(key); if (normalizedKey === null) return "nested arrays are not supported inside keys"; if (normalizedKey === "__proto__") Object.defineProperty(container, normalizedKey, { value, enumerable: true, configurable: true, writable: true }); else container[normalizedKey] = value; return ""; }, has: (container, key) => { const normalizedKey = normalizeKey(key); return normalizedKey !== null && Object.prototype.hasOwnProperty.call(container, normalizedKey); }, keys: (container) => Object.keys(container), get: (container, key) => { const normalizedKey = String(key); if (!Object.prototype.hasOwnProperty.call(container, normalizedKey)) return null; return container[normalizedKey]; } }); var DEFAULT_SNIPPET_OPTIONS = { maxLength: 79, indent: 1, linesBefore: 3, linesAfter: 2 }; function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { let head = ""; let tail = ""; const maxHalfLength = Math.floor(maxLineLength / 2) - 1; if (position - lineStart > maxHalfLength) { head = " ... "; lineStart = position - maxHalfLength + head.length; } if (lineEnd - position > maxHalfLength) { tail = " ..."; lineEnd = position + maxHalfLength - tail.length; } return { str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail, pos: position - lineStart + head.length }; } function padStart(string4, max2) { return " ".repeat(Math.max(max2 - string4.length, 0)) + string4; } function makeSnippet(mark, options) { if (!mark.buffer) return null; const opts = { ...DEFAULT_SNIPPET_OPTIONS, ...options }; const re2 = /\r?\n|\r|\0/g; const lineStarts = [0]; const lineEnds = []; let match; let foundLineNo = -1; while (match = re2.exec(mark.buffer)) { lineEnds.push(match.index); lineStarts.push(match.index + match[0].length); if (mark.position <= match.index && foundLineNo < 0) foundLineNo = lineStarts.length - 2; } if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; let result = ""; const lineNoLength = Math.min(mark.line + opts.linesAfter, lineEnds.length).toString().length; const maxLineLength = opts.maxLength - (opts.indent + lineNoLength + 3); for (let i4 = 1; i4 <= opts.linesBefore; i4++) { if (foundLineNo - i4 < 0) break; const line3 = getLine(mark.buffer, lineStarts[foundLineNo - i4], lineEnds[foundLineNo - i4], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i4]), maxLineLength); result = `${" ".repeat(opts.indent)}${padStart((mark.line - i4 + 1).toString(), lineNoLength)} | ${line3.str} ${result}`; } const line2 = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); result += `${" ".repeat(opts.indent)}${padStart((mark.line + 1).toString(), lineNoLength)} | ${line2.str} `; result += `${"-".repeat(opts.indent + lineNoLength + 3 + line2.pos)}^ `; for (let i4 = 1; i4 <= opts.linesAfter; i4++) { if (foundLineNo + i4 >= lineEnds.length) break; const line3 = getLine(mark.buffer, lineStarts[foundLineNo + i4], lineEnds[foundLineNo + i4], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i4]), maxLineLength); result += `${" ".repeat(opts.indent)}${padStart((mark.line + i4 + 1).toString(), lineNoLength)} | ${line3.str} `; } return result.replace(/\n$/, ""); } function formatError2(exception, compact) { let where = ""; if (!exception.mark) return exception.reason; if (exception.mark.name) where += `in "${exception.mark.name}" `; where += `(${exception.mark.line + 1}:${exception.mark.column + 1})`; if (!compact && exception.mark.snippet) where += ` ${exception.mark.snippet}`; return `${exception.reason} ${where}`; } var YAMLException = class extends Error { reason; mark; constructor(reason, mark) { super(); this.name = "YAMLException"; this.reason = reason; this.mark = mark; this.message = formatError2(this, false); if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor); } toString(compact) { return `${this.name}: ${formatError2(this, compact)}`; } }; function throwErrorAt(source, position, message, filename = "") { let line2 = 0; let lineStart = 0; for (let index = 0; index < position; index++) { const ch2 = source.charCodeAt(index); if (ch2 === 10) { line2++; lineStart = index + 1; } else if (ch2 === 13) { line2++; if (source.charCodeAt(index + 1) === 10) index++; lineStart = index + 1; } } const mark = { name: filename, buffer: source, position, line: line2, column: position - lineStart }; mark.snippet = makeSnippet(mark); throw new YAMLException(message, mark); } var NO_RANGE$3 = -1; function simpleEscapeSequence(c2) { switch (c2) { case 48: return "\0"; case 97: return "\x07"; case 98: return "\b"; case 116: return " "; case 9: return " "; case 110: return "\n"; case 118: return "\v"; case 102: return "\f"; case 114: return "\r"; case 101: return "\x1B"; case 32: return " "; case 34: return '"'; case 47: return "/"; case 92: return "\\"; case 78: return "\x85"; case 95: return "\xA0"; case 76: return "\u2028"; case 80: return "\u2029"; default: return ""; } } var simpleEscapeCheck = new Array(256); var simpleEscapeMap = new Array(256); for (let i4 = 0; i4 < 256; i4++) { simpleEscapeCheck[i4] = simpleEscapeSequence(i4) ? 1 : 0; simpleEscapeMap[i4] = simpleEscapeSequence(i4); } function charFromCodepoint(c2) { if (c2 <= 65535) return String.fromCharCode(c2); return String.fromCharCode((c2 - 65536 >> 10) + 55296, (c2 - 65536 & 1023) + 56320); } function fromHexCode$1(c2) { if (c2 >= 48 && c2 <= 57) return c2 - 48; return (c2 | 32) - 97 + 10; } function escapedHexLen$1(c2) { if (c2 === 120) return 2; if (c2 === 117) return 4; return 8; } function skipFoldedBreaks(input, position, end) { let breaks = 0; while (position < end) { const ch2 = input.charCodeAt(position); if (ch2 === 10) { breaks++; position++; } else if (ch2 === 13) { breaks++; position++; if (input.charCodeAt(position) === 10) position++; } else if (ch2 === 32 || ch2 === 9) position++; else break; } return { position, breaks }; } function foldedBreaks(count) { if (count === 1) return " "; return "\n".repeat(count - 1); } function getPlainValue(input, start, end) { let result = ""; let position = start; let captureStart = start; let captureEnd = start; while (position < end) { const ch2 = input.charCodeAt(position); if (ch2 === 10 || ch2 === 13) { result += input.slice(captureStart, captureEnd); const fold = skipFoldedBreaks(input, position, end); result += foldedBreaks(fold.breaks); position = captureStart = captureEnd = fold.position; } else { position++; if (ch2 !== 32 && ch2 !== 9) captureEnd = position; } } return result + input.slice(captureStart, captureEnd); } function getSingleQuotedValue(input, start, end) { let result = ""; let position = start; let captureStart = start; let captureEnd = start; while (position < end) { const ch2 = input.charCodeAt(position); if (ch2 === 39) { result += input.slice(captureStart, position) + "'"; position += 2; captureStart = captureEnd = position; } else if (ch2 === 10 || ch2 === 13) { result += input.slice(captureStart, captureEnd); const fold = skipFoldedBreaks(input, position, end); result += foldedBreaks(fold.breaks); position = captureStart = captureEnd = fold.position; } else { position++; if (ch2 !== 32 && ch2 !== 9) captureEnd = position; } } return result + input.slice(captureStart, end); } function getDoubleQuotedValue(input, start, end) { let result = ""; let position = start; let captureStart = start; let captureEnd = start; while (position < end) { const ch2 = input.charCodeAt(position); if (ch2 === 92) { result += input.slice(captureStart, position); position++; const escaped = input.charCodeAt(position); if (escaped === 10 || escaped === 13) position = skipFoldedBreaks(input, position, end).position; else if (escaped < 256 && simpleEscapeCheck[escaped]) { result += simpleEscapeMap[escaped]; position++; } else { let hexLength = escapedHexLen$1(escaped); let hexResult = 0; for (; hexLength > 0; hexLength--) { position++; const digit = fromHexCode$1(input.charCodeAt(position)); hexResult = (hexResult << 4) + digit; } result += charFromCodepoint(hexResult); position++; } captureStart = captureEnd = position; } else if (ch2 === 10 || ch2 === 13) { result += input.slice(captureStart, captureEnd); const fold = skipFoldedBreaks(input, position, end); result += foldedBreaks(fold.breaks); position = captureStart = captureEnd = fold.position; } else { position++; if (ch2 !== 32 && ch2 !== 9) captureEnd = position; } } return result + input.slice(captureStart, end); } function getBlockValue(input, start, end, indent, chomping, folded) { const textIndent = indent < 0 ? 0 : indent; const region = input.slice(start, end).replace(/\r\n?/g, "\n"); const lines = region === "" ? [] : (region.endsWith("\n") ? region.slice(0, -1) : region).split("\n"); let result = ""; let didReadContent = false; let emptyLines = 0; let atMoreIndented = false; for (const line2 of lines) { let column = 0; while (column < textIndent && line2.charCodeAt(column) === 32) column++; if (indent < 0 || column >= line2.length) { emptyLines++; continue; } const content = line2.slice(textIndent); const first = content.charCodeAt(0); if (folded) if (first === 32 || first === 9) { atMoreIndented = true; result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines); } else if (atMoreIndented) { atMoreIndented = false; result += "\n".repeat(emptyLines + 1); } else if (emptyLines === 0) { if (didReadContent) result += " "; } else result += "\n".repeat(emptyLines); else result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines); result += content; didReadContent = true; emptyLines = 0; } if (chomping === 3) result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines); else if (chomping !== 2) { if (didReadContent) result += "\n"; } return result; } function getScalarValue(input, scalar) { if (scalar.valueStart === NO_RANGE$3) return ""; const { valueStart, valueEnd } = scalar; if (scalar.fast) return input.slice(valueStart, valueEnd); switch (scalar.style) { case 2: return getSingleQuotedValue(input, valueStart, valueEnd); case 3: return getDoubleQuotedValue(input, valueStart, valueEnd); case 4: return getBlockValue(input, valueStart, valueEnd, scalar.indent, scalar.chomping, false); case 5: return getBlockValue(input, valueStart, valueEnd, scalar.indent, scalar.chomping, true); default: return getPlainValue(input, valueStart, valueEnd); } } var DEFAULT_TAG_HANDLERS = Object.assign(/* @__PURE__ */ Object.create(null), { "!": "!", "!!": "tag:yaml.org,2002:" }); function tagNameFull(rawTag, tagHandlers) { if (rawTag.startsWith("!<") && rawTag.endsWith(">")) return decodeURIComponent(rawTag.slice(2, -1)); const handleEnd = rawTag.indexOf("!", 1); const handle = handleEnd === -1 ? "!" : rawTag.slice(0, handleEnd + 1); const prefix = tagHandlers?.[handle] ?? DEFAULT_TAG_HANDLERS[handle] ?? handle; return decodeURIComponent(prefix) + decodeURIComponent(rawTag.slice(handle.length)); } var NO_RANGE$2 = -1; var DEFAULT_CONSTRUCTOR_OPTIONS = { filename: "", schema: CORE_SCHEMA, json: false, maxTotalMergeKeys: 1e4, maxAliases: -1 }; function eventPosition$1(event) { if ("tagStart" in event && event.tagStart !== NO_RANGE$2) return event.tagStart; if ("anchorStart" in event && event.anchorStart !== NO_RANGE$2) return event.anchorStart; if ("valueStart" in event && event.valueStart !== NO_RANGE$2) return event.valueStart; if ("start" in event) return event.start; return 0; } function throwError$1(state, message) { throwErrorAt(state.source, state.position, message, state.filename); } function finalizeCollection(state, position, tag, carrier) { try { return tag.finalize(carrier); } catch (error40) { if (error40 instanceof YAMLException) throw error40; throwErrorAt(state.source, position, error40 instanceof Error ? error40.message : String(error40), state.filename); } } function lookupTag(exact, prefix, tagName) { const exactTag = exact[tagName]; if (exactTag) return exactTag; for (const tag of prefix) if (tagName.startsWith(tag.tagName)) return tag; } function findExplicitTag(state, exact, prefix, tagName, nodeKind) { const tag = lookupTag(exact, prefix, tagName); if (tag) return tag; throwError$1(state, `unknown ${nodeKind} tag !<${tagName}>`); } function constructScalar(state, event) { const source = getScalarValue(state.source, event); const rawTag = event.tagStart === NO_RANGE$2 ? "" : state.source.slice(event.tagStart, event.tagEnd); const strTag2 = state.schema.defaultScalarTag; if (rawTag !== "") { if (rawTag === "!") return { value: source, tag: strTag2 }; const tagName = tagNameFull(rawTag, state.tagHandlers); const scalarTag = lookupTag(state.schema.exact.scalar, state.schema.prefix.scalar, tagName); if (scalarTag) { const result = scalarTag.resolve(source, true, tagName); if (result === NOT_RESOLVED) throwError$1(state, `cannot resolve a node with !<${tagName}> explicit tag`); return { value: result, tag: scalarTag }; } const collectionTagDef = lookupTag(state.schema.exact.mapping, state.schema.prefix.mapping, tagName) ?? lookupTag(state.schema.exact.sequence, state.schema.prefix.sequence, tagName); if (collectionTagDef) { if (source !== "") throwError$1(state, `cannot resolve a node with !<${tagName}> explicit tag`); const carrier = collectionTagDef.create(tagName); return { value: collectionTagDef.carrierIsResult ? carrier : finalizeCollection(state, state.position, collectionTagDef, carrier), tag: collectionTagDef }; } throwError$1(state, `unknown scalar tag !<${tagName}>`); } if (event.style === 1) { const candidates = state.schema.implicitScalarByFirstChar.get(source.charAt(0)) ?? state.schema.implicitScalarAnyFirstChar; for (const tag of candidates) { const result = tag.resolve(source, false, tag.tagName); if (result !== NOT_RESOLVED) return { value: result, tag }; } } return { value: strTag2.resolve(source, false, strTag2.tagName), tag: strTag2 }; } function collectionTag(state, event, exact, prefix, defaultTagName, nodeKind) { const rawTag = event.tagStart === NO_RANGE$2 ? "" : state.source.slice(event.tagStart, event.tagEnd); const tagName = rawTag === "" || rawTag === "!" ? defaultTagName : tagNameFull(rawTag, state.tagHandlers); return { tagName, tag: findExplicitTag(state, exact, prefix, tagName, nodeKind) }; } function isMappingTag(tag) { return tag.nodeKind === "mapping"; } function mergeKeys(state, frame, source, sourceTag) { for (const sourceKey of sourceTag.keys(source)) { if (state.maxTotalMergeKeys !== -1 && ++state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`); if (frame.tag.has(frame.value, sourceKey)) continue; const err2 = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey)); if (err2) throwError$1(state, err2); (frame.overridable ??= /* @__PURE__ */ new Set()).add(sourceKey); } } function mergeSource(state, frame, source, sourceTag) { state.position = frame.keyPosition; if (isMappingTag(sourceTag)) mergeKeys(state, frame, source, sourceTag); else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) for (const element of source) mergeKeys(state, frame, element, frame.tag); else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable"); } function addMappingValue(state, frame, key, value, tag) { state.position = frame.keyPosition; if (key === MERGE_KEY) { mergeSource(state, frame, value, tag); return; } if (!state.json && frame.tag.has(frame.value, key) && !frame.overridable?.has(key)) throwError$1(state, "duplicated mapping key"); const err2 = frame.tag.addPair(frame.value, key, value); if (err2) throwError$1(state, err2); frame.overridable?.delete(key); } function addValue(state, value, tag) { const frame = state.frames[state.frames.length - 1]; if (frame.kind === "document") { frame.value = value; frame.hasValue = true; } else if (frame.kind === "sequence") { if (frame.merge) { if (!isMappingTag(tag)) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable"); } const err2 = frame.tag.addItem(frame.value, value, frame.index++); if (err2) throwError$1(state, err2); } else if (frame.hasKey) { const key = frame.key; frame.key = void 0; frame.hasKey = false; addMappingValue(state, frame, key, value, tag); } else { frame.key = value; frame.keyPosition = state.position; frame.hasKey = true; } } function storeAnchor(state, event, value, tag, isValueFinal) { if (event.anchorStart !== NO_RANGE$2) { const anchor = { value, tag, isValueFinal }; state.anchors.set(state.source.slice(event.anchorStart, event.anchorEnd), anchor); return anchor; } return null; } function constructFromEvents(events, options) { const state = { ...DEFAULT_CONSTRUCTOR_OPTIONS, ...options, events, documents: [], eventIndex: 0, position: 0, frames: [], anchors: /* @__PURE__ */ new Map(), tagHandlers: /* @__PURE__ */ Object.create(null), totalMergeKeys: 0, aliasCount: 0 }; while (state.eventIndex < state.events.length) { const event = state.events[state.eventIndex++]; state.position = eventPosition$1(event); switch (event.type) { case 1: state.anchors = /* @__PURE__ */ new Map(); state.aliasCount = 0; state.tagHandlers = /* @__PURE__ */ Object.create(null); for (const directive of event.directives) if (directive.kind === "tag") state.tagHandlers[directive.handle] = directive.prefix; state.frames.push({ kind: "document", position: state.position, value: void 0, hasValue: false }); break; case 4: { const { value, tag } = constructScalar(state, event); storeAnchor(state, event, value, tag, true); addValue(state, value, tag); break; } case 2: { const definition = collectionTag(state, event, state.schema.exact.sequence, state.schema.prefix.sequence, "tag:yaml.org,2002:seq", "sequence"); const value = definition.tag.create(definition.tagName); const anchor = storeAnchor(state, event, value, definition.tag, definition.tag.carrierIsResult); const parent = state.frames[state.frames.length - 1]; const merge2 = parent !== void 0 && parent.kind === "mapping" && parent.hasKey && parent.key === MERGE_KEY; state.frames.push({ kind: "sequence", position: state.position, value, tag: definition.tag, anchor, index: 0, merge: merge2 }); break; } case 3: { const definition = collectionTag(state, event, state.schema.exact.mapping, state.schema.prefix.mapping, "tag:yaml.org,2002:map", "mapping"); const value = definition.tag.create(definition.tagName); const anchor = storeAnchor(state, event, value, definition.tag, definition.tag.carrierIsResult); state.frames.push({ kind: "mapping", position: state.position, value, tag: definition.tag, anchor, key: void 0, keyPosition: state.position, hasKey: false, overridable: null }); break; } case 5: { if (state.maxAliases !== -1 && ++state.aliasCount > state.maxAliases) throwError$1(state, `aliases exceeded maxAliases (${state.maxAliases})`); const name24 = state.source.slice(event.anchorStart, event.anchorEnd); const anchor = state.anchors.get(name24); if (!anchor) throwError$1(state, `unidentified alias "${name24}"`); if (!anchor.isValueFinal) throwError$1(state, `recursive alias "${name24}" is not supported for tag ${anchor.tag.tagName} because it uses finalize()`); addValue(state, anchor.value, anchor.tag); break; } case 6: { const frame = state.frames.pop(); if (frame.kind === "mapping" && frame.hasKey) { state.position = frame.keyPosition; throwError$1(state, "incomplete mapping pair in event stream"); } if (frame.kind === "document") state.documents.push(frame.value); else { const value = frame.tag.carrierIsResult ? frame.value : finalizeCollection(state, frame.position, frame.tag, frame.value); if (frame.anchor) { frame.anchor.value = value; frame.anchor.isValueFinal = true; } addValue(state, value, frame.tag); } break; } } } return state.documents; } var NO_RANGE$1 = -1; var HAS_OWN = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; var CONTEXT_FLOW_OUT = 2; var CONTEXT_BLOCK_IN = 3; var CONTEXT_BLOCK_OUT = 4; var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; var PATTERN_FLOW_INDICATORS = /[,\[\]{}]/; var PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/; var NS_URI_CHAR = String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$,_.!~*'()\[\]])`; var NS_TAG_CHAR = String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$.~*'()_])`; var PATTERN_TAG_URI = new RegExp(`^(?:${NS_URI_CHAR})*$`); var PATTERN_TAG_SUFFIX = new RegExp(`^(?:${NS_TAG_CHAR})+$`); var PATTERN_TAG_PREFIX = new RegExp(`^(?:!(?:${NS_URI_CHAR})*|${NS_TAG_CHAR}(?:${NS_URI_CHAR})*)$`); var DEFAULT_PARSER_OPTIONS = { filename: "", maxDepth: 100 }; function addDocumentEvent(state, explicitStart, explicitEnd) { state.events.push({ type: 1, explicitStart, explicitEnd, directives: state.directives }); } function addSequenceEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) { state.events.push({ type: 2, start, anchorStart, anchorEnd, tagStart, tagEnd, style }); } function addMappingEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) { state.events.push({ type: 3, start, anchorStart, anchorEnd, tagStart, tagEnd, style }); } function insertFlowPairMappingEvent(state, snapshot) { state.events.splice(snapshot.eventsLength, 0, { type: 3, start: snapshot.position, anchorStart: NO_RANGE$1, anchorEnd: NO_RANGE$1, tagStart: NO_RANGE$1, tagEnd: NO_RANGE$1, style: 2 }); } function addScalarEvent(state, valueStart, valueEnd, anchorStart, anchorEnd, tagStart, tagEnd, style, chomping = 1, indent = -1, fast = false) { state.events.push({ type: 4, valueStart, valueEnd, anchorStart, anchorEnd, tagStart, tagEnd, style, chomping, indent, fast }); } function addAliasEvent(state, anchorStart, anchorEnd) { state.events.push({ type: 5, anchorStart, anchorEnd }); } function addPopEvent(state) { state.events.push({ type: 6 }); } function addEmptyScalarEvent(state) { addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, 1); } function emptyProperties() { return { anchorStart: NO_RANGE$1, anchorEnd: NO_RANGE$1, tagStart: NO_RANGE$1, tagEnd: NO_RANGE$1 }; } function snapshotState(state) { return { position: state.position, line: state.line, lineStart: state.lineStart, lineIndent: state.lineIndent, firstTabInLine: state.firstTabInLine, eventsLength: state.events.length }; } function restoreState(state, snapshot) { state.position = snapshot.position; state.line = snapshot.line; state.lineStart = snapshot.lineStart; state.lineIndent = snapshot.lineIndent; state.firstTabInLine = snapshot.firstTabInLine; state.events.length = snapshot.eventsLength; } function throwError(state, message) { throwErrorAt(state.input.slice(0, state.length), state.position, message, state.filename); } function isEol(c2) { return c2 === 10 || c2 === 13; } function isWhiteSpace(c2) { return c2 === 9 || c2 === 32; } function isWsOrEol(c2) { return isWhiteSpace(c2) || isEol(c2); } function isWsOrEolOrEnd(c2) { return c2 === 0 || isWsOrEol(c2); } function isFlowIndicator(c2) { return c2 === 44 || c2 === 91 || c2 === 93 || c2 === 123 || c2 === 125; } function fromDecimalCode(c2) { return c2 >= 48 && c2 <= 57 ? c2 - 48 : -1; } function fromHexCode(c2) { if (c2 >= 48 && c2 <= 57) return c2 - 48; const lc3 = c2 | 32; if (lc3 >= 97 && lc3 <= 102) return lc3 - 97 + 10; return -1; } function escapedHexLen(c2) { if (c2 === 120) return 2; if (c2 === 117) return 4; if (c2 === 85) return 8; return 0; } function isSimpleEscape(c2) { return c2 === 48 || c2 === 97 || c2 === 98 || c2 === 116 || c2 === 9 || c2 === 110 || c2 === 118 || c2 === 102 || c2 === 114 || c2 === 101 || c2 === 32 || c2 === 34 || c2 === 47 || c2 === 92 || c2 === 78 || c2 === 95 || c2 === 76 || c2 === 80; } function consumeLineBreak(state) { if (state.input.charCodeAt(state.position) === 10) state.position++; else { state.position++; if (state.input.charCodeAt(state.position) === 10) state.position++; } state.line++; state.lineStart = state.position; state.lineIndent = 0; state.firstTabInLine = -1; } function skipSeparationSpace(state, allowComments) { let lineBreaks = 0; let ch2 = state.input.charCodeAt(state.position); let hasSeparation = state.position === state.lineStart || isWsOrEol(state.input.charCodeAt(state.position - 1)); while (ch2 !== 0) { while (isWhiteSpace(ch2)) { hasSeparation = true; if (ch2 === 9 && state.firstTabInLine === -1) state.firstTabInLine = state.position; ch2 = state.input.charCodeAt(++state.position); } if (allowComments && hasSeparation && ch2 === 35) do ch2 = state.input.charCodeAt(++state.position); while (!isEol(ch2) && ch2 !== 0); if (!isEol(ch2)) break; consumeLineBreak(state); lineBreaks++; hasSeparation = true; ch2 = state.input.charCodeAt(state.position); while (ch2 === 32) { state.lineIndent++; ch2 = state.input.charCodeAt(++state.position); } } return lineBreaks; } function testDocumentSeparator(state, position = state.position) { const ch2 = state.input.charCodeAt(position); if ((ch2 === 45 || ch2 === 46) && ch2 === state.input.charCodeAt(position + 1) && ch2 === state.input.charCodeAt(position + 2)) { const following = state.input.charCodeAt(position + 3); return following === 0 || isWsOrEol(following); } return false; } function skipUntilLineEnd(state) { let ch2 = state.input.charCodeAt(state.position); while (ch2 !== 0 && !isEol(ch2)) ch2 = state.input.charCodeAt(++state.position); } function checkPrintable(state, start, end) { if (PATTERN_NON_PRINTABLE.test(state.input.slice(start, end))) throwError(state, "the stream contains non-printable characters"); } function readTagProperty(state, props, inFlow) { if (state.input.charCodeAt(state.position) !== 33) return false; if (props.tagStart !== NO_RANGE$1) throwError(state, "duplication of a tag property"); const start = state.position; let isVerbatim = false; let isNamed = false; let tagHandle = "!"; let ch2 = state.input.charCodeAt(++state.position); if (ch2 === 60) { isVerbatim = true; ch2 = state.input.charCodeAt(++state.position); } else if (ch2 === 33) { isNamed = true; tagHandle = "!!"; ch2 = state.input.charCodeAt(++state.position); } let suffixStart = state.position; let tagName; if (isVerbatim) { while (ch2 !== 0 && ch2 !== 62) ch2 = state.input.charCodeAt(++state.position); if (ch2 !== 62) throwError(state, "unexpected end of the stream within a verbatim tag"); tagName = state.input.slice(suffixStart, state.position); state.position++; } else { while (ch2 !== 0 && !isWsOrEol(ch2) && !(inFlow && isFlowIndicator(ch2))) { if (ch2 === 33) if (!isNamed) { tagHandle = state.input.slice(suffixStart - 1, state.position + 1); if (!PATTERN_TAG_HANDLE.test(tagHandle)) throwError(state, "named tag handle cannot contain such characters"); isNamed = true; suffixStart = state.position + 1; } else throwError(state, "tag suffix cannot contain exclamation marks"); ch2 = state.input.charCodeAt(++state.position); } tagName = state.input.slice(suffixStart, state.position); if (PATTERN_FLOW_INDICATORS.test(tagName)) throwError(state, "tag suffix cannot contain flow indicator characters"); } if (tagName && !(isVerbatim ? PATTERN_TAG_URI.test(tagName) : PATTERN_TAG_SUFFIX.test(tagName))) throwError(state, `tag name cannot contain such characters: ${tagName}`); if (!isVerbatim && tagHandle !== "!" && tagHandle !== "!!" && !HAS_OWN.call(state.tagHandlers, tagHandle)) throwError(state, `undeclared tag handle "${tagHandle}"`); props.tagStart = start; props.tagEnd = state.position; return true; } function readAnchorProperty(state, props) { if (state.input.charCodeAt(state.position) !== 38) return false; if (props.anchorStart !== NO_RANGE$1) throwError(state, "duplication of an anchor property"); state.position++; const start = state.position; while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++; if (state.position === start) throwError(state, "name of an anchor node must contain at least one character"); props.anchorStart = start; props.anchorEnd = state.position; return true; } function readAlias(state, props) { if (state.input.charCodeAt(state.position) !== 42) return false; if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) throwError(state, "alias node should not have any properties"); state.position++; const start = state.position; while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++; if (state.position === start) throwError(state, "name of an alias node must contain at least one character"); addAliasEvent(state, start, state.position); return true; } function readFlowScalarBreak(state, nodeIndent) { skipSeparationSpace(state, false); if (state.lineIndent < nodeIndent) throwError(state, "deficient indentation"); } function readSingleQuotedScalar(state, nodeIndent, props) { if (state.input.charCodeAt(state.position) !== 39) return false; state.position++; const start = state.position; let simple = true; while (state.input.charCodeAt(state.position) !== 0) { const ch2 = state.input.charCodeAt(state.position); if (ch2 === 39) { if (state.input.charCodeAt(state.position + 1) === 39) { simple = false; state.position += 2; continue; } const end = state.position; state.position++; addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 2, 1, -1, simple); return true; } if (isEol(ch2)) { simple = false; readFlowScalarBreak(state, nodeIndent); } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a single quoted scalar"); else if (ch2 !== 9 && ch2 < 32) throwError(state, "expected valid JSON character"); else state.position++; } throwError(state, "unexpected end of the stream within a single quoted scalar"); } function readDoubleQuotedScalar(state, nodeIndent, props) { if (state.input.charCodeAt(state.position) !== 34) return false; state.position++; const start = state.position; let simple = true; while (state.input.charCodeAt(state.position) !== 0) { const ch2 = state.input.charCodeAt(state.position); if (ch2 === 34) { const end = state.position; state.position++; addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 3, 1, -1, simple); return true; } if (ch2 === 92) { simple = false; const escaped = state.input.charCodeAt(++state.position); if (isEol(escaped)) readFlowScalarBreak(state, nodeIndent); else if (isSimpleEscape(escaped)) state.position++; else { let hexLength = escapedHexLen(escaped); if (hexLength === 0) throwError(state, "unknown escape sequence"); while (hexLength-- > 0) { state.position++; if (fromHexCode(state.input.charCodeAt(state.position)) < 0) throwError(state, "expected hexadecimal character"); } state.position++; } } else if (isEol(ch2)) { simple = false; readFlowScalarBreak(state, nodeIndent); } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a double quoted scalar"); else if (ch2 !== 9 && ch2 < 32) throwError(state, "expected valid JSON character"); else state.position++; } throwError(state, "unexpected end of the stream within a double quoted scalar"); } function readBlockScalar(state, parentIndent, props) { const ch2 = state.input.charCodeAt(state.position); let chomping = 1; let indent = -1; let detectedIndent = false; if (ch2 !== 124 && ch2 !== 62) return false; const style = ch2 === 124 ? 4 : 5; state.position++; while (state.input.charCodeAt(state.position) !== 0) { const current = state.input.charCodeAt(state.position); const digit = fromDecimalCode(current); if (current === 43 || current === 45) { if (chomping !== 1) throwError(state, "repeat of a chomping mode identifier"); chomping = current === 43 ? 3 : 2; state.position++; } else if (digit >= 0) { if (digit === 0) throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one"); if (detectedIndent) throwError(state, "repeat of an indentation width identifier"); indent = parentIndent + digit - 1; detectedIndent = true; state.position++; } else break; } let hadWhitespace = false; while (isWhiteSpace(state.input.charCodeAt(state.position))) { hadWhitespace = true; state.position++; } if (hadWhitespace && state.input.charCodeAt(state.position) === 35) skipUntilLineEnd(state); if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state); else if (state.input.charCodeAt(state.position) !== 0) throwError(state, "a line break is expected"); let contentIndent = detectedIndent ? indent : -1; let maxLeadingIndent = 0; const valueStart = state.position; let valueEnd = state.position; while (state.input.charCodeAt(state.position) !== 0) { const linePosition = state.position; let column = 0; while (state.input.charCodeAt(linePosition + column) === 32) column++; const first = state.input.charCodeAt(linePosition + column); if (first === 0) { if (contentIndent >= 0) { if (column > contentIndent) valueEnd = linePosition + column; } else if (column > 0) valueEnd = linePosition + column; break; } if (linePosition === state.lineStart && testDocumentSeparator(state, linePosition)) break; if (!detectedIndent && contentIndent === -1 && isEol(first)) maxLeadingIndent = Math.max(maxLeadingIndent, column); if (!detectedIndent && contentIndent === -1 && !isEol(first)) { if (first === 9 && column < parentIndent) { state.position = linePosition + column; throwError(state, "tab characters must not be used in indentation"); } if (column < maxLeadingIndent) { state.position = linePosition + column; throwError(state, "bad indentation of a mapping entry"); } } if (contentIndent === -1 && first !== 0 && !isEol(first) && column < parentIndent) { state.lineIndent = column; state.position = linePosition + column; break; } if (!detectedIndent && first !== 0 && !isEol(first) && contentIndent === -1) contentIndent = column; const requiredIndent = contentIndent === -1 ? parentIndent + 1 : contentIndent; if (first !== 0 && !isEol(first) && column < requiredIndent) { state.lineIndent = column; state.position = linePosition + column; break; } skipUntilLineEnd(state); valueEnd = state.position; if (isEol(state.input.charCodeAt(state.position))) { consumeLineBreak(state); valueEnd = state.position; } } checkPrintable(state, valueStart, valueEnd); addScalarEvent(state, valueStart, valueEnd, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, style, chomping, contentIndent); return true; } function canStartPlainScalar(state, nodeContext) { const ch2 = state.input.charCodeAt(state.position); const inFlow = nodeContext === CONTEXT_FLOW_IN; if (ch2 === 0 || isWsOrEol(ch2) || ch2 === 35 || ch2 === 38 || ch2 === 42 || ch2 === 33 || ch2 === 124 || ch2 === 62 || ch2 === 39 || ch2 === 34 || ch2 === 37 || ch2 === 64 || ch2 === 96 || inFlow && isFlowIndicator(ch2)) return false; if (ch2 === 63 || ch2 === 45) { const following = state.input.charCodeAt(state.position + 1); if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) return false; } return true; } function readPlainScalar(state, nodeIndent, nodeContext, props) { if (!canStartPlainScalar(state, nodeContext)) return false; const start = state.position; let end = state.position; let ch2 = state.input.charCodeAt(state.position); const inFlow = nodeContext === CONTEXT_FLOW_IN; let multiline2 = false; while (ch2 !== 0) { if (state.position === state.lineStart && testDocumentSeparator(state)) break; if (ch2 === 58) { const following = state.input.charCodeAt(state.position + 1); if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) break; } else if (ch2 === 35) { if (isWsOrEol(state.input.charCodeAt(state.position - 1))) break; } else if (inFlow && isFlowIndicator(ch2)) break; else if (isEol(ch2)) { const savedPosition = state.position; const savedLine = state.line; const savedLineStart = state.lineStart; const savedLineIndent = state.lineIndent; skipSeparationSpace(state, false); if (state.lineIndent >= nodeIndent) { multiline2 = true; ch2 = state.input.charCodeAt(state.position); continue; } state.position = savedPosition; state.line = savedLine; state.lineStart = savedLineStart; state.lineIndent = savedLineIndent; break; } if (!isWhiteSpace(ch2)) end = state.position + 1; ch2 = state.input.charCodeAt(++state.position); } if (end === start) return false; checkPrintable(state, start, end); addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1, 1, -1, !multiline2); return true; } function skipFlowSeparationSpace(state, nodeIndent) { const startLine = state.line; skipSeparationSpace(state, true); if (state.line > startLine && state.lineIndent < nodeIndent || state.firstTabInLine !== -1 && state.lineIndent < nodeIndent) throwError(state, "deficient indentation"); } function readFlowCollection(state, nodeIndent, props) { const ch2 = state.input.charCodeAt(state.position); const isMapping = ch2 === 123; const start = state.position; let readNext = true; if (ch2 !== 91 && ch2 !== 123) return false; const terminator = isMapping ? 125 : 93; if (isMapping) addMappingEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 2); else addSequenceEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 2); state.position++; while (state.input.charCodeAt(state.position) !== 0) { skipFlowSeparationSpace(state, nodeIndent); let ch3 = state.input.charCodeAt(state.position); if (ch3 === terminator) { state.position++; addPopEvent(state); return true; } else if (!readNext) throwError(state, "missed comma between flow collection entries"); else if (ch3 === 44) throwError(state, "expected the node content, but found ','"); let isPair = false; let isExplicitPair = false; if (ch3 === 63 && isWsOrEol(state.input.charCodeAt(state.position + 1))) { isPair = isExplicitPair = true; state.position += 1; skipFlowSeparationSpace(state, nodeIndent); } const entryLine = state.line; const entryStart = snapshotState(state); const keyWasRead = parseNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); skipFlowSeparationSpace(state, nodeIndent); ch3 = state.input.charCodeAt(state.position); if ((isMapping || isExplicitPair || state.line === entryLine) && ch3 === 58) { isPair = true; state.position++; skipFlowSeparationSpace(state, nodeIndent); if (!isMapping) { insertFlowPairMappingEvent(state, entryStart); if (!keyWasRead) addEmptyScalarEvent(state); } else if (!keyWasRead) addEmptyScalarEvent(state); if (!parseNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)) addEmptyScalarEvent(state); skipFlowSeparationSpace(state, nodeIndent); if (!isMapping) addPopEvent(state); } else if (isMapping && isPair) { if (!keyWasRead) addEmptyScalarEvent(state); addEmptyScalarEvent(state); } else if (isMapping) addEmptyScalarEvent(state); else if (isPair) { insertFlowPairMappingEvent(state, entryStart); if (!keyWasRead) addEmptyScalarEvent(state); addEmptyScalarEvent(state); addPopEvent(state); } ch3 = state.input.charCodeAt(state.position); if (ch3 === 44) { readNext = true; state.position++; } else readNext = false; } throwError(state, "unexpected end of the stream within a flow collection"); } function readBlockSequence(state, nodeIndent, props) { if (state.firstTabInLine !== -1 || state.input.charCodeAt(state.position) !== 45 || !isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) return false; addSequenceEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1); while (state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) { if (state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, "tab characters must not be used in indentation"); } const entryLine = state.line; state.position++; const hadBreak = skipSeparationSpace(state, true) > 0; if (state.firstTabInLine !== -1 && state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) throwError(state, "bad indentation of a sequence entry"); if (hadBreak && state.lineIndent <= nodeIndent) addEmptyScalarEvent(state); else parseNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); skipSeparationSpace(state, true); if (state.lineIndent < nodeIndent || state.position >= state.length) break; if (state.lineIndent > nodeIndent) throwError(state, "bad indentation of a sequence entry"); if (state.line === entryLine && state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) throwError(state, "bad indentation of a sequence entry"); } addPopEvent(state); return true; } function readBlockMapping(state, nodeIndent, flowIndent, props) { let atExplicitKey = false; let detected = false; let mappingOpened = false; let pendingExplicitKey = false; if (state.firstTabInLine !== -1) return false; let ch2 = state.input.charCodeAt(state.position); while (ch2 !== 0) { if (!atExplicitKey && state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, "tab characters must not be used in indentation"); } const following = state.input.charCodeAt(state.position + 1); const entryLine = state.line; if ((ch2 === 63 || ch2 === 58) && isWsOrEolOrEnd(following)) { if (!mappingOpened) { addMappingEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1); mappingOpened = true; } if (ch2 === 63) { if (atExplicitKey) addEmptyScalarEvent(state); detected = true; atExplicitKey = true; } else if (atExplicitKey) atExplicitKey = false; else { addEmptyScalarEvent(state); detected = true; atExplicitKey = false; } state.position += 1; pendingExplicitKey = true; } else { if (atExplicitKey) { addEmptyScalarEvent(state); atExplicitKey = false; } const beforeKey = snapshotState(state); if (!parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) break; if (state.line === entryLine) { ch2 = state.input.charCodeAt(state.position); while (isWhiteSpace(ch2)) ch2 = state.input.charCodeAt(++state.position); if (ch2 === 58) { ch2 = state.input.charCodeAt(++state.position); if (!isWsOrEolOrEnd(ch2)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping"); if (!mappingOpened) { restoreState(state, beforeKey); addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1); mappingOpened = true; parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true); ch2 = state.input.charCodeAt(state.position); while (isWhiteSpace(ch2)) ch2 = state.input.charCodeAt(++state.position); state.position++; } detected = true; atExplicitKey = false; pendingExplicitKey = false; } else if (detected) throwError(state, "expected ':' after a mapping key"); else { if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) { restoreState(state, beforeKey); return false; } return true; } } else if (detected) throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key"); else { if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) { restoreState(state, beforeKey); return false; } return true; } } if (parseNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, pendingExplicitKey)) pendingExplicitKey = false; if (!atExplicitKey) { if (pendingExplicitKey) { addEmptyScalarEvent(state); pendingExplicitKey = false; } } skipSeparationSpace(state, true); ch2 = state.input.charCodeAt(state.position); if ((state.line === entryLine || state.lineIndent > nodeIndent) && ch2 !== 0) throwError(state, "bad indentation of a mapping entry"); else if (state.lineIndent < nodeIndent) break; } if (!detected) return false; if (atExplicitKey) addEmptyScalarEvent(state); if (mappingOpened) addPopEvent(state); return true; } function parseNode(state, parentIndent, nodeContext, allowToSeek, allowCompact, allowPropertyMapping = true) { if (state.depth >= state.maxDepth) throwError(state, `nesting exceeded maxDepth (${state.maxDepth})`); state.depth++; let indentStatus = 1; let atNewLine = false; let hasContent = false; let propertyStart = null; const props = emptyProperties(); let allowBlockScalars = nodeContext === CONTEXT_BLOCK_OUT || nodeContext === CONTEXT_BLOCK_IN; let allowBlockCollections = allowBlockScalars; const allowBlockStyles = allowBlockScalars; if (allowToSeek && skipSeparationSpace(state, true)) { atNewLine = true; if (state.lineIndent > parentIndent) indentStatus = 1; else if (state.lineIndent === parentIndent) indentStatus = 0; else indentStatus = -1; } if (indentStatus === 1) while (true) { const ch2 = state.input.charCodeAt(state.position); const propertyState = snapshotState(state); if (atNewLine && indentStatus !== 1 && (ch2 === 33 || ch2 === 38)) break; if (atNewLine && allowBlockStyles && (props.tagStart !== NO_RANGE$1 || props.anchorStart !== NO_RANGE$1) && (ch2 === 33 || ch2 === 38)) { const fallbackState = snapshotState(state); const flowIndent = parentIndent + 1; if (readBlockMapping(state, state.position - state.lineStart, flowIndent, props) && state.events[fallbackState.eventsLength]?.type === 3) { state.depth--; return true; } restoreState(state, fallbackState); } if (atNewLine && (ch2 === 33 && props.tagStart !== NO_RANGE$1 || ch2 === 38 && props.anchorStart !== NO_RANGE$1)) break; if (!readTagProperty(state, props, nodeContext === CONTEXT_FLOW_IN) && !readAnchorProperty(state, props)) break; if (propertyStart === null) propertyStart = propertyState; if (skipSeparationSpace(state, true)) { atNewLine = true; allowBlockCollections = allowBlockStyles; if (state.lineIndent > parentIndent) indentStatus = 1; else if (state.lineIndent === parentIndent) indentStatus = 0; else indentStatus = -1; } else allowBlockCollections = false; } if (allowBlockCollections) allowBlockCollections = atNewLine || allowCompact; if (indentStatus === 1 || nodeContext === CONTEXT_BLOCK_OUT) { const flowIndent = nodeContext === CONTEXT_FLOW_IN || nodeContext === CONTEXT_FLOW_OUT ? parentIndent : parentIndent + 1; const blockIndent = state.position - state.lineStart; if (indentStatus === 1) if (allowBlockCollections && (readBlockSequence(state, blockIndent, props) || readBlockMapping(state, blockIndent, flowIndent, props)) || readFlowCollection(state, flowIndent, props)) hasContent = true; else { const ch2 = state.input.charCodeAt(state.position); if (propertyStart !== null && allowPropertyMapping && allowBlockStyles && !allowBlockCollections && ch2 !== 124 && ch2 !== 62) { const fallbackState = snapshotState(state); const propertyIndent = propertyStart.position - propertyStart.lineStart; restoreState(state, propertyStart); if (readBlockMapping(state, propertyIndent, flowIndent, emptyProperties()) && state.events[fallbackState.eventsLength]?.type === 3) hasContent = true; else restoreState(state, fallbackState); } if (!hasContent && (allowBlockScalars && readBlockScalar(state, flowIndent, props) || readSingleQuotedScalar(state, flowIndent, props) || readDoubleQuotedScalar(state, flowIndent, props) || readAlias(state, props) || readPlainScalar(state, flowIndent, nodeContext, props))) hasContent = true; } else if (indentStatus === 0) hasContent = allowBlockCollections && readBlockSequence(state, blockIndent, props); } allowBlockScalars = allowBlockScalars && !hasContent; if (!hasContent && (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1 || allowBlockScalars)) { addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1); hasContent = true; } state.depth--; return hasContent || props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1; } function readDirective(state) { if (state.lineIndent > 0 || state.input.charCodeAt(state.position) !== 37) return false; state.position++; const nameStart = state.position; while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++; const name24 = state.input.slice(nameStart, state.position); const args = []; if (name24.length === 0) throwError(state, "directive name must not be less than one character in length"); while (state.input.charCodeAt(state.position) !== 0 && !isEol(state.input.charCodeAt(state.position))) { while (isWhiteSpace(state.input.charCodeAt(state.position))) state.position++; if (state.input.charCodeAt(state.position) === 35 || isEol(state.input.charCodeAt(state.position)) || state.input.charCodeAt(state.position) === 0) break; const start = state.position; while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++; args.push(state.input.slice(start, state.position)); } if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state); if (name24 === "YAML") { if (state.directives.some((directive) => directive.kind === "yaml")) throwError(state, "duplication of %YAML directive"); if (args.length !== 1) throwError(state, "YAML directive accepts exactly one argument"); const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); if (match === null) throwError(state, "ill-formed argument of the YAML directive"); if (parseInt(match[1], 10) !== 1) throwError(state, "unacceptable YAML version of the document"); state.directives.push({ kind: "yaml", version: args[0] }); } else if (name24 === "TAG") { if (args.length !== 2) throwError(state, "TAG directive accepts exactly two arguments"); const [handle, prefix] = args; if (!PATTERN_TAG_HANDLE.test(handle)) throwError(state, "ill-formed tag handle (first argument) of the TAG directive"); if (HAS_OWN.call(state.tagHandlers, handle)) throwError(state, `there is a previously declared suffix for "${handle}" tag handle`); if (!PATTERN_TAG_PREFIX.test(prefix)) throwError(state, "ill-formed tag prefix (second argument) of the TAG directive"); state.tagHandlers[handle] = prefix; state.directives.push({ kind: "tag", handle, prefix }); } return true; } function readDocument(state) { state.directives = []; state.tagHandlers = /* @__PURE__ */ Object.create(null); let hasDirectives = false; skipSeparationSpace(state, true); while (readDirective(state)) { hasDirectives = true; skipSeparationSpace(state, true); } let explicitStart = false; let explicitEnd = false; let allowCompact = true; if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 3))) { explicitStart = true; const markerLine = state.line; state.position += 3; skipSeparationSpace(state, true); allowCompact = state.line > markerLine; } else if (hasDirectives) throwError(state, "directives end mark is expected"); const documentEventIndex = state.events.length; if (!explicitStart && state.position === state.lineStart && state.input.charCodeAt(state.position) === 46 && testDocumentSeparator(state)) { state.position += 3; skipSeparationSpace(state, true); return; } addDocumentEvent(state, explicitStart, false); if (!parseNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, allowCompact, allowCompact)) addEmptyScalarEvent(state); skipSeparationSpace(state, true); if (state.position === state.lineStart && testDocumentSeparator(state)) { explicitEnd = state.input.charCodeAt(state.position) === 46; if (explicitEnd) { const markerLine = state.line; state.position += 3; skipSeparationSpace(state, true); if (state.line === markerLine && state.position < state.length) throwError(state, "end of the stream or a document separator is expected"); } } const documentEvent = state.events[documentEventIndex]; if (documentEvent?.type === 1) documentEvent.explicitEnd = explicitEnd; addPopEvent(state); if (!explicitEnd && state.position < state.length && !(state.position === state.lineStart && testDocumentSeparator(state))) throwError(state, "end of the stream or a document separator is expected"); } function parseEvents(input, options) { const length = input.length; const state = { ...DEFAULT_PARSER_OPTIONS, ...options, input: `${input}\0`, length, position: 0, line: 0, lineStart: 0, lineIndent: 0, firstTabInLine: -1, depth: 0, directives: [], tagHandlers: /* @__PURE__ */ Object.create(null), events: [] }; const nullpos = input.indexOf("\0"); if (nullpos !== -1) throwErrorAt(input, nullpos, "null byte is not allowed in input", state.filename); if (state.input.charCodeAt(state.position) === 65279) state.position++; while (state.position < state.length) { skipSeparationSpace(state, true); if (state.position >= state.length) break; const documentStart = state.position; readDocument(state); if (state.position === documentStart) throwError(state, "can not read a document"); } return state.events; } var DEFAULT_LOAD_OPTIONS = { ...DEFAULT_PARSER_OPTIONS, ...DEFAULT_CONSTRUCTOR_OPTIONS }; function loadDocuments(input, options = {}) { const opts = { ...DEFAULT_LOAD_OPTIONS, ...options }; const source = String(input); const PARSER_OPT_KEYS = Object.keys(DEFAULT_PARSER_OPTIONS); const CONSTRUCTOR_OPT_KEYS = Object.keys(DEFAULT_CONSTRUCTOR_OPTIONS); return constructFromEvents(parseEvents(source, pick3(opts, PARSER_OPT_KEYS)), { ...pick3(opts, CONSTRUCTOR_OPT_KEYS), source }); } function load(input, options) { const documents = loadDocuments(input, options); if (documents.length === 0) throw new YAMLException("expected a document, but the input is empty"); if (documents.length === 1) return documents[0]; throw new YAMLException("expected a single document in the stream, but found more"); } var ESCAPE_SEQUENCES = {}; ESCAPE_SEQUENCES[0] = "\\0"; ESCAPE_SEQUENCES[7] = "\\a"; ESCAPE_SEQUENCES[8] = "\\b"; ESCAPE_SEQUENCES[9] = "\\t"; ESCAPE_SEQUENCES[10] = "\\n"; ESCAPE_SEQUENCES[11] = "\\v"; ESCAPE_SEQUENCES[12] = "\\f"; ESCAPE_SEQUENCES[13] = "\\r"; ESCAPE_SEQUENCES[27] = "\\e"; ESCAPE_SEQUENCES[34] = '\\"'; ESCAPE_SEQUENCES[92] = "\\\\"; ESCAPE_SEQUENCES[133] = "\\N"; ESCAPE_SEQUENCES[160] = "\\_"; ESCAPE_SEQUENCES[8232] = "\\L"; ESCAPE_SEQUENCES[8233] = "\\P"; var DEFAULT_PRESENTER_OPTIONS = { indent: 2, seqNoIndent: false, seqInlineFirst: true, sortKeys: false, lineWidth: 80, flowBracketPadding: false, flowSkipCommaSpace: false, flowSkipColonSpace: false, quoteFlowKeys: false, quoteStyle: "single", forceQuotes: false, tagBeforeAnchor: false }; var DEFAULT_DUMP_SCHEMA = YAML11_SCHEMA.withTags({ ...intYaml11Tag, resolve: (source, isExplicit, tagName) => { const result = intYaml11Tag.resolve(source, isExplicit, tagName); return result === NOT_RESOLVED ? intCoreTag.resolve(source, isExplicit, tagName) : result; } }, { ...floatYaml11Tag, resolve: (source, isExplicit, tagName) => { const result = floatYaml11Tag.resolve(source, isExplicit, tagName); return result === NOT_RESOLVED ? floatCoreTag.resolve(source, isExplicit, tagName) : result; } }); var DEFAULT_DUMP_OPTIONS = { ...DEFAULT_PRESENTER_OPTIONS, schema: DEFAULT_DUMP_SCHEMA, skipInvalid: false, noRefs: false, flowLevel: -1, transform: () => { } }; // node_modules/@flatten-js/core/dist/main.mjs var CCW = true; var CW = false; var ORIENTATION = { CCW: -1, CW: 1, NOT_ORIENTABLE: 0 }; var PIx2 = 2 * Math.PI; var INSIDE$2 = 1; var OUTSIDE$1 = 0; var BOUNDARY$1 = 2; var CONTAINS = 3; var INTERLACE = 4; var OVERLAP_SAME$1 = 1; var OVERLAP_OPPOSITE$1 = 2; var NOT_VERTEX$1 = 0; var START_VERTEX$1 = 1; var END_VERTEX$1 = 2; var Constants = /* @__PURE__ */ Object.freeze({ __proto__: null, BOUNDARY: BOUNDARY$1, CCW, CONTAINS, CW, END_VERTEX: END_VERTEX$1, INSIDE: INSIDE$2, INTERLACE, NOT_VERTEX: NOT_VERTEX$1, ORIENTATION, OUTSIDE: OUTSIDE$1, OVERLAP_OPPOSITE: OVERLAP_OPPOSITE$1, OVERLAP_SAME: OVERLAP_SAME$1, PIx2, START_VERTEX: START_VERTEX$1 }); var DP_TOL = 1e-6; function setTolerance(tolerance) { DP_TOL = tolerance; } function getTolerance() { return DP_TOL; } var DECIMALS = 3; function EQ_0(x4) { return x4 < DP_TOL && x4 > -DP_TOL; } function EQ(x4, y2) { return x4 - y2 < DP_TOL && x4 - y2 > -DP_TOL; } function GT(x4, y2) { return x4 - y2 > DP_TOL; } function GE(x4, y2) { return x4 - y2 > -DP_TOL; } function LT(x4, y2) { return x4 - y2 < -DP_TOL; } function LE(x4, y2) { return x4 - y2 < DP_TOL; } var Utils$1 = /* @__PURE__ */ Object.freeze({ __proto__: null, DECIMALS, EQ, EQ_0, GE, GT, LE, LT, getTolerance, setTolerance }); var Flatten = { Utils: Utils$1, Errors: void 0, Matrix: void 0, Planar_set: void 0, Point: void 0, Vector: void 0, Line: void 0, Circle: void 0, Segment: void 0, Arc: void 0, Box: void 0, Edge: void 0, Face: void 0, Ray: void 0, Ray_shooting: void 0, Multiline: void 0, Polygon: void 0, Distance: void 0, Inversion: void 0 }; for (let c2 in Constants) { Flatten[c2] = Constants[c2]; } Object.defineProperty(Flatten, "DP_TOL", { get: function() { return getTolerance(); }, set: function(value) { setTolerance(value); } }); var Errors = class { /** * Throw error ILLEGAL_PARAMETERS when cannot instantiate from given parameter * @returns {ReferenceError} */ static get ILLEGAL_PARAMETERS() { return new ReferenceError("Illegal Parameters"); } /** * Throw error ZERO_DIVISION to catch situation of zero division * @returns {Error} */ static get ZERO_DIVISION() { return new Error("Zero division"); } /** * Error to throw from BooleanOperations module in case when fixBoundaryConflicts not capable to fix it * @returns {Error} */ static get UNRESOLVED_BOUNDARY_CONFLICT() { return new Error("Unresolved boundary conflict in boolean operation"); } /** * Error to throw from LinkedList:testInfiniteLoop static method * in case when circular loop detected in linked list * @returns {Error} */ static get INFINITE_LOOP() { return new Error("Infinite loop"); } static get CANNOT_COMPLETE_BOOLEAN_OPERATION() { return new Error("Cannot complete boolean operation"); } static get CANNOT_INVOKE_ABSTRACT_METHOD() { return new Error("Abstract method cannot be invoked"); } static get OPERATION_IS_NOT_SUPPORTED() { return new Error("Operation is not supported"); } static get UNSUPPORTED_SHAPE_TYPE() { return new Error("Unsupported shape type"); } }; Flatten.Errors = Errors; var LinkedList = class { constructor(first, last) { this.first = first; this.last = last || this.first; } [Symbol.iterator]() { let value = void 0; return { next: () => { value = value ? value.next : this.first; return { value, done: value === void 0 }; } }; } /** * Return number of elements in the list * @returns {number} */ get size() { let counter = 0; for (let edge of this) { counter++; } return counter; } /** * Return array of elements from start to end, * If start or end not defined, take first as start, last as end * @returns {Array} */ toArray(start = void 0, end = void 0) { let elements = []; let from = start || this.first; let to = end || this.last; let element = from; if (element === void 0) return elements; do { elements.push(element); element = element.next; } while (element !== to.next); return elements; } /** * Append new element to the end of the list * @param {LinkedListElement} element * @returns {LinkedList} */ append(element) { if (this.isEmpty()) { this.first = element; } else { element.prev = this.last; this.last.next = element; } this.last = element; this.last.next = void 0; this.first.prev = void 0; return this; } /** * Insert new element to the list after elementBefore * @param {LinkedListElement} newElement * @param {LinkedListElement} elementBefore * @returns {LinkedList} */ insert(newElement, elementBefore) { if (this.isEmpty()) { this.first = newElement; this.last = newElement; } else if (elementBefore === null || elementBefore === void 0) { newElement.next = this.first; this.first.prev = newElement; this.first = newElement; } else { let elementAfter = elementBefore.next; elementBefore.next = newElement; if (elementAfter) elementAfter.prev = newElement; newElement.prev = elementBefore; newElement.next = elementAfter; if (this.last === elementBefore) this.last = newElement; } this.last.next = void 0; this.first.prev = void 0; return this; } /** * Remove element from the list * @param {LinkedListElement} element * @returns {LinkedList} */ remove(element) { if (element === this.first && element === this.last) { this.first = void 0; this.last = void 0; } else { if (element.prev) element.prev.next = element.next; if (element.next) element.next.prev = element.prev; if (element === this.first) { this.first = element.next; } if (element === this.last) { this.last = element.prev; } } return this; } /** * Return true if list is empty * @returns {boolean} */ isEmpty() { return this.first === void 0; } /** * Throw an error if circular loop detected in the linked list * @param {LinkedListElement} first element to start iteration * @throws {Errors.INFINITE_LOOP} */ static testInfiniteLoop(first) { let edge = first; let controlEdge = first; do { if (edge != first && edge === controlEdge) { throw Errors.INFINITE_LOOP; } edge = edge.next; controlEdge = controlEdge.next.next; } while (edge != first); } }; var defaultAttributes = { stroke: "black" }; var SVGAttributes = class { constructor(args = defaultAttributes) { for (const property in args) { this[property] = args[property]; } this.stroke = args.stroke ?? defaultAttributes.stroke; } toAttributesString() { return Object.keys(this).reduce( (acc, key) => acc + (this[key] !== void 0 ? this.toAttrString(key, this[key]) : ""), `` ); } toAttrString(key, value) { const SVGKey = key === "className" ? "class" : this.convertCamelToKebabCase(key); return value === null ? `${SVGKey} ` : `${SVGKey}="${value.toString()}" `; } convertCamelToKebabCase(str) { return str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).join("-").toLowerCase(); } }; function convertToString(attrs) { return new SVGAttributes(attrs).toAttributesString(); } function intersectLine2Line(line1, line2) { let ip = []; let [A1, B1, C1] = line1.standard; let [A2, B22, C2] = line2.standard; let det = A1 * B22 - B1 * A2; let detX = C1 * B22 - B1 * C2; let detY = A1 * C2 - C1 * A2; if (!Flatten.Utils.EQ_0(det)) { let x4, y2; if (B1 === 0) { x4 = C1 / A1; y2 = detY / det; } else if (B22 === 0) { x4 = C2 / A2; y2 = detY / det; } else if (A1 === 0) { x4 = detX / det; y2 = C1 / B1; } else if (A2 === 0) { x4 = detX / det; y2 = C2 / B22; } else { x4 = detX / det; y2 = detY / det; } ip.push(new Flatten.Point(x4, y2)); } return ip; } function intersectLine2Circle(line2, circle2) { let ip = []; let prj = circle2.pc.projectionOn(line2); let dist = circle2.pc.distanceTo(prj)[0]; if (Flatten.Utils.EQ(dist, circle2.r)) { ip.push(prj); } else if (Flatten.Utils.LT(dist, circle2.r)) { let delta = Math.sqrt(circle2.r * circle2.r - dist * dist); let v_trans, pt2; v_trans = line2.norm.rotate90CCW().multiply(delta); pt2 = prj.translate(v_trans); ip.push(pt2); v_trans = line2.norm.rotate90CW().multiply(delta); pt2 = prj.translate(v_trans); ip.push(pt2); } return ip; } function intersectLine2Box(line2, box2) { let ips = []; for (let seg of box2.toSegments()) { let ips_tmp = intersectSegment2Line(seg, line2); for (let pt2 of ips_tmp) { if (!ptInIntPoints(pt2, ips)) { ips.push(pt2); } } } return ips; } function intersectLine2Arc(line2, arc2) { let ip = []; if (intersectLine2Box(line2, arc2.box).length === 0) { return ip; } let circle2 = new Flatten.Circle(arc2.pc, arc2.r); let ip_tmp = intersectLine2Circle(line2, circle2); for (let pt2 of ip_tmp) { if (pt2.on(arc2)) { ip.push(pt2); } } return ip; } function intersectSegment2Line(seg, line2) { let ip = []; if (seg.ps.on(line2)) { ip.push(seg.ps); } if (seg.pe.on(line2) && !seg.isZeroLength()) { ip.push(seg.pe); } if (ip.length > 0) { return ip; } if (seg.isZeroLength()) { return ip; } if (seg.ps.leftTo(line2) && seg.pe.leftTo(line2) || !seg.ps.leftTo(line2) && !seg.pe.leftTo(line2)) { return ip; } let line1 = new Flatten.Line(seg.ps, seg.pe); return intersectLine2Line(line1, line2); } function intersectSegment2Segment(seg1, seg2) { let ip = []; if (seg1.isZeroLength()) { if (seg1.ps.on(seg2)) { ip.push(seg1.ps); } return ip; } if (seg2.isZeroLength()) { if (seg2.ps.on(seg1)) { ip.push(seg2.ps); } return ip; } let line1 = new Flatten.Line(seg1.ps, seg1.pe); let line2 = new Flatten.Line(seg2.ps, seg2.pe); if (line1.incidentTo(line2)) { if (seg1.ps.on(seg2)) { ip.push(seg1.ps); } if (seg1.pe.on(seg2)) { ip.push(seg1.pe); } if (seg2.ps.on(seg1) && !seg2.ps.equalTo(seg1.ps) && !seg2.ps.equalTo(seg1.pe)) { ip.push(seg2.ps); } if (seg2.pe.on(seg1) && !seg2.pe.equalTo(seg1.ps) && !seg2.pe.equalTo(seg1.pe)) { ip.push(seg2.pe); } } else if (line1.parallelTo(line2)) { const r4 = new Flatten.Vector(seg1.ps, seg1.pe); const s2 = new Flatten.Vector(seg2.ps, seg2.pe); const q_p = new Flatten.Vector(seg1.ps, seg2.ps); const r_cross_s = r4.cross(s2); if (!Flatten.Utils.EQ_0(r_cross_s)) { const t4 = q_p.cross(s2) / r_cross_s; const u2 = q_p.cross(r4) / r_cross_s; if (Flatten.Utils.GE(t4, 0) && Flatten.Utils.LE(t4, 1) && Flatten.Utils.GE(u2, 0) && Flatten.Utils.LE(u2, 1)) { ip.push(snapToSegmentEndpoints(seg1.ps.translate(r4.multiply(t4)), seg1, seg2)); } } } else { let new_ip = intersectLine2Line(line1, line2); if (new_ip.length > 0) { if (isPointInSegmentBox(new_ip[0], seg1) && isPointInSegmentBox(new_ip[0], seg2)) { ip.push(snapToSegmentEndpoints(new_ip[0], seg1, seg2)); } } } return ip; } function snapToSegmentEndpoints(pt2, seg1, seg2) { for (const endpoint of [seg1.ps, seg1.pe, seg2.ps, seg2.pe]) { if (pt2.equalTo(endpoint)) { return endpoint; } } return pt2; } function isPointInSegmentBox(point2, segment2) { const box2 = segment2.box; return Flatten.Utils.LE(point2.x, box2.xmax) && Flatten.Utils.GE(point2.x, box2.xmin) && Flatten.Utils.LE(point2.y, box2.ymax) && Flatten.Utils.GE(point2.y, box2.ymin); } function intersectSegment2Circle(segment2, circle2) { let ips = []; if (segment2.isZeroLength()) { let [dist, _2] = segment2.ps.distanceTo(circle2.pc); if (Flatten.Utils.EQ(dist, circle2.r)) { ips.push(segment2.ps); } return ips; } let line2 = new Flatten.Line(segment2.ps, segment2.pe); let ips_tmp = intersectLine2Circle(line2, circle2); for (let ip of ips_tmp) { if (ip.on(segment2)) { ips.push(ip); } } return ips; } function intersectSegment2Arc(segment2, arc2) { let ip = []; if (segment2.isZeroLength()) { if (segment2.ps.on(arc2)) { ip.push(segment2.ps); } return ip; } let line2 = new Flatten.Line(segment2.ps, segment2.pe); let circle2 = new Flatten.Circle(arc2.pc, arc2.r); let ip_tmp = intersectLine2Circle(line2, circle2); for (let pt2 of ip_tmp) { if (pt2.on(segment2) && pt2.on(arc2)) { ip.push(pt2); } } return ip; } function intersectSegment2Box(segment2, box2) { let ips = []; for (let seg of box2.toSegments()) { let ips_tmp = intersectSegment2Segment(seg, segment2); for (let ip of ips_tmp) { ips.push(ip); } } return ips; } function intersectCircle2Circle(circle1, circle2) { let ip = []; let vec = new Flatten.Vector(circle1.pc, circle2.pc); let r1 = circle1.r; let r22 = circle2.r; if (Flatten.Utils.EQ_0(r1) || Flatten.Utils.EQ_0(r22)) return ip; if (Flatten.Utils.EQ_0(vec.x) && Flatten.Utils.EQ_0(vec.y) && Flatten.Utils.EQ(r1, r22)) { ip.push(circle1.pc.translate(-r1, 0)); return ip; } let dist = circle1.pc.distanceTo(circle2.pc)[0]; if (Flatten.Utils.GT(dist, r1 + r22)) return ip; if (Flatten.Utils.LT(dist, Math.abs(r1 - r22))) return ip; vec.x /= dist; vec.y /= dist; let pt2; if (Flatten.Utils.EQ(dist, r1 + r22) || Flatten.Utils.EQ(dist, Math.abs(r1 - r22))) { pt2 = circle1.pc.translate(r1 * vec.x, r1 * vec.y); ip.push(pt2); return ip; } let a3 = r1 * r1 / (2 * dist) - r22 * r22 / (2 * dist) + dist / 2; let mid_pt = circle1.pc.translate(a3 * vec.x, a3 * vec.y); let h2 = Math.sqrt(r1 * r1 - a3 * a3); pt2 = mid_pt.translate(vec.rotate90CCW().multiply(h2)); ip.push(pt2); pt2 = mid_pt.translate(vec.rotate90CW().multiply(h2)); ip.push(pt2); return ip; } function intersectCircle2Box(circle2, box2) { let ips = []; for (let seg of box2.toSegments()) { let ips_tmp = intersectSegment2Circle(seg, circle2); for (let ip of ips_tmp) { ips.push(ip); } } return ips; } function intersectArc2Arc(arc1, arc2) { let ip = []; if (arc1.pc.equalTo(arc2.pc) && Flatten.Utils.EQ(arc1.r, arc2.r)) { let pt2; pt2 = arc1.start; if (pt2.on(arc2)) ip.push(pt2); pt2 = arc1.end; if (pt2.on(arc2)) ip.push(pt2); pt2 = arc2.start; if (pt2.on(arc1)) ip.push(pt2); pt2 = arc2.end; if (pt2.on(arc1)) ip.push(pt2); return ip; } let circle1 = new Flatten.Circle(arc1.pc, arc1.r); let circle2 = new Flatten.Circle(arc2.pc, arc2.r); let ip_tmp = circle1.intersect(circle2); for (let pt2 of ip_tmp) { if (pt2.on(arc1) && pt2.on(arc2)) { ip.push(pt2); } } return ip; } function intersectArc2Circle(arc2, circle2) { let ip = []; if (circle2.pc.equalTo(arc2.pc) && Flatten.Utils.EQ(circle2.r, arc2.r)) { ip.push(arc2.start); ip.push(arc2.end); return ip; } let circle1 = circle2; let circle22 = new Flatten.Circle(arc2.pc, arc2.r); let ip_tmp = intersectCircle2Circle(circle1, circle22); for (let pt2 of ip_tmp) { if (pt2.on(arc2)) { ip.push(pt2); } } return ip; } function intersectArc2Box(arc2, box2) { let ips = []; for (let seg of box2.toSegments()) { let ips_tmp = intersectSegment2Arc(seg, arc2); for (let ip of ips_tmp) { ips.push(ip); } } return ips; } function intersectEdge2Segment(edge, segment2) { return edge.isSegment ? intersectSegment2Segment(edge.shape, segment2) : intersectSegment2Arc(segment2, edge.shape); } function intersectEdge2Arc(edge, arc2) { return edge.isSegment ? intersectSegment2Arc(edge.shape, arc2) : intersectArc2Arc(edge.shape, arc2); } function intersectEdge2Line(edge, line2) { return edge.isSegment ? intersectSegment2Line(edge.shape, line2) : intersectLine2Arc(line2, edge.shape); } function intersectEdge2Ray(edge, ray2) { return edge.isSegment ? intersectRay2Segment(ray2, edge.shape) : intersectRay2Arc(ray2, edge.shape); } function intersectEdge2Circle(edge, circle2) { return edge.isSegment ? intersectSegment2Circle(edge.shape, circle2) : intersectArc2Circle(edge.shape, circle2); } function intersectSegment2Polygon(segment2, polygon2) { let ip = []; for (let edge of polygon2.edges) { for (let pt2 of intersectEdge2Segment(edge, segment2)) { ip.push(pt2); } } return ip; } function intersectArc2Polygon(arc2, polygon2) { let ip = []; for (let edge of polygon2.edges) { for (let pt2 of intersectEdge2Arc(edge, arc2)) { ip.push(pt2); } } return ip; } function intersectLine2Polygon(line2, polygon2) { let ip = []; if (polygon2.isEmpty()) { return ip; } for (let edge of polygon2.edges) { for (let pt2 of intersectEdge2Line(edge, line2)) { if (!ptInIntPoints(pt2, ip)) { ip.push(pt2); } } } return line2.sortPoints(ip); } function intersectCircle2Polygon(circle2, polygon2) { let ip = []; if (polygon2.isEmpty()) { return ip; } for (let edge of polygon2.edges) { for (let pt2 of intersectEdge2Circle(edge, circle2)) { ip.push(pt2); } } return ip; } function intersectEdge2Edge(edge1, edge2) { if (edge1.isSegment) { return intersectEdge2Segment(edge2, edge1.shape); } else if (edge1.isArc) { return intersectEdge2Arc(edge2, edge1.shape); } else if (edge1.isLine) { return intersectEdge2Line(edge2, edge1.shape); } else if (edge1.isRay) { return intersectEdge2Ray(edge2, edge1.shape); } return []; } function intersectEdge2Polygon(edge, polygon2) { let ip = []; if (polygon2.isEmpty() || edge.shape.box.not_intersect(polygon2.box)) { return ip; } let resp_edges = polygon2.edges.search(edge.shape.box); for (let resp_edge of resp_edges) { ip = [...ip, ...intersectEdge2Edge(edge, resp_edge)]; } return ip; } function intersectMultiline2Polygon(multiline2, polygon2) { let ip = []; if (polygon2.isEmpty() || multiline2.size === 0) { return ip; } for (let edge of multiline2) { ip = [...ip, ...intersectEdge2Polygon(edge, polygon2)]; } return ip; } function intersectPolygon2Polygon(polygon1, polygon2) { let ip = []; if (polygon1.isEmpty() || polygon2.isEmpty()) { return ip; } if (polygon1.box.not_intersect(polygon2.box)) { return ip; } for (let edge1 of polygon1.edges) { ip = [...ip, ...intersectEdge2Polygon(edge1, polygon2)]; } return ip; } function intersectShape2Polygon(shape, polygon2) { if (shape instanceof Flatten.Line) { return intersectLine2Polygon(shape, polygon2); } else if (shape instanceof Flatten.Segment) { return intersectSegment2Polygon(shape, polygon2); } else if (shape instanceof Flatten.Arc) { return intersectArc2Polygon(shape, polygon2); } else { return []; } } function ptInIntPoints(new_pt, ip) { return ip.some((pt2) => pt2.equalTo(new_pt)); } function createLineFromRay(ray2) { return new Flatten.Line(ray2.start, ray2.norm); } function intersectRay2Segment(ray2, segment2) { return intersectSegment2Line(segment2, createLineFromRay(ray2)).filter((pt2) => ray2.contains(pt2)); } function intersectRay2Arc(ray2, arc2) { return intersectLine2Arc(createLineFromRay(ray2), arc2).filter((pt2) => ray2.contains(pt2)); } function intersectRay2Circle(ray2, circle2) { return intersectLine2Circle(createLineFromRay(ray2), circle2).filter((pt2) => ray2.contains(pt2)); } function intersectRay2Box(ray2, box2) { return intersectLine2Box(createLineFromRay(ray2), box2).filter((pt2) => ray2.contains(pt2)); } function intersectRay2Line(ray2, line2) { return intersectLine2Line(createLineFromRay(ray2), line2).filter((pt2) => ray2.contains(pt2)); } function intersectRay2Ray(ray1, ray2) { return intersectLine2Line(createLineFromRay(ray1), createLineFromRay(ray2)).filter((pt2) => ray1.contains(pt2)).filter((pt2) => ray2.contains(pt2)); } function intersectRay2Polygon(ray2, polygon2) { return intersectLine2Polygon(createLineFromRay(ray2), polygon2).filter((pt2) => ray2.contains(pt2)); } function intersectShape2Shape(shape1, shape2) { if (shape1.intersect && shape1.intersect instanceof Function) { return shape1.intersect(shape2); } throw Errors.UNSUPPORTED_SHAPE_TYPE; } function intersectShape2Multiline(shape, multiline2) { let ip = []; for (let edge of multiline2) { ip = [...ip, ...intersectShape2Shape(shape, edge.shape)]; } return ip; } function intersectMultiline2Multiline(multiline1, multiline2) { let ip = []; for (let edge1 of multiline1) { for (let edge2 of multiline2) { ip = [...ip, ...intersectShape2Shape(edge1.shape, edge2.shape)]; } } return ip; } var Multiline$1 = class Multiline extends LinkedList { constructor(...args) { super(); this.isInfinite = false; if (args.length === 1 && args[0] instanceof Array && args[0].length > 0) { const shapes = args[0]; const L3 = shapes.length; const anyShape = (s2) => s2 instanceof Flatten.Segment || s2 instanceof Flatten.Arc || s2 instanceof Flatten.Ray || s2 instanceof Flatten.Line; const anyShapeExceptLine = (s2) => s2 instanceof Flatten.Segment || s2 instanceof Flatten.Arc || s2 instanceof Flatten.Ray; const shapeSegmentOrArc = (s2) => s2 instanceof Flatten.Segment || s2 instanceof Flatten.Arc; const validShapes = L3 === 1 && anyShape(shapes[0]) || L3 > 1 && anyShapeExceptLine(shapes[0]) && anyShapeExceptLine(shapes[L3 - 1]) && shapes.slice(1, L3 - 1).every(shapeSegmentOrArc); if (validShapes) { this.isInfinite = shapes.some( (shape) => shape instanceof Flatten.Ray || shape instanceof Flatten.Line ); for (let shape of shapes) { let edge = new Flatten.Edge(shape); this.append(edge); } this.setArcLength(); } else { throw Flatten.Errors.ILLEGAL_PARAMETERS; } } } /** * (Getter) Return array of edges * @returns {Edge[]} */ get edges() { return [...this]; } /** * (Getter) Return bounding box of the multiline * @returns {Box} */ get box() { return this.edges.reduce((acc, edge) => acc.merge(edge.box), new Flatten.Box()); } /** * (Getter) Returns array of vertices * @returns {Point[]} */ get vertices() { let v2 = this.edges.map((edge) => edge.start); v2.push(this.last.end); return v2; } /** * (Getter) Returns length of the multiline, return POSITIVE_INFINITY if multiline is infinite * @returns {number} */ get length() { if (this.isEmpty()) return 0; if (this.isInfinite) return Number.POSITIVE_INFINITY; let len = 0; for (let edge of this) { len += edge.length; } return len; } /** * Return new cloned instance of Multiline * @returns {Multiline} */ clone() { return new Multiline(this.toShapes()); } /** * Set arc_length property for each of the edges in the multiline. * Arc_length of the edge is the arc length from the multiline start vertex to the edge start vertex */ setArcLength() { for (let edge of this) { this.setOneEdgeArcLength(edge); } } setOneEdgeArcLength(edge) { if (edge === this.first) { edge.arc_length = 0; } else { edge.arc_length = edge.prev.arc_length + edge.prev.length; } } /** * Return point on multiline at given length from the start of the multiline * @param length * @returns {Point | null} */ pointAtLength(length) { if (length > this.length || length < 0) return null; if (this.isInfinite) return null; let point2 = null; for (let edge of this) { if (length >= edge.arc_length && (edge === this.last || length < edge.next.arc_length)) { point2 = edge.pointAtLength(length - edge.arc_length); break; } } return point2; } /** * Split edge and add new vertex, return new edge inserted * @param {Point} pt - point on edge that will be added as new vertex * @param {Edge} edge - edge to split * @returns {Edge} */ addVertex(pt2, edge) { let shapes = edge.shape.split(pt2); if (shapes[0] === null) return edge.prev; if (shapes[1] === null) return edge; let newEdge = new Flatten.Edge(shapes[0]); let edgeBefore = edge.prev; this.insert(newEdge, edgeBefore); edge.shape = shapes[1]; return newEdge; } getChain(edgeFrom, edgeTo) { let edges = []; for (let edge = edgeFrom; edge !== edgeTo.next; edge = edge.next) { edges.push(edge); } return edges; } /** * Split edges of multiline with intersection points and return mutated multiline * @param {Point[]} ip - array of points to be added as new vertices * @returns {Multiline} */ split(ip) { for (let pt2 of ip) { let edge = this.findEdgeByPoint(pt2); this.addVertex(pt2, edge); } return this; } /** * Returns edge which contains given point * @param {Point} pt * @returns {Edge} */ findEdgeByPoint(pt2) { let edgeFound; for (let edge of this) { if (edge.shape.contains(pt2)) { edgeFound = edge; break; } } return edgeFound; } /** * Calculate distance and shortest segment from any shape to multiline * @param shape * @returns {[number,Flatten.Segment]} */ distanceTo(shape) { if (shape instanceof Point) { const [dist, shortest_segment] = Flatten.Distance.shape2multiline(shape, this); return [dist, shortest_segment.reverse()]; } if (shape instanceof Flatten.Line) { const [dist, shortest_segment] = Flatten.Distance.shape2multiline(shape, this); return [dist, shortest_segment.reverse()]; } if (shape instanceof Flatten.Circle) { const [dist, shortest_segment] = Flatten.Distance.shape2multiline(shape, this); return [dist, shortest_segment.reverse()]; } if (shape instanceof Flatten.Segment) { const [dist, shortest_segment] = Flatten.Distance.shape2multiline(shape, this); return [dist, shortest_segment.reverse()]; } if (shape instanceof Flatten.Arc) { const [dist, shortest_segment] = Flatten.Distance.shape2multiline(shape, this); return [dist, shortest_segment.reverse()]; } if (shape instanceof Flatten.Multiline) { return Flatten.Distance.multiline2multiline(this, shape); } throw Flatten.Errors.UNSUPPORTED_SHAPE_TYPE; } /** * Calculate intersection of multiline with other shape * @param {Shape} shape * @returns {Point[]} */ intersect(shape) { if (shape instanceof Flatten.Multiline) { return intersectMultiline2Multiline(this, shape); } else { return intersectShape2Multiline(shape, this); } } /** * Return true if multiline contains the shape: no point of shape lies outside * @param shape * @returns {boolean} */ contains(shape) { if (shape instanceof Flatten.Point) { return this.edges.some((edge) => edge.shape.contains(shape)); } throw Flatten.Errors.UNSUPPORTED_SHAPE_TYPE; } /** * Returns new multiline translated by vector vec * @param {Vector} vec * @returns {Multiline} */ translate(vec) { return new Multiline(this.edges.map((edge) => edge.shape.translate(vec))); } /** * Return new multiline rotated by given angle around given point * If point omitted, rotate around origin (0,0) * Positive value of angle defines rotation counterclockwise, negative - clockwise * @param {number} angle - rotation angle in radians * @param {Point} center - rotation center, default is (0,0) * @returns {Multiline} - new rotated polygon */ rotate(angle = 0, center = new Flatten.Point()) { return new Multiline(this.edges.map((edge) => edge.shape.rotate(angle, center))); } /** * Return new multiline transformed using affine transformation matrix * Method does not support unbounded shapes * @param {Matrix} matrix - affine transformation matrix * @returns {Multiline} - new multiline */ transform(matrix2 = new Flatten.Matrix()) { return new Multiline(this.edges.map((edge) => edge.shape.transform(matrix2))); } /** * Transform multiline into array of shapes * @returns {Shape[]} */ toShapes() { return this.edges.map((edge) => edge.shape.clone()); } /** * This method returns an object that defines how data will be * serialized when called JSON.stringify() method * @returns {Object} */ toJSON() { return this.edges.map((edge) => edge.toJSON()); } /** * Return string to be inserted into 'points' attribute of element * @returns {string} */ svgPoints() { return this.vertices.map((p2) => `${p2.x},${p2.y}`).join(" "); } /** * Return string to be assigned to 'd' attribute of element * @returns {string} */ dpath() { let dPathStr = `M${this.first.start.x},${this.first.start.y}`; for (let edge of this) { dPathStr += edge.svg(); } return dPathStr; } /** * Return string to draw multiline in svg * @param attrs - an object with attributes for svg path element * TODO: support semi-infinite Ray and infinite Line * @returns {string} */ svg(attrs = {}) { let svgStr = ` `; return svgStr; } }; Flatten.Multiline = Multiline$1; var multiline = (...args) => new Flatten.Multiline(...args); Flatten.multiline = multiline; function addToIntPoints(edge, pt2, int_points) { let id = int_points.length; let shapes = edge.shape.split(pt2); if (shapes.length === 0) return; let len = 0; if (shapes[0] === null) { len = 0; } else if (shapes[1] === null) { len = edge.shape.length; } else { len = shapes[0].length; } let is_vertex = NOT_VERTEX$1; if (EQ(len, 0)) { is_vertex |= START_VERTEX$1; } if (EQ(len, edge.shape.length)) { is_vertex |= END_VERTEX$1; } let arc_length; if (len === Infinity) { arc_length = shapes[0].coord(pt2); } else { arc_length = is_vertex & END_VERTEX$1 && edge.next && edge.next.arc_length === 0 ? 0 : edge.arc_length + len; } int_points.push({ id, pt: pt2, arc_length, edge_before: edge, edge_after: void 0, face: edge.face, is_vertex }); } function sortIntersections(intersections) { intersections.int_points1_sorted = getSortedArray(intersections.int_points1); intersections.int_points2_sorted = getSortedArray(intersections.int_points2); } function getSortedArray(int_points) { let faceMap = /* @__PURE__ */ new Map(); let id = 0; for (let ip of int_points) { if (!faceMap.has(ip.face)) { faceMap.set(ip.face, id); id++; } } for (let ip of int_points) { ip.faceId = faceMap.get(ip.face); } let int_points_sorted = int_points.slice().sort(compareFn); return int_points_sorted; } function compareFn(ip1, ip2) { if (ip1.faceId < ip2.faceId) { return -1; } if (ip1.faceId > ip2.faceId) { return 1; } if (ip1.arc_length < ip2.arc_length) { return -1; } if (ip1.arc_length > ip2.arc_length) { return 1; } return 0; } function filterDuplicatedIntersections(intersections) { if (intersections.int_points1.length < 2) return; let do_squeeze = false; let int_point_ref1; let int_point_ref2; let int_point_cur1; let int_point_cur2; for (let i4 = 0; i4 < intersections.int_points1_sorted.length; i4++) { if (intersections.int_points1_sorted[i4].id === -1) continue; int_point_ref1 = intersections.int_points1_sorted[i4]; int_point_ref2 = intersections.int_points2[int_point_ref1.id]; for (let j2 = i4 + 1; j2 < intersections.int_points1_sorted.length; j2++) { int_point_cur1 = intersections.int_points1_sorted[j2]; if (!EQ(int_point_cur1.arc_length, int_point_ref1.arc_length)) { break; } if (int_point_cur1.id === -1) continue; int_point_cur2 = intersections.int_points2[int_point_cur1.id]; if (int_point_cur2.id === -1) continue; if (int_point_cur1.edge_before === int_point_ref1.edge_before && int_point_cur1.edge_after === int_point_ref1.edge_after && int_point_cur2.edge_before === int_point_ref2.edge_before && int_point_cur2.edge_after === int_point_ref2.edge_after) { int_point_cur1.id = -1; int_point_cur2.id = -1; do_squeeze = true; } } } int_point_ref2 = intersections.int_points2_sorted[0]; int_point_ref1 = intersections.int_points1[int_point_ref2.id]; for (let i4 = 1; i4 < intersections.int_points2_sorted.length; i4++) { let int_point_cur22 = intersections.int_points2_sorted[i4]; if (int_point_cur22.id === -1) continue; if (int_point_ref2.id === -1 || /* can't be reference if already deleted */ !EQ(int_point_cur22.arc_length, int_point_ref2.arc_length)) { int_point_ref2 = int_point_cur22; int_point_ref1 = intersections.int_points1[int_point_ref2.id]; continue; } let int_point_cur12 = intersections.int_points1[int_point_cur22.id]; if (int_point_cur12.edge_before === int_point_ref1.edge_before && int_point_cur12.edge_after === int_point_ref1.edge_after && int_point_cur22.edge_before === int_point_ref2.edge_before && int_point_cur22.edge_after === int_point_ref2.edge_after) { int_point_cur12.id = -1; int_point_cur22.id = -1; do_squeeze = true; } } if (do_squeeze) { intersections.int_points1 = intersections.int_points1.filter((int_point) => int_point.id >= 0); intersections.int_points2 = intersections.int_points2.filter((int_point) => int_point.id >= 0); intersections.int_points1.forEach((int_point, index) => int_point.id = index); intersections.int_points2.forEach((int_point, index) => int_point.id = index); } } function initializeInclusionFlags(int_points) { for (let int_point of int_points) { if (int_point.edge_before) { int_point.edge_before.bvStart = void 0; int_point.edge_before.bvEnd = void 0; int_point.edge_before.bv = void 0; int_point.edge_before.overlap = void 0; } if (int_point.edge_after) { int_point.edge_after.bvStart = void 0; int_point.edge_after.bvEnd = void 0; int_point.edge_after.bv = void 0; int_point.edge_after.overlap = void 0; } } for (let int_point of int_points) { if (int_point.edge_before) int_point.edge_before.bvEnd = BOUNDARY$1; if (int_point.edge_after) int_point.edge_after.bvStart = BOUNDARY$1; } } function calculateInclusionFlags(int_points, polygon2) { for (let int_point of int_points) { if (int_point.edge_before) int_point.edge_before.setInclusion(polygon2); if (int_point.edge_after) int_point.edge_after.setInclusion(polygon2); } } function setOverlappingFlags(intersections) { let cur_face = void 0; let first_int_point_in_face_id = void 0; let next_int_point1 = void 0; let num_int_points = intersections.int_points1.length; for (let i4 = 0; i4 < num_int_points; i4++) { let cur_int_point1 = intersections.int_points1_sorted[i4]; if (cur_int_point1.face !== cur_face) { first_int_point_in_face_id = i4; cur_face = cur_int_point1.face; } let int_points_cur_pool_start = i4; let int_points_cur_pool_num = intPointsPoolCount(intersections.int_points1_sorted, i4, cur_face); let next_int_point_id; if (int_points_cur_pool_start + int_points_cur_pool_num < num_int_points && intersections.int_points1_sorted[int_points_cur_pool_start + int_points_cur_pool_num].face === cur_face) { next_int_point_id = int_points_cur_pool_start + int_points_cur_pool_num; } else { next_int_point_id = first_int_point_in_face_id; } let int_points_next_pool_num = intPointsPoolCount(intersections.int_points1_sorted, next_int_point_id, cur_face); next_int_point1 = null; for (let j2 = next_int_point_id; j2 < next_int_point_id + int_points_next_pool_num; j2++) { let next_int_point1_tmp = intersections.int_points1_sorted[j2]; if (next_int_point1_tmp.face === cur_face && intersections.int_points2[next_int_point1_tmp.id].face === intersections.int_points2[cur_int_point1.id].face) { next_int_point1 = next_int_point1_tmp; break; } } if (next_int_point1 === null) continue; let edge_from1 = cur_int_point1.edge_after; let edge_to1 = next_int_point1.edge_before; if (!(edge_from1.bv === BOUNDARY$1 && edge_to1.bv === BOUNDARY$1)) continue; if (edge_from1 !== edge_to1) continue; let cur_int_point2 = intersections.int_points2[cur_int_point1.id]; let next_int_point2 = intersections.int_points2[next_int_point1.id]; let edge_from2 = cur_int_point2.edge_after; let edge_to2 = next_int_point2.edge_before; if (!(edge_from2.bv === BOUNDARY$1 && edge_to2.bv === BOUNDARY$1 && edge_from2 === edge_to2)) { cur_int_point2 = intersections.int_points2[next_int_point1.id]; next_int_point2 = intersections.int_points2[cur_int_point1.id]; edge_from2 = cur_int_point2.edge_after; edge_to2 = next_int_point2.edge_before; } if (!(edge_from2.bv === BOUNDARY$1 && edge_to2.bv === BOUNDARY$1 && edge_from2 === edge_to2)) continue; edge_from1.setOverlap(edge_from2); } } function intPointsPoolCount(int_points, cur_int_point_num, cur_face) { let int_point_current; let int_point_next; let int_points_pool_num = 1; if (int_points.length === 1) return 1; int_point_current = int_points[cur_int_point_num]; for (let i4 = cur_int_point_num + 1; i4 < int_points.length; i4++) { if (int_point_current.face !== cur_face) { break; } int_point_next = int_points[i4]; if (!(int_point_next.pt.equalTo(int_point_current.pt) && int_point_next.edge_before === int_point_current.edge_before && int_point_next.edge_after === int_point_current.edge_after)) { break; } int_points_pool_num++; } return int_points_pool_num; } function splitByIntersections(polygon2, int_points) { if (!int_points) return; for (let int_point of int_points) { let edge = int_point.edge_before; int_point.is_vertex = NOT_VERTEX$1; if (edge.shape.start && edge.shape.start.equalTo(int_point.pt)) { int_point.is_vertex |= START_VERTEX$1; } if (edge.shape.end && edge.shape.end.equalTo(int_point.pt)) { int_point.is_vertex |= END_VERTEX$1; } if (int_point.is_vertex & START_VERTEX$1) { int_point.edge_before = edge.prev; if (edge.prev) { int_point.is_vertex = END_VERTEX$1; } continue; } if (int_point.is_vertex & END_VERTEX$1) { continue; } let newEdge = polygon2.addVertex(int_point.pt, edge); int_point.edge_before = newEdge; } for (let int_point of int_points) { if (int_point.edge_before) { int_point.edge_after = int_point.edge_before.next; } else { if (polygon2 instanceof Multiline$1 && int_point.is_vertex & START_VERTEX$1) { int_point.edge_after = polygon2.first; } } } } function insertBetweenIntPoints(int_point1, int_point2, new_edges) { const edge_before = int_point1.edge_before; const edge_after = int_point2.edge_after; const len = new_edges.length; edge_before.next = new_edges[0]; new_edges[0].prev = edge_before; new_edges[len - 1].next = edge_after; edge_after.prev = new_edges[len - 1]; } var { INSIDE: INSIDE$1, OUTSIDE, BOUNDARY, OVERLAP_SAME, OVERLAP_OPPOSITE } = Constants; var { NOT_VERTEX, START_VERTEX, END_VERTEX } = Constants; var BOOLEAN_UNION = 1; var BOOLEAN_INTERSECT = 2; var BOOLEAN_SUBTRACT = 3; function unify(polygon1, polygon2) { let [res_poly, wrk_poly] = booleanOpBinary(polygon1, polygon2, BOOLEAN_UNION, true); return res_poly; } function subtract(polygon1, polygon2) { let polygon2_tmp = polygon2.clone(); let polygon2_reversed = polygon2_tmp.reverse(); let [res_poly, wrk_poly] = booleanOpBinary(polygon1, polygon2_reversed, BOOLEAN_SUBTRACT, true); return res_poly; } function intersect$1(polygon1, polygon2) { let [res_poly, wrk_poly] = booleanOpBinary(polygon1, polygon2, BOOLEAN_INTERSECT, true); return res_poly; } function innerClip(polygon1, polygon2) { let [res_poly, wrk_poly] = booleanOpBinary(polygon1, polygon2, BOOLEAN_INTERSECT, false); let clip_shapes1 = []; for (let face of res_poly.faces) { clip_shapes1 = [...clip_shapes1, ...[...face.edges].map((edge) => edge.shape)]; } let clip_shapes2 = []; for (let face of wrk_poly.faces) { clip_shapes2 = [...clip_shapes2, ...[...face.edges].map((edge) => edge.shape)]; } return [clip_shapes1, clip_shapes2]; } function outerClip(polygon1, polygon2) { let [res_poly, wrk_poly] = booleanOpBinary(polygon1, polygon2, BOOLEAN_SUBTRACT, false); let clip_shapes1 = []; for (let face of res_poly.faces) { clip_shapes1 = [...clip_shapes1, ...[...face.edges].map((edge) => edge.shape)]; } return clip_shapes1; } function calculateIntersections(polygon1, polygon2) { let res_poly = polygon1.clone(); let wrk_poly = polygon2.clone(); let intersections = getIntersections(res_poly, wrk_poly); sortIntersections(intersections); splitByIntersections(res_poly, intersections.int_points1_sorted); splitByIntersections(wrk_poly, intersections.int_points2_sorted); filterDuplicatedIntersections(intersections); sortIntersections(intersections); let ip_sorted1 = intersections.int_points1_sorted.map((int_point) => int_point.pt); let ip_sorted2 = intersections.int_points2_sorted.map((int_point) => int_point.pt); return [ip_sorted1, ip_sorted2]; } function filterNotRelevantEdges(res_poly, wrk_poly, intersections, op) { let notIntersectedFacesRes = getNotIntersectedFaces(res_poly, intersections.int_points1); let notIntersectedFacesWrk = getNotIntersectedFaces(wrk_poly, intersections.int_points2); calcInclusionForNotIntersectedFaces(notIntersectedFacesRes, wrk_poly); calcInclusionForNotIntersectedFaces(notIntersectedFacesWrk, res_poly); initializeInclusionFlags(intersections.int_points1); initializeInclusionFlags(intersections.int_points2); calculateInclusionFlags(intersections.int_points1, wrk_poly); calculateInclusionFlags(intersections.int_points2, res_poly); while (fixBoundaryConflicts(res_poly, wrk_poly, intersections.int_points1, intersections.int_points1_sorted, intersections.int_points2, intersections)) ; setOverlappingFlags(intersections); removeNotRelevantChains(res_poly, op, intersections.int_points1_sorted, true); removeNotRelevantChains(wrk_poly, op, intersections.int_points2_sorted, false); removeNotRelevantNotIntersectedFaces(res_poly, notIntersectedFacesRes, op, true); removeNotRelevantNotIntersectedFaces(wrk_poly, notIntersectedFacesWrk, op, false); } function swapLinksAndRestore(res_poly, wrk_poly, intersections, op) { copyWrkToRes(res_poly, wrk_poly, op, intersections.int_points2); swapLinks(res_poly, wrk_poly, intersections); removeOldFaces(res_poly, intersections.int_points1); removeOldFaces(wrk_poly, intersections.int_points2); restoreFaces(res_poly, intersections.int_points1, intersections.int_points2); restoreFaces(res_poly, intersections.int_points2, intersections.int_points1); removeDetachedEdges(res_poly); removeDetachedEdges(wrk_poly); } function booleanOpBinary(polygon1, polygon2, op, restore) { let res_poly = polygon1.clone(); let wrk_poly = polygon2.clone(); let intersections = getIntersections(res_poly, wrk_poly); sortIntersections(intersections); splitByIntersections(res_poly, intersections.int_points1_sorted); splitByIntersections(wrk_poly, intersections.int_points2_sorted); filterDuplicatedIntersections(intersections); sortIntersections(intersections); filterNotRelevantEdges(res_poly, wrk_poly, intersections, op); if (restore) { swapLinksAndRestore(res_poly, wrk_poly, intersections, op); } return [res_poly, wrk_poly]; } function getIntersections(polygon1, polygon2) { let intersections = { int_points1: [], int_points2: [] }; for (let edge1 of polygon1.edges) { let resp = polygon2.edges.search(edge1.box); for (let edge2 of resp) { let ip = edge1.shape.intersect(edge2.shape); for (let pt2 of ip) { addToIntPoints(edge1, pt2, intersections.int_points1); addToIntPoints(edge2, pt2, intersections.int_points2); } } } return intersections; } function getNotIntersectedFaces(poly, int_points) { let notIntersected = []; for (let face of poly.faces) { if (!int_points.find((ip) => ip.face === face)) { notIntersected.push(face); } } return notIntersected; } function calcInclusionForNotIntersectedFaces(notIntersectedFaces, poly2) { for (let face of notIntersectedFaces) { face.first.bv = face.first.bvStart = face.first.bvEnd = void 0; face.first.setInclusion(poly2); } } function fixBoundaryConflicts(poly1, poly2, int_points1, int_points1_sorted, int_points2, intersections) { let cur_face; let first_int_point_in_face_id; let next_int_point1; let num_int_points = int_points1_sorted.length; let iterate_more = false; for (let i4 = 0; i4 < num_int_points; i4++) { let cur_int_point1 = int_points1_sorted[i4]; if (cur_int_point1.face !== cur_face) { first_int_point_in_face_id = i4; cur_face = cur_int_point1.face; } let int_points_cur_pool_start = i4; let int_points_cur_pool_num = intPointsPoolCount(int_points1_sorted, i4, cur_face); let next_int_point_id; if (int_points_cur_pool_start + int_points_cur_pool_num < num_int_points && int_points1_sorted[int_points_cur_pool_start + int_points_cur_pool_num].face === cur_face) { next_int_point_id = int_points_cur_pool_start + int_points_cur_pool_num; } else { next_int_point_id = first_int_point_in_face_id; } let int_points_next_pool_num = intPointsPoolCount(int_points1_sorted, next_int_point_id, cur_face); next_int_point1 = null; for (let j2 = next_int_point_id; j2 < next_int_point_id + int_points_next_pool_num; j2++) { let next_int_point1_tmp = int_points1_sorted[j2]; if (next_int_point1_tmp.face === cur_face && int_points2[next_int_point1_tmp.id].face === int_points2[cur_int_point1.id].face) { next_int_point1 = next_int_point1_tmp; break; } } if (next_int_point1 === null) continue; let edge_from1 = cur_int_point1.edge_after; let edge_to1 = next_int_point1.edge_before; if (edge_from1.bv === BOUNDARY && edge_to1.bv != BOUNDARY) { edge_from1.bv = edge_to1.bv; continue; } if (edge_from1.bv != BOUNDARY && edge_to1.bv === BOUNDARY) { edge_to1.bv = edge_from1.bv; continue; } if (edge_from1.bv === BOUNDARY && edge_to1.bv === BOUNDARY && edge_from1 != edge_to1 || (edge_from1.bv === INSIDE$1 && edge_to1.bv === OUTSIDE || edge_from1.bv === OUTSIDE && edge_to1.bv === INSIDE$1)) { let edge_tmp = edge_from1.next; while (edge_tmp != edge_to1) { edge_tmp.bvStart = void 0; edge_tmp.bvEnd = void 0; edge_tmp.bv = void 0; edge_tmp.setInclusion(poly2); edge_tmp = edge_tmp.next; } } if (edge_from1.bv === BOUNDARY && edge_to1.bv === BOUNDARY && edge_from1 != edge_to1) { let edge_tmp = edge_from1.next; let new_bv; while (edge_tmp != edge_to1) { if (edge_tmp.bv != BOUNDARY) { if (new_bv === void 0) { new_bv = edge_tmp.bv; } else { if (edge_tmp.bv != new_bv) { throw Errors.UNRESOLVED_BOUNDARY_CONFLICT; } } } edge_tmp = edge_tmp.next; } if (new_bv != void 0) { edge_from1.bv = new_bv; edge_to1.bv = new_bv; } continue; } if (edge_from1.bv === INSIDE$1 && edge_to1.bv === OUTSIDE || edge_from1.bv === OUTSIDE && edge_to1.bv === INSIDE$1) { let edge_tmp = edge_from1; while (edge_tmp != edge_to1) { if (edge_tmp.bvStart === edge_from1.bv && edge_tmp.bvEnd === edge_to1.bv) { let [dist, segment2] = edge_tmp.shape.distanceTo(poly2); if (dist < 10 * Flatten.DP_TOL) { addToIntPoints(edge_tmp, segment2.ps, int_points1); let int_point1 = int_points1[int_points1.length - 1]; if (int_point1.is_vertex & START_VERTEX) { int_point1.edge_after = edge_tmp; int_point1.edge_before = edge_tmp.prev; edge_tmp.bvStart = BOUNDARY; edge_tmp.bv = void 0; edge_tmp.setInclusion(poly2); } else if (int_point1.is_vertex & END_VERTEX) { int_point1.edge_after = edge_tmp.next; edge_tmp.bvEnd = BOUNDARY; edge_tmp.bv = void 0; edge_tmp.setInclusion(poly2); } else { let newEdge1 = poly2.addVertex(int_point1.pt, edge_tmp); int_point1.edge_before = newEdge1; int_point1.edge_after = newEdge1.next; newEdge1.setInclusion(poly2); newEdge1.next.bvStart = BOUNDARY; newEdge1.next.bvEnd = void 0; newEdge1.next.bv = void 0; newEdge1.next.setInclusion(poly2); } let edge2 = poly2.findEdgeByPoint(segment2.pe); addToIntPoints(edge2, segment2.pe, int_points2); let int_point2 = int_points2[int_points2.length - 1]; if (int_point2.is_vertex & START_VERTEX) { int_point2.edge_after = edge2; int_point2.edge_before = edge2.prev; } else if (int_point2.is_vertex & END_VERTEX) { int_point2.edge_after = edge2.next; } else { let int_point2_edge_after = int_points2.find((int_point) => int_point.edge_after === edge2); let newEdge2 = poly2.addVertex(int_point2.pt, edge2); int_point2.edge_before = newEdge2; int_point2.edge_after = newEdge2.next; if (int_point2_edge_after) int_point2_edge_after.edge_after = newEdge2; newEdge2.bvStart = void 0; newEdge2.bvEnd = BOUNDARY; newEdge2.bv = void 0; newEdge2.setInclusion(poly1); newEdge2.next.bvStart = BOUNDARY; newEdge2.next.bvEnd = void 0; newEdge2.next.bv = void 0; newEdge2.next.setInclusion(poly1); } sortIntersections(intersections); iterate_more = true; break; } } edge_tmp = edge_tmp.next; } if (iterate_more) break; throw Errors.UNRESOLVED_BOUNDARY_CONFLICT; } } return iterate_more; } function removeNotRelevantChains(polygon2, op, int_points, is_res_polygon) { if (!int_points) return; let cur_face = void 0; let first_int_point_in_face_num = void 0; let int_point_current; let int_point_next; for (let i4 = 0; i4 < int_points.length; i4++) { int_point_current = int_points[i4]; if (int_point_current.face !== cur_face) { first_int_point_in_face_num = i4; cur_face = int_point_current.face; } if (cur_face.isEmpty()) continue; let int_points_from_pull_start = i4; let int_points_from_pull_num = intPointsPoolCount(int_points, i4, cur_face); let next_int_point_num; if (int_points_from_pull_start + int_points_from_pull_num < int_points.length && int_points[int_points_from_pull_start + int_points_from_pull_num].face === int_point_current.face) { next_int_point_num = int_points_from_pull_start + int_points_from_pull_num; } else { next_int_point_num = first_int_point_in_face_num; } int_point_next = int_points[next_int_point_num]; let int_points_to_pull_start = next_int_point_num; let int_points_to_pull_num = intPointsPoolCount(int_points, int_points_to_pull_start, cur_face); let edge_from = int_point_current.edge_after; let edge_to = int_point_next.edge_before; if (edge_from.bv === INSIDE$1 && edge_to.bv === INSIDE$1 && op === BOOLEAN_UNION || edge_from.bv === OUTSIDE && edge_to.bv === OUTSIDE && op === BOOLEAN_INTERSECT || (edge_from.bv === OUTSIDE || edge_to.bv === OUTSIDE) && op === BOOLEAN_SUBTRACT && !is_res_polygon || (edge_from.bv === INSIDE$1 || edge_to.bv === INSIDE$1) && op === BOOLEAN_SUBTRACT && is_res_polygon || edge_from.bv === BOUNDARY && edge_to.bv === BOUNDARY && edge_from.overlap & OVERLAP_SAME && is_res_polygon || edge_from.bv === BOUNDARY && edge_to.bv === BOUNDARY && edge_from.overlap & OVERLAP_OPPOSITE) { polygon2.removeChain(cur_face, edge_from, edge_to); for (let k = int_points_from_pull_start; k < int_points_from_pull_start + int_points_from_pull_num; k++) { int_points[k].edge_after = void 0; } for (let k = int_points_to_pull_start; k < int_points_to_pull_start + int_points_to_pull_num; k++) { int_points[k].edge_before = void 0; } } i4 += int_points_from_pull_num - 1; } } function copyWrkToRes(res_polygon, wrk_polygon, op, int_points) { for (let face of wrk_polygon.faces) { for (let edge of face) { res_polygon.edges.add(edge); } if ( /*(op === BOOLEAN_UNION || op == BOOLEAN_SUBTRACT) &&*/ int_points.find((ip) => ip.face === face) === void 0 ) { res_polygon.addFace(face.first, face.last); } } } function swapLinks(res_polygon, wrk_polygon, intersections) { if (intersections.int_points1.length === 0) return; for (let i4 = 0; i4 < intersections.int_points1.length; i4++) { let int_point1 = intersections.int_points1[i4]; let int_point2 = intersections.int_points2[i4]; if (int_point1.edge_before !== void 0 && int_point1.edge_after === void 0) { if (int_point2.edge_before === void 0 && int_point2.edge_after !== void 0) { int_point1.edge_before.next = int_point2.edge_after; int_point2.edge_after.prev = int_point1.edge_before; int_point1.edge_after = int_point2.edge_after; int_point2.edge_before = int_point1.edge_before; } } if (int_point2.edge_before !== void 0 && int_point2.edge_after === void 0) { if (int_point1.edge_before === void 0 && int_point1.edge_after !== void 0) { int_point2.edge_before.next = int_point1.edge_after; int_point1.edge_after.prev = int_point2.edge_before; int_point2.edge_after = int_point1.edge_after; int_point1.edge_before = int_point2.edge_before; } } if (int_point1.edge_before !== void 0 && int_point1.edge_after === void 0) { for (let int_point of intersections.int_points1_sorted) { if (int_point === int_point1) continue; if (int_point.edge_before === void 0 && int_point.edge_after !== void 0) { if (int_point.pt.equalTo(int_point1.pt)) { int_point1.edge_before.next = int_point.edge_after; int_point.edge_after.prev = int_point1.edge_before; int_point1.edge_after = int_point.edge_after; int_point.edge_before = int_point1.edge_before; } } } } if (int_point2.edge_before !== void 0 && int_point2.edge_after === void 0) { for (let int_point of intersections.int_points2_sorted) { if (int_point === int_point2) continue; if (int_point.edge_before === void 0 && int_point.edge_after !== void 0) { if (int_point.pt.equalTo(int_point2.pt)) { int_point2.edge_before.next = int_point.edge_after; int_point.edge_after.prev = int_point2.edge_before; int_point2.edge_after = int_point.edge_after; int_point.edge_before = int_point2.edge_before; } } } } } } function removeOldFaces(polygon2, int_points) { for (let int_point of int_points) { polygon2.faces.delete(int_point.face); int_point.face = void 0; if (int_point.edge_before) int_point.edge_before.face = void 0; if (int_point.edge_after) int_point.edge_after.face = void 0; } } function restoreFaces(polygon2, int_points, other_int_points) { for (let int_point of int_points) { if (int_point.edge_before === void 0 || int_point.edge_after === void 0) continue; if (int_point.face) continue; if (int_point.edge_after.face || int_point.edge_before.face) continue; let first = int_point.edge_after; let last = int_point.edge_before; try { LinkedList.testInfiniteLoop(first); } catch (error40) { throw Errors.CANNOT_COMPLETE_BOOLEAN_OPERATION; } let face = polygon2.addFace(first, last); for (let int_point_tmp of int_points) { if (int_point_tmp.edge_before && int_point_tmp.edge_after && int_point_tmp.edge_before.face === face && int_point_tmp.edge_after.face === face) { int_point_tmp.face = face; } } for (let int_point_tmp of other_int_points) { if (int_point_tmp.edge_before && int_point_tmp.edge_after && int_point_tmp.edge_before.face === face && int_point_tmp.edge_after.face === face) { int_point_tmp.face = face; } } } } function removeNotRelevantNotIntersectedFaces(polygon2, notIntersectedFaces, op, is_res_polygon) { for (let face of notIntersectedFaces) { let rel = face.first.bv; if (op === BOOLEAN_UNION && rel === INSIDE$1 || op === BOOLEAN_SUBTRACT && rel === INSIDE$1 && is_res_polygon || op === BOOLEAN_SUBTRACT && rel === OUTSIDE && !is_res_polygon || op === BOOLEAN_INTERSECT && rel === OUTSIDE) { polygon2.deleteFace(face); } } } function removeDetachedEdges(polygon2) { const detachedEdges = []; for (const edge of polygon2.edges) { if (!edge.face || !polygon2.faces.has(edge.face)) { detachedEdges.push(edge); } } for (const edge of detachedEdges) { polygon2.edges.delete(edge); } } var BooleanOperations = /* @__PURE__ */ Object.freeze({ __proto__: null, BOOLEAN_INTERSECT, BOOLEAN_SUBTRACT, BOOLEAN_UNION, calculateIntersections, innerClip, intersect: intersect$1, outerClip, removeNotRelevantChains, removeOldFaces, restoreFaces, subtract, unify }); var EQUAL = RegExp("T.F..FFF.|T.F...F.."); var INTERSECT = RegExp("T........|.T.......|...T.....|....T...."); var TOUCH = RegExp("FT.......|F..T.....|F...T...."); var INSIDE = RegExp("T.F..F..."); var COVERED = RegExp("T.F..F...|.TF..F...|..FT.F...|..F.TF..."); var DE9IM = class { /** * Create new instance of DE9IM matrix */ constructor() { this.m = new Array(9).fill(void 0); } /** * Get Interior To Interior intersection * @returns {Shape[] | undefined} */ get I2I() { return this.m[0]; } /** * Set Interior To Interior intersection * @param geom */ set I2I(geom) { this.m[0] = geom; } /** * Get Interior To Boundary intersection * @returns {Shape[] | undefined} */ get I2B() { return this.m[1]; } /** * Set Interior to Boundary intersection * @param geomc */ set I2B(geom) { this.m[1] = geom; } /** * Get Interior To Exterior intersection * @returns {Shape[] | undefined} */ get I2E() { return this.m[2]; } /** * Set Interior to Exterior intersection * @param geom */ set I2E(geom) { this.m[2] = geom; } /** * Get Boundary To Interior intersection * @returns {Shape[] | undefined} */ get B2I() { return this.m[3]; } /** * Set Boundary to Interior intersection * @param geom */ set B2I(geom) { this.m[3] = geom; } /** * Get Boundary To Boundary intersection * @returns {Shape[] | undefined} */ get B2B() { return this.m[4]; } /** * Set Boundary to Boundary intersection * @param geom */ set B2B(geom) { this.m[4] = geom; } /** * Get Boundary To Exterior intersection * @returns {Shape[] | undefined} */ get B2E() { return this.m[5]; } /** * Set Boundary to Exterior intersection * @param geom */ set B2E(geom) { this.m[5] = geom; } /** * Get Exterior To Interior intersection * @returns {Shape[] | undefined} */ get E2I() { return this.m[6]; } /** * Set Exterior to Interior intersection * @param geom */ set E2I(geom) { this.m[6] = geom; } /** * Get Exterior To Boundary intersection * @returns {Shape[] | undefined} */ get E2B() { return this.m[7]; } /** * Set Exterior to Boundary intersection * @param geom */ set E2B(geom) { this.m[7] = geom; } /** * Get Exterior to Exterior intersection * @returns {Shape[] | undefined} */ get E2E() { return this.m[8]; } /** * Set Exterior to Exterior intersection * @param geom */ set E2E(geom) { this.m[8] = geom; } /** * Return de9im matrix as string where
* - intersection is 'T'
* - not intersected is 'F'
* - not relevant is '*'
* For example, string 'FF**FF****' means 'DISJOINT' * @returns {string} */ toString() { return this.m.map((e5) => { if (e5 instanceof Array && e5.length > 0) { return "T"; } else if (e5 instanceof Array && e5.length === 0) { return "F"; } else { return "*"; } }).join(""); } equal() { return EQUAL.test(this.toString()); } intersect() { return INTERSECT.test(this.toString()); } touch() { return TOUCH.test(this.toString()); } inside() { return INSIDE.test(this.toString()); } covered() { return COVERED.test(this.toString()); } }; function ray_shoot(polygon2, point2) { let contains = void 0; let ray2 = new Flatten.Ray(point2); let line2 = new Flatten.Line(ray2.pt, ray2.norm); const searchBox = new Flatten.Box( ray2.box.xmin - Flatten.DP_TOL, ray2.box.ymin - Flatten.DP_TOL, ray2.box.xmax + Flatten.DP_TOL, ray2.box.ymax + Flatten.DP_TOL ); if (polygon2.box.not_intersect(searchBox)) { return Flatten.OUTSIDE; } let resp_edges = polygon2.edges.search(searchBox); if (resp_edges.length === 0) { return Flatten.OUTSIDE; } for (let edge of resp_edges) { if (edge.shape.contains(point2)) { return Flatten.BOUNDARY; } } let faces = [...polygon2.faces]; let intersections = []; for (let edge of resp_edges) { for (let ip of ray2.intersect(edge.shape)) { if (ip.equalTo(point2)) { return Flatten.BOUNDARY; } intersections.push({ pt: ip, edge, face_index: faces.indexOf(edge.face) }); } } intersections.sort((i1, i22) => { if (LT(i1.pt.x, i22.pt.x)) { return -1; } if (GT(i1.pt.x, i22.pt.x)) { return 1; } if (i1.face_index < i22.face_index) { return -1; } if (i1.face_index > i22.face_index) { return 1; } if (i1.edge.arc_length < i22.edge.arc_length) { return -1; } if (i1.edge.arc_length > i22.edge.arc_length) { return 1; } return 0; }); let counter = 0; for (let i4 = 0; i4 < intersections.length; i4++) { let intersection2 = intersections[i4]; if (intersection2.pt.equalTo(intersection2.edge.shape.start)) { if (i4 > 0 && intersection2.pt.equalTo(intersections[i4 - 1].pt) && intersection2.face_index === intersections[i4 - 1].face_index && intersection2.edge.prev === intersections[i4 - 1].edge) { continue; } let prev_edge = intersection2.edge.prev; while (EQ_0(prev_edge.length)) { prev_edge = prev_edge.prev; } let prev_tangent = prev_edge.shape.tangentInEnd(); let prev_point = intersection2.pt.translate(prev_tangent); let cur_tangent = intersection2.edge.shape.tangentInStart(); let cur_point = intersection2.pt.translate(cur_tangent); let prev_on_the_left = prev_point.leftTo(line2); let cur_on_the_left = cur_point.leftTo(line2); if (prev_on_the_left && !cur_on_the_left || !prev_on_the_left && cur_on_the_left) { counter++; } } else if (intersection2.pt.equalTo(intersection2.edge.shape.end)) { if (i4 > 0 && intersection2.pt.equalTo(intersections[i4 - 1].pt) && intersection2.face_index === intersections[i4 - 1].face_index && intersection2.edge.next === intersections[i4 - 1].edge) { continue; } let next_edge = intersection2.edge.next; while (EQ_0(next_edge.length)) { next_edge = next_edge.next; } let next_tangent = next_edge.shape.tangentInStart(); let next_point = intersection2.pt.translate(next_tangent); let cur_tangent = intersection2.edge.shape.tangentInEnd(); let cur_point = intersection2.pt.translate(cur_tangent); let next_on_the_left = next_point.leftTo(line2); let cur_on_the_left = cur_point.leftTo(line2); if (next_on_the_left && !cur_on_the_left || !next_on_the_left && cur_on_the_left) { counter++; } } else { if (intersection2.edge.shape instanceof Flatten.Segment) { counter++; } else { let box2 = intersection2.edge.shape.box; if (!(EQ(intersection2.pt.y, box2.ymin) || EQ(intersection2.pt.y, box2.ymax))) { counter++; } } } } contains = counter % 2 === 1 ? INSIDE$2 : OUTSIDE$1; return contains; } function equal(shape1, shape2) { return relate(shape1, shape2).equal(); } function intersect(shape1, shape2) { return relate(shape1, shape2).intersect(); } function touch(shape1, shape2) { return relate(shape1, shape2).touch(); } function disjoint(shape1, shape2) { return !intersect(shape1, shape2); } function inside(shape1, shape2) { return relate(shape1, shape2).inside(); } function covered(shape1, shape2) { return relate(shape1, shape2).covered(); } function contain(shape1, shape2) { return inside(shape2, shape1); } function cover(shape1, shape2) { return covered(shape2, shape1); } function relate(shape1, shape2) { if (shape1 instanceof Flatten.Line && shape2 instanceof Flatten.Line) { return relateLine2Line(shape1, shape2); } else if (shape1 instanceof Flatten.Line && shape2 instanceof Flatten.Circle) { return relateLine2Circle(shape1, shape2); } else if (shape1 instanceof Flatten.Line && shape2 instanceof Flatten.Box) { return relateLine2Box(shape1, shape2); } else if (shape1 instanceof Flatten.Line && shape2 instanceof Flatten.Polygon) { return relateLine2Polygon(shape1, shape2); } else if ((shape1 instanceof Flatten.Segment || shape1 instanceof Flatten.Arc) && shape2 instanceof Flatten.Polygon) { return relateShape2Polygon(shape1, shape2); } else if ((shape1 instanceof Flatten.Segment || shape1 instanceof Flatten.Arc) && (shape2 instanceof Flatten.Circle || shape2 instanceof Flatten.Box)) { return relateShape2Polygon(shape1, new Flatten.Polygon(shape2)); } else if (shape1 instanceof Flatten.Polygon && shape2 instanceof Flatten.Polygon) { return relatePolygon2Polygon(shape1, shape2); } else if ((shape1 instanceof Flatten.Circle || shape1 instanceof Flatten.Box) && (shape2 instanceof Flatten.Circle || shape2 instanceof Flatten.Box)) { return relatePolygon2Polygon(new Flatten.Polygon(shape1), new Flatten.Polygon(shape2)); } else if ((shape1 instanceof Flatten.Circle || shape1 instanceof Flatten.Box) && shape2 instanceof Flatten.Polygon) { return relatePolygon2Polygon(new Flatten.Polygon(shape1), shape2); } else if (shape1 instanceof Flatten.Polygon && (shape2 instanceof Flatten.Circle || shape2 instanceof Flatten.Box)) { return relatePolygon2Polygon(shape1, new Flatten.Polygon(shape2)); } } function relateLine2Line(line1, line2) { let denim = new DE9IM(); let ip = intersectLine2Line(line1, line2); if (ip.length === 0) { if (line1.contains(line2.pt) && line2.contains(line1.pt)) { denim.I2I = [line1]; denim.I2E = []; denim.E2I = []; } else { denim.I2I = []; denim.I2E = [line1]; denim.E2I = [line2]; } } else { denim.I2I = ip; denim.I2E = line1.split(ip); denim.E2I = line2.split(ip); } return denim; } function relateLine2Circle(line2, circle2) { let denim = new DE9IM(); let ip = intersectLine2Circle(line2, circle2); if (ip.length === 0) { denim.I2I = []; denim.I2B = []; denim.I2E = [line2]; denim.E2I = [circle2]; } else if (ip.length === 1) { denim.I2I = []; denim.I2B = ip; denim.I2E = line2.split(ip); denim.E2I = [circle2]; } else { let multiline2 = new Multiline$1([line2]); let ip_sorted = line2.sortPoints(ip); multiline2.split(ip_sorted); let splitShapes = multiline2.toShapes(); denim.I2I = [splitShapes[1]]; denim.I2B = ip_sorted; denim.I2E = [splitShapes[0], splitShapes[2]]; denim.E2I = new Flatten.Polygon([circle2.toArc()]).cutWithLine(line2); } return denim; } function relateLine2Box(line2, box2) { let denim = new DE9IM(); let ip = intersectLine2Box(line2, box2); if (ip.length === 0) { denim.I2I = []; denim.I2B = []; denim.I2E = [line2]; denim.E2I = [box2]; } else if (ip.length === 1) { denim.I2I = []; denim.I2B = ip; denim.I2E = line2.split(ip); denim.E2I = [box2]; } else { let multiline2 = new Multiline$1([line2]); let ip_sorted = line2.sortPoints(ip); multiline2.split(ip_sorted); let splitShapes = multiline2.toShapes(); if (box2.toSegments().some((segment2) => segment2.contains(ip[0]) && segment2.contains(ip[1]))) { denim.I2I = []; denim.I2B = [splitShapes[1]]; denim.I2E = [splitShapes[0], splitShapes[2]]; denim.E2I = [box2]; } else { denim.I2I = [splitShapes[1]]; denim.I2B = ip_sorted; denim.I2E = [splitShapes[0], splitShapes[2]]; denim.E2I = new Flatten.Polygon(box2.toSegments()).cutWithLine(line2); } } return denim; } function relateLine2Polygon(line2, polygon2) { let denim = new DE9IM(); let ip = intersectLine2Polygon(line2, polygon2); let multiline2 = new Multiline$1([line2]); let ip_sorted = ip.length > 0 ? ip.slice() : line2.sortPoints(ip); multiline2.split(ip_sorted); [...multiline2].forEach((edge) => edge.setInclusion(polygon2)); denim.I2I = [...multiline2].filter((edge) => edge.bv === Flatten.INSIDE).map((edge) => edge.shape); denim.I2B = [...multiline2].slice(1).map((edge) => edge.bv === Flatten.BOUNDARY ? edge.shape : edge.shape.start); denim.I2E = [...multiline2].filter((edge) => edge.bv === Flatten.OUTSIDE).map((edge) => edge.shape); denim.E2I = polygon2.cutWithLine(line2); return denim; } function relateShape2Polygon(shape, polygon2) { let denim = new DE9IM(); let ip = intersectShape2Polygon(shape, polygon2); let ip_sorted = ip.length > 0 ? ip.slice() : shape.sortPoints(ip); let multiline2 = new Multiline$1([shape]); multiline2.split(ip_sorted); [...multiline2].forEach((edge) => edge.setInclusion(polygon2)); denim.I2I = [...multiline2].filter((edge) => edge.bv === Flatten.INSIDE).map((edge) => edge.shape); denim.I2B = [...multiline2].slice(1).map((edge) => edge.bv === Flatten.BOUNDARY ? edge.shape : edge.shape.start); denim.I2E = [...multiline2].filter((edge) => edge.bv === Flatten.OUTSIDE).map((edge) => edge.shape); denim.B2I = []; denim.B2B = []; denim.B2E = []; for (let pt2 of [shape.start, shape.end]) { switch (ray_shoot(polygon2, pt2)) { case Flatten.INSIDE: denim.B2I.push(pt2); break; case Flatten.BOUNDARY: denim.B2B.push(pt2); break; case Flatten.OUTSIDE: denim.B2E.push(pt2); break; } } return denim; } function relatePolygon2Polygon(polygon1, polygon2) { let denim = new DE9IM(); let [ip_sorted1, ip_sorted2] = calculateIntersections(polygon1, polygon2); let boolean_intersection = intersect$1(polygon1, polygon2); let boolean_difference1 = subtract(polygon1, polygon2); let boolean_difference2 = subtract(polygon2, polygon1); let [inner_clip_shapes1, inner_clip_shapes2] = innerClip(polygon1, polygon2); let outer_clip_shapes1 = outerClip(polygon1, polygon2); let outer_clip_shapes2 = outerClip(polygon2, polygon1); denim.I2I = boolean_intersection.isEmpty() ? [] : [boolean_intersection]; denim.I2B = inner_clip_shapes2; denim.I2E = boolean_difference1.isEmpty() ? [] : [boolean_difference1]; denim.B2I = inner_clip_shapes1; denim.B2B = ip_sorted1; denim.B2E = outer_clip_shapes1; denim.E2I = boolean_difference2.isEmpty() ? [] : [boolean_difference2]; denim.E2B = outer_clip_shapes2; return denim; } var Relations = /* @__PURE__ */ Object.freeze({ __proto__: null, contain, cover, covered, disjoint, equal, inside, intersect, relate, touch }); var Matrix = class _Matrix { /** * Construct new instance of affine transformation matrix
* If parameters omitted, construct identity matrix a = 1, d = 1 * @param {number} a - position(0,0) sx*cos(alpha) * @param {number} c - position (1,0) -sy*sin(alpha) * @param {number} b - position (0,1) sx*sin(alpha) * @param {number} d - position (1,1) sy*cos(alpha) * @param {number} tx - position (2,0) translation by x * @param {number} ty - position (2,1) translation by y */ constructor(a3 = 1, b5 = 0, c2 = 0, d2 = 1, tx = 0, ty = 0) { this.a = a3; this.b = b5; this.c = c2; this.d = d2; this.tx = tx; this.ty = ty; } /** * Return new matrix from 3x3 affine transformation matrix * @param {AffineMatrix3x3} matrix3x3 * @returns {Matrix} */ fromMatrix3x3(matrix3x3) { const [a3, c2, tx] = matrix3x3[0]; const [b5, d2, ty] = matrix3x3[1]; return new _Matrix(a3, b5, c2, d2, tx, ty); } /** * Return 3x3 affine transformation matrix * @returns {AffineMatrix3x3} */ toMatrix3x3() { return [ [this.a, this.c, this.tx], [this.b, this.d, this.ty], [0, 0, 1] ]; } /** * Return new cloned instance of matrix * @return {Matrix} **/ clone() { return new _Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty); } /** * Transform vector [x,y] using transformation matrix.
* Vector [x,y] is an abstract array[2] of numbers and not a FlattenJS object
* The result is also an abstract vector [x',y'] = A * [x,y]: * * [x' [ ax + cy + tx * y' = bx + dy + ty * 1] 1 ] * * @param {number[]} vector - array[2] of numbers * @returns {number[]} transformation result - array[2] of numbers */ transform(vector2) { return [ vector2[0] * this.a + vector2[1] * this.c + this.tx, vector2[0] * this.b + vector2[1] * this.d + this.ty ]; } /** * Returns result of multiplication of this matrix by other matrix * @param {Matrix} other_matrix - matrix to multiply by * @returns {Matrix} */ multiply(other_matrix) { return new _Matrix( this.a * other_matrix.a + this.c * other_matrix.b, this.b * other_matrix.a + this.d * other_matrix.b, this.a * other_matrix.c + this.c * other_matrix.d, this.b * other_matrix.c + this.d * other_matrix.d, this.a * other_matrix.tx + this.c * other_matrix.ty + this.tx, this.b * other_matrix.tx + this.d * other_matrix.ty + this.ty ); } /** * Return new matrix as a result of multiplication of the current matrix * by the matrix(1,0,0,1,tx,ty) * @param {Vector} vector - Translation by vector or * @param {number} tx - translation by x-axis * @param {number} ty - translation by y-axis * @returns {Matrix} */ translate(...args) { let tx, ty; if (args.length == 1 && !isNaN(args[0].x) && !isNaN(args[0].y)) { tx = args[0].x; ty = args[0].y; } else if (args.length === 2 && typeof args[0] == "number" && typeof args[1] == "number") { tx = args[0]; ty = args[1]; } else { throw Errors.ILLEGAL_PARAMETERS; } return this.multiply(new _Matrix(1, 0, 0, 1, tx, ty)); } /** * Return new matrix as a result of multiplication of the current matrix * by the matrix that defines rotation by given angle (in radians) around * center of rotation (centerX,centerY) in counterclockwise direction * @param {number} angle - angle in radians * @param {number} centerX - center of rotation * @param {number} centerY - center of rotation * @returns {Matrix} */ rotate(angle, centerX = 0, centerY = 0) { let cos = Math.cos(angle); let sin = Math.sin(angle); return this.translate(centerX, centerY).multiply(new _Matrix(cos, sin, -sin, cos, 0, 0)).translate(-centerX, -centerY); } /** * Return new matrix as a result of multiplication of the current matrix * by the matrix (sx,0,0,sy,0,0) that defines scaling * @param {number} sx * @param {number} sy * @returns {Matrix} */ scale(sx, sy) { return this.multiply(new _Matrix(sx, 0, 0, sy, 0, 0)); } /** * Returns true if two matrix are equal parameter by parameter * @param {Matrix} matrix - other matrix * @returns {boolean} true if equal, false otherwise */ equalTo(matrix2) { if (!Flatten.Utils.EQ(this.tx, matrix2.tx)) return false; if (!Flatten.Utils.EQ(this.ty, matrix2.ty)) return false; if (!Flatten.Utils.EQ(this.a, matrix2.a)) return false; if (!Flatten.Utils.EQ(this.b, matrix2.b)) return false; if (!Flatten.Utils.EQ(this.c, matrix2.c)) return false; if (!Flatten.Utils.EQ(this.d, matrix2.d)) return false; return true; } }; Flatten.Matrix = Matrix; var matrix = (...args) => new Flatten.Matrix(...args); Flatten.matrix = matrix; var IntervalBase = class { constructor(low, high) { this.low = low; this.high = high; } get max() { return this.clone(); } // Default numeric/date comparison (lexicographic by low then high) less_than(other_interval) { return this.low < other_interval.low || this.low === other_interval.low && this.high < other_interval.high; } equal_to(other_interval) { return this.low === other_interval.low && this.high === other_interval.high; } intersect(other_interval) { return !this.not_intersect(other_interval); } not_intersect(other_interval) { return this.high < other_interval.low || other_interval.high < this.low; } merge(other_interval) { const low = this.low === void 0 ? other_interval.low : this.low < other_interval.low ? this.low : other_interval.low; const high = this.high === void 0 ? other_interval.high : this.high > other_interval.high ? this.high : other_interval.high; const cloned = this.clone(); cloned.low = low; cloned.high = high; return cloned; } output() { return [this.low, this.high]; } // Instance-level comparator so child classes can customize value comparison semantics comparable_less_than(val1, val2) { return val1 < val2; } }; var Interval = class _Interval extends IntervalBase { clone() { return new _Interval(this.low, this.high); } }; var RB_TREE_COLOR_RED = 1; var RB_TREE_COLOR_BLACK = 0; var Node = class { constructor(key, value, left = null, right = null, parent = null, color = RB_TREE_COLOR_BLACK) { this.left = left; this.right = right; this.parent = parent; this.color = color; this.item = { key: void 0, values: [] }; if (value !== void 0) { this.item.values.push(value); } if (key !== void 0) { if (Array.isArray(key)) { const [rawLow, rawHigh] = key; if (!Number.isNaN(rawLow) && !Number.isNaN(rawHigh)) { let low = rawLow; let high = rawHigh; if (low > high) [low, high] = [high, low]; this.item.key = new Interval(low, high); } } else { this.item.key = key; } } this.max = this.item.key ? this.item.key.max : void 0; } isNil() { return this.item.key === void 0 && this.item.values.length === 0 && this.left === null && this.right === null && this.color === RB_TREE_COLOR_BLACK; } requireKey() { if (!this.item.key) { throw new Error("Node key is undefined (nil/sentinel). Operation is not applicable."); } return this.item.key; } less_than(other_node) { const a3 = this.requireKey(); const b5 = other_node.requireKey(); return a3.less_than(b5); } _value_equal(other_node) { const a3 = this.item.values[0]; const b5 = other_node.item.values[0]; return a3 && b5 && a3.equal_to ? a3.equal_to(b5) : a3 === b5; } equal_to(other_node) { const a3 = this.requireKey(); const b5 = other_node.requireKey(); return a3.equal_to(b5); } intersect(other_node) { const a3 = this.requireKey(); const b5 = other_node.requireKey(); return a3.intersect(b5); } copy_data(other_node) { this.item.key = other_node.item.key; this.item.values = other_node.item.values.slice(); } update_max() { this.max = this.item.key ? this.item.key.max : void 0; if (this.right && this.right.max) { this.max = this.max ? this.max.merge(this.right.max) : this.right.max; } if (this.left && this.left.max) { this.max = this.max ? this.max.merge(this.left.max) : this.left.max; } } // Other_node does not intersect any node of left subtree not_intersect_left_subtree(search_node) { if (!this.left) return true; const high = this.left.max ? this.left.max.high : this.left.item.key.high; const selfKey = this.requireKey(); const searchKey = search_node.requireKey(); return selfKey.comparable_less_than(high, searchKey.low); } // Other_node does not intersect right subtree not_intersect_right_subtree(search_node) { if (!this.right) return true; const low = this.right.max ? this.right.max.low : this.right.item.key.low; const selfKey = this.requireKey(); const searchKey = search_node.requireKey(); return selfKey.comparable_less_than(searchKey.high, low); } }; var IntervalTree = class _IntervalTree { /** * Construct new empty instance of IntervalTree */ constructor() { this.root = null; this.nil_node = new Node(); } /** * Returns number of items stored in the interval tree * @returns {number} */ get size() { let count = 0; this.tree_walk(this.root, (node) => count += node.item.values.length); return count; } /** * Returns array of sorted keys in the ascending order * @returns {Array} */ get keys() { const res = []; this.tree_walk(this.root, (node) => res.push(node.item.key.output())); return res; } /** * Return array of values in the ascending keys order * @returns {Array} */ get values() { const res = []; this.tree_walk(this.root, (node) => { for (const v2 of node.item.values) res.push(v2); }); return res; } /** * Returns array of items ( pairs) in the ascended keys order * @returns {Array} */ get items() { const res = []; this.tree_walk(this.root, (node) => { const keyOut = node.item.key.output(); for (const v2 of node.item.values) { res.push({ key: keyOut, value: v2 }); } }); return res; } /** * Returns true if tree is empty * @returns {boolean} */ isEmpty() { return this.root == null || this.root === this.nil_node; } /** * Clear tree */ clear() { this.root = null; } /** * Insert new item into interval tree * @param key - interval object or array of two numbers [low, high] * @param value - value representing any object (optional) * @returns returns reference to inserted node */ insert(key, value = key) { if (key === void 0) return; const existing = this.tree_search(this.root, new Node(key)); if (existing) { existing.item.values.push(value); return existing; } const insert_node = new Node(key, value, this.nil_node, this.nil_node, null, RB_TREE_COLOR_RED); this.tree_insert(insert_node); this.recalc_max(insert_node); return insert_node; } /** * Returns true if item {key,value} exist in the tree * @param key - interval correspondent to keys stored in the tree * @param value - value object to be checked * @returns true if item {key, value} exist in the tree, false otherwise */ exist(key, value = key) { const node = this.tree_search(this.root, new Node(key)); if (!node) return false; if (arguments.length < 2 || value === key) return true; return node.item.values.some((v2) => v2 && v2.equal_to ? v2.equal_to(value) : v2 === value); } /** * Remove entry {key, value} from the tree * @param key - interval correspondent to keys stored in the tree * @param value - value object * @returns deleted node or undefined if not found */ remove(key, value = key) { const node = this.tree_search(this.root, new Node(key)); if (!node) return void 0; if (arguments.length < 2) { this.tree_delete(node); return node; } const idx = node.item.values.findIndex((v2) => v2 && v2.equal_to ? v2.equal_to(value) : v2 === value); if (idx >= 0) { node.item.values.splice(idx, 1); if (node.item.values.length === 0) { this.tree_delete(node); } return node; } return void 0; } search(interval, outputMapperFn = (value, key) => value === key ? key.output() : value) { const search_node = new Node(interval); const resp_nodes = []; this.tree_search_interval(this.root, search_node, resp_nodes); const res = []; for (const node of resp_nodes) { for (const v2 of node.item.values) { res.push(outputMapperFn(v2, node.item.key)); } } return res; } /** * Returns true if intersection between given and any interval stored in the tree found * @param interval - search interval or tuple [low, high] * @returns {boolean} */ intersect_any(interval) { const search_node = new Node(interval); return this.tree_find_any_interval(this.root, search_node); } /** * Tree visitor. For each node implement a callback function. * Method calls a callback function with two parameters (key, value) * @param visitor - function to be called for each tree item */ forEach(visitor) { this.tree_walk(this.root, (node) => { for (const v2 of node.item.values) visitor(node.item.key, v2); }); } /** * Value Mapper. Walk through every node and map node value to another value * @param callback - function to be called for each tree item */ map(callback) { const tree = new _IntervalTree(); this.tree_walk(this.root, (node) => { for (const v2 of node.item.values) { tree.insert(node.item.key, callback(v2, node.item.key)); } }); return tree; } *iterate(interval, outputMapperFn = (value, key) => value === key ? key.output() : value) { let node = null; if (interval) { node = this.tree_search_nearest_forward(this.root, new Node(interval)); } else if (this.root) { node = this.local_minimum(this.root); } while (node) { for (const v2 of node.item.values) { yield outputMapperFn(v2, node.item.key); } node = this.tree_successor(node); } } /** * Recalculate max property upward from given node to root * @param node - starting node */ recalc_max(node) { let node_current = node; while (node_current.parent != null) { node_current.parent.update_max(); node_current = node_current.parent; } } /** * Insert node into tree and rebalance * @param insert_node - node to insert */ tree_insert(insert_node) { let current_node = this.root; let parent_node = null; if (this.root == null || this.root === this.nil_node) { this.root = insert_node; } else { while (current_node !== this.nil_node) { parent_node = current_node; if (insert_node.less_than(current_node)) { current_node = current_node.left; } else { current_node = current_node.right; } } insert_node.parent = parent_node; if (insert_node.less_than(parent_node)) { parent_node.left = insert_node; } else { parent_node.right = insert_node; } } this.insert_fixup(insert_node); } /** * Restore red-black tree properties after insertion * @param insert_node - inserted node */ insert_fixup(insert_node) { let current_node; let uncle_node; current_node = insert_node; while (current_node !== this.root && current_node.parent.color === RB_TREE_COLOR_RED) { if (current_node.parent === current_node.parent.parent.left) { uncle_node = current_node.parent.parent.right; if (uncle_node.color === RB_TREE_COLOR_RED) { current_node.parent.color = RB_TREE_COLOR_BLACK; uncle_node.color = RB_TREE_COLOR_BLACK; current_node.parent.parent.color = RB_TREE_COLOR_RED; current_node = current_node.parent.parent; } else { if (current_node === current_node.parent.right) { current_node = current_node.parent; this.rotate_left(current_node); } current_node.parent.color = RB_TREE_COLOR_BLACK; current_node.parent.parent.color = RB_TREE_COLOR_RED; this.rotate_right(current_node.parent.parent); } } else { uncle_node = current_node.parent.parent.left; if (uncle_node.color === RB_TREE_COLOR_RED) { current_node.parent.color = RB_TREE_COLOR_BLACK; uncle_node.color = RB_TREE_COLOR_BLACK; current_node.parent.parent.color = RB_TREE_COLOR_RED; current_node = current_node.parent.parent; } else { if (current_node === current_node.parent.left) { current_node = current_node.parent; this.rotate_right(current_node); } current_node.parent.color = RB_TREE_COLOR_BLACK; current_node.parent.parent.color = RB_TREE_COLOR_RED; this.rotate_left(current_node.parent.parent); } } } this.root.color = RB_TREE_COLOR_BLACK; } /** * Delete node from tree and rebalance * @param delete_node - node to delete */ tree_delete(delete_node) { let cut_node; let fix_node; if (delete_node.left === this.nil_node || delete_node.right === this.nil_node) { cut_node = delete_node; } else { cut_node = this.tree_successor(delete_node); } if (cut_node.left !== this.nil_node) { fix_node = cut_node.left; } else { fix_node = cut_node.right; } fix_node.parent = cut_node.parent; if (cut_node === this.root) { this.root = fix_node; } else { if (cut_node === cut_node.parent.left) { cut_node.parent.left = fix_node; } else { cut_node.parent.right = fix_node; } cut_node.parent.update_max(); } this.recalc_max(fix_node); if (cut_node !== delete_node) { delete_node.copy_data(cut_node); delete_node.update_max(); this.recalc_max(delete_node); } if (cut_node.color === RB_TREE_COLOR_BLACK) { this.delete_fixup(fix_node); } } /** * Restore red-black tree properties after deletion * @param fix_node - node to fix from */ delete_fixup(fix_node) { let current_node = fix_node; let brother_node; while (current_node !== this.root && current_node.parent != null && current_node.color === RB_TREE_COLOR_BLACK) { if (current_node === current_node.parent.left) { brother_node = current_node.parent.right; if (brother_node.color === RB_TREE_COLOR_RED) { brother_node.color = RB_TREE_COLOR_BLACK; current_node.parent.color = RB_TREE_COLOR_RED; this.rotate_left(current_node.parent); brother_node = current_node.parent.right; } if (brother_node.left.color === RB_TREE_COLOR_BLACK && brother_node.right.color === RB_TREE_COLOR_BLACK) { brother_node.color = RB_TREE_COLOR_RED; current_node = current_node.parent; } else { if (brother_node.right.color === RB_TREE_COLOR_BLACK) { brother_node.color = RB_TREE_COLOR_RED; brother_node.left.color = RB_TREE_COLOR_BLACK; this.rotate_right(brother_node); brother_node = current_node.parent.right; } brother_node.color = current_node.parent.color; current_node.parent.color = RB_TREE_COLOR_BLACK; brother_node.right.color = RB_TREE_COLOR_BLACK; this.rotate_left(current_node.parent); current_node = this.root; } } else { brother_node = current_node.parent.left; if (brother_node.color === RB_TREE_COLOR_RED) { brother_node.color = RB_TREE_COLOR_BLACK; current_node.parent.color = RB_TREE_COLOR_RED; this.rotate_right(current_node.parent); brother_node = current_node.parent.left; } if (brother_node.left.color === RB_TREE_COLOR_BLACK && brother_node.right.color === RB_TREE_COLOR_BLACK) { brother_node.color = RB_TREE_COLOR_RED; current_node = current_node.parent; } else { if (brother_node.left.color === RB_TREE_COLOR_BLACK) { brother_node.color = RB_TREE_COLOR_RED; brother_node.right.color = RB_TREE_COLOR_BLACK; this.rotate_left(brother_node); brother_node = current_node.parent.left; } brother_node.color = current_node.parent.color; current_node.parent.color = RB_TREE_COLOR_BLACK; brother_node.left.color = RB_TREE_COLOR_BLACK; this.rotate_right(current_node.parent); current_node = this.root; } } } current_node.color = RB_TREE_COLOR_BLACK; } /** * Search for node with given key and value * @param node - starting node * @param search_node - node to search for * @returns found node or undefined */ tree_search(node, search_node) { if (node == null || node === this.nil_node) return void 0; if (search_node.equal_to(node)) { return node; } if (search_node.less_than(node)) { return this.tree_search(node.left, search_node); } else { return this.tree_search(node.right, search_node); } } /** * Find nearest forward node from given interval * @param node - starting node * @param search_node - search interval as node * @returns nearest forward node or null */ tree_search_nearest_forward(node, search_node) { let best = null; let curr = node; while (curr && curr !== this.nil_node) { if (curr.less_than(search_node)) { if (curr.intersect(search_node)) { best = curr; curr = curr.left; } else { curr = curr.right; } } else { if (!best || curr.less_than(best)) best = curr; curr = curr.left; } } return best || null; } /** * Search all intervals intersecting given interval * @param node - starting node * @param search_node - search interval as node * @param res - result array to collect found nodes */ tree_search_interval(node, search_node, res) { if (node != null && node !== this.nil_node) { if (node.left !== this.nil_node && !node.not_intersect_left_subtree(search_node)) { this.tree_search_interval(node.left, search_node, res); } if (node.intersect(search_node)) { res.push(node); } if (node.right !== this.nil_node && !node.not_intersect_right_subtree(search_node)) { this.tree_search_interval(node.right, search_node, res); } } } /** * Check if any interval intersects with given interval * @param node - starting node * @param search_node - search interval as node * @returns true if intersection found */ tree_find_any_interval(node, search_node) { let found = false; if (node != null && node !== this.nil_node) { if (node.left !== this.nil_node && !node.not_intersect_left_subtree(search_node)) { found = this.tree_find_any_interval(node.left, search_node); } if (!found) { found = node.intersect(search_node); } if (!found && node.right !== this.nil_node && !node.not_intersect_right_subtree(search_node)) { found = this.tree_find_any_interval(node.right, search_node); } } return found; } /** * Find node with minimum key in subtree * @param node - root of subtree * @returns node with minimum key */ local_minimum(node) { let node_min = node; while (node_min.left != null && node_min.left !== this.nil_node) { node_min = node_min.left; } return node_min; } /** * Find node with maximum key in subtree * @param node - root of subtree * @returns node with maximum key */ local_maximum(node) { let node_max = node; while (node_max.right != null && node_max.right !== this.nil_node) { node_max = node_max.right; } return node_max; } /** * Find successor node (next in sorted order) * @param node - current node * @returns successor node or null */ tree_successor(node) { let node_successor; let current_node; let parent_node; if (node.right !== this.nil_node) { node_successor = this.local_minimum(node.right); } else { current_node = node; parent_node = node.parent; while (parent_node != null && parent_node.right === current_node) { current_node = parent_node; parent_node = parent_node.parent; } node_successor = parent_node; } return node_successor; } /** * Left rotation around node x * @param x - node to rotate */ rotate_left(x4) { const y2 = x4.right; x4.right = y2.left; if (y2.left !== this.nil_node) { y2.left.parent = x4; } y2.parent = x4.parent; if (x4 === this.root) { this.root = y2; } else { if (x4 === x4.parent.left) { x4.parent.left = y2; } else { x4.parent.right = y2; } } y2.left = x4; x4.parent = y2; if (x4 !== null && x4 !== this.nil_node) { x4.update_max(); } if (y2 != null && y2 !== this.nil_node) { y2.update_max(); } } /** * Right rotation around node y * @param y - node to rotate */ rotate_right(y2) { const x4 = y2.left; y2.left = x4.right; if (x4.right !== this.nil_node) { x4.right.parent = y2; } x4.parent = y2.parent; if (y2 === this.root) { this.root = x4; } else { if (y2 === y2.parent.left) { y2.parent.left = x4; } else { y2.parent.right = x4; } } x4.right = y2; y2.parent = x4; if (y2 !== null && y2 !== this.nil_node) { y2.update_max(); } if (x4 != null && x4 !== this.nil_node) { x4.update_max(); } } /** * Performs in-order traversal of the tree * Applies action callback to each node in ascending order of keys * @param node - starting node for traversal (typically root) * @param action - callback function to be executed for each node */ tree_walk(node, action) { if (node != null && node !== this.nil_node) { this.tree_walk(node.left, action); action(node); this.tree_walk(node.right, action); } } /** * Test red-black tree property: all red nodes have exactly two black child nodes * @returns true if property holds */ testRedBlackProperty() { let res = true; this.tree_walk(this.root, function(node) { if (node.color === RB_TREE_COLOR_RED) { if (!(node.left.color === RB_TREE_COLOR_BLACK && node.right.color === RB_TREE_COLOR_BLACK)) { res = false; } } }); return res; } /** * Test red-black tree property: every path from root to leaf has same black height * @param node - starting node * @returns black height * @throws Error if property is violated */ testBlackHeightProperty(node) { let height = 0; let heightLeft = 0; let heightRight = 0; if (node.color === RB_TREE_COLOR_BLACK) { height++; } if (node.left !== this.nil_node) { heightLeft = this.testBlackHeightProperty(node.left); } else { heightLeft = 1; } if (node.right !== this.nil_node) { heightRight = this.testBlackHeightProperty(node.right); } else { heightRight = 1; } if (heightLeft !== heightRight) { throw new Error("Red-black height property violated"); } height += heightLeft; return height; } }; var PlanarSet = class extends Set { /** * Create new instance of PlanarSet * @param shapes - array or set of geometric objects to store in planar set * Each object should have a box property */ constructor(shapes) { super(shapes); this.index = new IntervalTree(); this.forEach((shape) => this.index.insert(shape)); } /** * Add new shape to planar set and to its spatial index.
* If shape already exist, it will not be added again. * This happens with no error, it is possible to use size property to check if * a shape was actually added.
* Method returns planar set object updated and may be chained * @param {AnyShape | {Box, AnyShape}} entry - shape to be added, should have valid box property * Another option to transfer as an object {key: Box, value: AnyShape} * @returns {PlanarSet} */ add(entry) { let size = this.size; const { key, value } = entry; const box2 = key || entry.box; const shape = value || entry; super.add(shape); if (this.size > size) { this.index.insert(box2, shape); } return this; } /** * Delete shape from planar set. Returns true if shape was actually deleted, false otherwise * @param {AnyShape | {Box, AnyShape}} entry - shape to be deleted * @returns {boolean} */ delete(entry) { const { key, value } = entry; const box2 = key || entry.box; const shape = value || entry; let deleted = super.delete(shape); if (deleted) { this.index.remove(box2, shape); } return deleted; } /** * Clear planar set */ clear() { super.clear(); this.index = new IntervalTree(); } /** * 2d range search in planar set.
* Returns array of all shapes in planar set which bounding box is intersected with query box * @param {Box} box - query box * @returns {AnyShape[]} */ search(box2) { let resp = this.index.search(box2); return resp; } /** * Point location test. Returns array of shapes which contains given point * @param {Point} point - query point * @returns {AnyShape[]} */ hit(point2) { let box2 = new Flatten.Box(point2.x - 1, point2.y - 1, point2.x + 1, point2.y + 1); let resp = this.index.search(box2); return resp.filter((shape) => point2.on(shape)); } /** * Returns svg string to draw all shapes in planar set * @returns {String} */ svg() { let svgcontent = [...this].reduce((acc, shape) => acc + shape.svg(), ""); return svgcontent; } }; Flatten.PlanarSet = PlanarSet; var Shape = class { get name() { throw Errors.CANNOT_INVOKE_ABSTRACT_METHOD; } get box() { throw Errors.CANNOT_INVOKE_ABSTRACT_METHOD; } clone() { throw Errors.CANNOT_INVOKE_ABSTRACT_METHOD; } /** * Returns new shape translated by given vector. * Translation vector may be also defined by a pair of numbers. * @param {Vector | (number, number) } args - Translation vector * or tuple of numbers * @returns {Shape} */ translate(...args) { return this.transform(new Matrix().translate(...args)); } /** * Returns new shape rotated by given angle around given center point. * If center point is omitted, rotates around zero point (0,0). * Positive value of angle defines rotation in counterclockwise direction, * negative angle defines rotation in clockwise direction * @param {number} angle - angle in radians * @param {Point} [center=(0,0)] center * @returns {Shape} */ rotate(angle, center = new Flatten.Point()) { return this.transform(new Matrix().rotate(angle, center.x, center.y)); } /** * Return new shape with coordinates multiplied by scaling factor * @param {number} sx - x-axis scaling factor * @param {number} sy - y-axis scaling factor * @returns {Shape} */ scale(sx, sy) { return this.transform(new Matrix().scale(sx, sy)); } transform(...args) { throw Errors.CANNOT_INVOKE_ABSTRACT_METHOD; } /** * This method returns an object that defines how data will be * serialized when called JSON.stringify() method * @returns {Object} */ toJSON() { return Object.assign({}, this, { name: this.name }); } svg(attrs = {}) { throw Errors.CANNOT_INVOKE_ABSTRACT_METHOD; } }; var Point$3 = class Point2 extends Shape { /** * Point may be constructed by two numbers, or by array of two numbers * @param {number} x - x-coordinate (float number) * @param {number} y - y-coordinate (float number) */ constructor(...args) { super(); this.x = 0; this.y = 0; if (args.length === 0) { return; } if (args.length === 1 && args[0] instanceof Array && args[0].length === 2) { let arr = args[0]; if (typeof arr[0] == "number" && typeof arr[1] == "number") { this.x = arr[0]; this.y = arr[1]; return; } } if (args.length === 1 && args[0] instanceof Object && args[0].name === "point") { let { x: x4, y: y2 } = args[0]; this.x = x4; this.y = y2; return; } if (args.length === 2) { if (typeof args[0] == "number" && typeof args[1] == "number") { this.x = args[0]; this.y = args[1]; return; } } throw Errors.ILLEGAL_PARAMETERS; } /** * Returns bounding box of a point * @returns {Box} */ get box() { return new Flatten.Box(this.x, this.y, this.x, this.y); } /** * Return new cloned instance of point * @returns {Point} */ clone() { return new Flatten.Point(this.x, this.y); } get vertices() { return [this.clone()]; } /** * Returns true if points are equal up to [Flatten.Utils.DP_TOL]{@link DP_TOL} tolerance * @param {Point} pt Query point * @returns {boolean} */ equalTo(pt2) { return Flatten.Utils.EQ(this.x, pt2.x) && Flatten.Utils.EQ(this.y, pt2.y); } /** * Defines predicate "less than" between points. Returns true if the point is less than query points, false otherwise
* By definition point1 < point2 if {point1.y < point2.y || point1.y == point2.y && point1.x < point2.x
* Numeric values compared with [Flatten.Utils.DP_TOL]{@link DP_TOL} tolerance * @param {Point} pt Query point * @returns {boolean} */ lessThan(pt2) { if (Flatten.Utils.LT(this.y, pt2.y)) return true; if (Flatten.Utils.EQ(this.y, pt2.y) && Flatten.Utils.LT(this.x, pt2.x)) return true; return false; } /** * Return new point transformed by affine transformation matrix * @param {Matrix} m - affine transformation matrix (a,b,c,d,tx,ty) * @returns {Point} */ transform(m3) { return new Flatten.Point(m3.transform([this.x, this.y])); } /** * Returns projection point on given line * @param {Line} line Line this point be projected on * @returns {Point} */ projectionOn(line2) { if (this.equalTo(line2.pt)) return this.clone(); let vec = new Flatten.Vector(this, line2.pt); if (Flatten.Utils.EQ_0(vec.cross(line2.norm))) return line2.pt.clone(); let dist = vec.dot(line2.norm); let proj_vec = line2.norm.multiply(dist); return this.translate(proj_vec); } /** * Returns true if point belongs to the "left" semi-plane, which means, point belongs to the same semi plane where line normal vector points to * Return false if point belongs to the "right" semi-plane or to the line itself * @param {Line} line Query line * @returns {boolean} */ leftTo(line2) { let vec = new Flatten.Vector(line2.pt, this); let onLeftSemiPlane = Flatten.Utils.GT(vec.dot(line2.norm), 0); return onLeftSemiPlane; } /** * Calculate distance and shortest segment from point to shape and return as array [distance, shortest segment] * @param {Shape} shape Shape of the one of supported types Point, Line, Circle, Segment, Arc, Polygon or Planar Set * @returns {number} distance from point to shape * @returns {Segment} shortest segment between point and shape (started at point, ended at shape) */ distanceTo(shape) { if (shape instanceof Point2) { let dx = shape.x - this.x; let dy = shape.y - this.y; return [Math.sqrt(dx * dx + dy * dy), new Flatten.Segment(this, shape)]; } if (shape instanceof Flatten.Line) { return Flatten.Distance.point2line(this, shape); } if (shape instanceof Flatten.Circle) { return Flatten.Distance.point2circle(this, shape); } if (shape instanceof Flatten.Segment) { return Flatten.Distance.point2segment(this, shape); } if (shape instanceof Flatten.Arc) { return Flatten.Distance.point2arc(this, shape); } if (shape instanceof Flatten.Polygon) { return Flatten.Distance.point2polygon(this, shape); } if (shape instanceof Flatten.PlanarSet) { return Flatten.Distance.shape2planarSet(this, shape); } if (shape instanceof Flatten.Multiline) { return Flatten.Distance.shape2multiline(this, shape); } } /** * Returns true if point is on a shape, false otherwise * @param {Shape} shape * @returns {boolean} */ on(shape) { if (shape instanceof Flatten.Point) { return this.equalTo(shape); } if (shape.contains && shape.contains instanceof Function) { return shape.contains(this); } throw Flatten.Errors.UNSUPPORTED_SHAPE_TYPE; } get name() { return "point"; } /** * Return string to draw point in svg as circle with radius "r"
* Accept any valid attributes of svg elements as svg object * Defaults attribues are:
* { * r:"3", * stroke:"black", * strokeWidth:"1", * fill:"red" * } * @param {Object} attrs - Any valid attributes of svg circle element, like "r", "stroke", "strokeWidth", "fill" * @returns {String} */ svg(attrs = {}) { const r4 = attrs.r ?? 3; return ` `; } }; Flatten.Point = Point$3; var point = (...args) => new Flatten.Point(...args); Flatten.point = point; var Vector$1 = class Vector extends Shape { /** * Vector may be constructed by two points, or by two float numbers, * or by array of two numbers or by segment * @param {Point} ps - start point * @param {Point} pe - end point */ constructor(...args) { super(); this.x = 0; this.y = 0; if (args.length === 0) { return; } if (args.length === 1 && args[0] instanceof Array && args[0].length === 2) { let arr = args[0]; if (typeof arr[0] == "number" && typeof arr[1] == "number") { this.x = arr[0]; this.y = arr[1]; return; } } if (args.length === 1 && args[0] instanceof Object && args[0].name === "vector") { let { x: x4, y: y2 } = args[0]; this.x = x4; this.y = y2; return; } if (args.length === 1 && args[0] instanceof Object && args[0].name === "segment") { let { start, end } = args[0]; this.x = end.x - start.x; this.y = end.y - start.y; return; } if (args.length === 2) { let a1 = args[0]; let a22 = args[1]; if (typeof a1 == "number" && typeof a22 == "number") { this.x = a1; this.y = a22; return; } if (a1 instanceof Flatten.Point && a22 instanceof Flatten.Point) { this.x = a22.x - a1.x; this.y = a22.y - a1.y; return; } } throw Errors.ILLEGAL_PARAMETERS; } /** * Method clone returns new instance of Vector * @returns {Vector} */ clone() { return new Flatten.Vector(this.x, this.y); } /** * Slope of the vector in radians from 0 to 2PI * @returns {number} */ get slope() { let angle = Math.atan2(this.y, this.x); if (angle < 0) angle = 2 * Math.PI + angle; return angle; } /** * Length of vector * @returns {number} */ get length() { return Math.sqrt(this.dot(this)); } /** * Returns true if the vector is zero length * @returns {boolean} */ isZeroLength() { return Flatten.Utils.EQ_0(this.length); } /** * Returns true if vectors are equal up to [DP_TOL]{@link http://localhost:63342/flatten-js/docs/global.html#DP_TOL} * tolerance * @param {Vector} v * @returns {boolean} */ equalTo(v2) { return Flatten.Utils.EQ(this.x, v2.x) && Flatten.Utils.EQ(this.y, v2.y); } /** * Returns new vector multiplied by scalar * @param {number} scalar * @returns {Vector} */ multiply(scalar) { return new Flatten.Vector(scalar * this.x, scalar * this.y); } /** * Returns scalar product (dot product) of two vectors
* dot_product = (this * v) * @param {Vector} v Other vector * @returns {number} */ dot(v2) { return this.x * v2.x + this.y * v2.y; } /** * Returns vector product (cross product) of two vectors
* cross_product = (this x v) * @param {Vector} v Other vector * @returns {number} */ cross(v2) { return this.x * v2.y - this.y * v2.x; } /** * Returns unit vector.
* Throw error if given vector has zero length * @returns {Vector} */ normalize() { if (this.isZeroLength()) { throw Errors.ZERO_DIVISION; } return new Flatten.Vector(this.x / this.length, this.y / this.length); } /** * Returns new vector rotated by given angle, * positive angle defines rotation in counterclockwise direction, * negative - in clockwise direction * Vector only can be rotated around (0,0) point! * @param {number} angle - Angle in radians * @param {Point} center - Center of rotation, default is (0,0) * @returns {Vector} */ rotate(angle, center = new Flatten.Point()) { if (center.x === 0 && center.y === 0) { return this.transform(new Matrix().rotate(angle)); } throw Errors.OPERATION_IS_NOT_SUPPORTED; } /** * Return new vector transformed by affine transformation matrix m * @param {Matrix} m - affine transformation matrix (a,b,c,d,tx,ty) * @returns {Vector} */ transform(m3) { return new Flatten.Vector(m3.transform([this.x, this.y])); } /** * Returns vector rotated 90 degrees counterclockwise * @returns {Vector} */ rotate90CCW() { return new Flatten.Vector(-this.y, this.x); } /** * Returns vector rotated 90 degrees clockwise * @returns {Vector} */ rotate90CW() { return new Flatten.Vector(this.y, -this.x); } /** * Return inverted vector * @returns {Vector} */ invert() { return new Flatten.Vector(-this.x, -this.y); } /** * Return result of addition of other vector to this vector as a new vector * @param {Vector} v Other vector * @returns {Vector} */ add(v2) { return new Flatten.Vector(this.x + v2.x, this.y + v2.y); } /** * Return result of subtraction of other vector from current vector as a new vector * @param {Vector} v Another vector * @returns {Vector} */ subtract(v2) { return new Flatten.Vector(this.x - v2.x, this.y - v2.y); } /** * Return angle between this vector and other vector.
* Angle is measured from 0 to 2*PI in the counterclockwise direction * from current vector to another. * @param {Vector} v Another vector * @returns {number} */ angleTo(v2) { let norm1 = this.normalize(); let norm2 = v2.normalize(); let angle = Math.atan2(norm1.cross(norm2), norm1.dot(norm2)); if (angle < 0) angle += 2 * Math.PI; return angle; } /** * Return vector projection of the current vector on another vector * @param {Vector} v Another vector * @returns {Vector} */ projectionOn(v2) { let n5 = v2.normalize(); let d2 = this.dot(n5); return n5.multiply(d2); } get name() { return "vector"; } }; Flatten.Vector = Vector$1; var vector$1 = (...args) => new Flatten.Vector(...args); Flatten.vector = vector$1; var Segment$1 = class Segment extends Shape { /** * * @param {Point} ps - start point * @param {Point} pe - end point */ constructor(...args) { super(); this.ps = new Flatten.Point(); this.pe = new Flatten.Point(); if (args.length === 0) { return; } if (args.length === 1 && args[0] instanceof Array && args[0].length === 4) { let coords = args[0]; this.ps = new Flatten.Point(coords[0], coords[1]); this.pe = new Flatten.Point(coords[2], coords[3]); return; } if (args.length === 1 && args[0] instanceof Object && args[0].name === "segment") { let { ps: ps2, pe } = args[0]; this.ps = new Flatten.Point(ps2.x, ps2.y); this.pe = new Flatten.Point(pe.x, pe.y); return; } if (args.length === 1 && args[0] instanceof Flatten.Point) { this.ps = args[0].clone(); return; } if (args.length === 2 && args[0] instanceof Flatten.Point && args[1] instanceof Flatten.Point) { this.ps = args[0].clone(); this.pe = args[1].clone(); return; } if (args.length === 4) { this.ps = new Flatten.Point(args[0], args[1]); this.pe = new Flatten.Point(args[2], args[3]); return; } throw Errors.ILLEGAL_PARAMETERS; } /** * Return new cloned instance of segment * @returns {Segment} */ clone() { return new Flatten.Segment(this.start, this.end); } /** * Start point * @returns {Point} */ get start() { return this.ps; } /** * End point * @returns {Point} */ get end() { return this.pe; } /** * Returns array of start and end point * @returns [Point,Point] */ get vertices() { return [this.ps.clone(), this.pe.clone()]; } /** * Length of a segment * @returns {number} */ get length() { return this.start.distanceTo(this.end)[0]; } /** * Slope of the line - angle to axe x in radians from 0 to 2PI * @returns {number} */ get slope() { let vec = new Flatten.Vector(this.start, this.end); return vec.slope; } /** * Bounding box * @returns {Box} */ get box() { return new Flatten.Box( Math.min(this.start.x, this.end.x), Math.min(this.start.y, this.end.y), Math.max(this.start.x, this.end.x), Math.max(this.start.y, this.end.y) ); } /** * Returns true if equals to query segment, false otherwise * @param {Segment} seg - query segment * @returns {boolean} */ equalTo(seg) { return this.ps.equalTo(seg.ps) && this.pe.equalTo(seg.pe); } /** * Returns true if segment contains point * @param {Point} pt Query point * @returns {boolean} */ contains(pt2) { return Flatten.Utils.EQ_0(this.distanceToPoint(pt2)); } /** * Returns array of intersection points between segment and other shape * @param {Shape} shape - Shape of the one of supported types
* @returns {Point[]} */ intersect(shape) { if (shape instanceof Flatten.Point) { return this.contains(shape) ? [shape] : []; } if (shape instanceof Flatten.Line) { return intersectSegment2Line(this, shape); } if (shape instanceof Flatten.Ray) { return intersectRay2Segment(shape, this); } if (shape instanceof Flatten.Segment) { return intersectSegment2Segment(this, shape); } if (shape instanceof Flatten.Circle) { return intersectSegment2Circle(this, shape); } if (shape instanceof Flatten.Box) { return intersectSegment2Box(this, shape); } if (shape instanceof Flatten.Arc) { return intersectSegment2Arc(this, shape); } if (shape instanceof Flatten.Polygon) { return intersectSegment2Polygon(this, shape); } if (shape instanceof Flatten.Multiline) { return intersectShape2Multiline(this, shape); } } /** * Calculate distance and shortest segment from segment to shape and return as array [distance, shortest segment] * @param {Shape} shape Shape of the one of supported types Point, Line, Circle, Segment, Arc, Polygon or Planar Set * @returns {[number, Segment]} shortest segment between segment and shape (started at segment, ended at shape) */ distanceTo(shape) { if (shape instanceof Flatten.Point) { let [dist, shortest_segment] = Flatten.Distance.point2segment(shape, this); shortest_segment = shortest_segment.reverse(); return [dist, shortest_segment]; } if (shape instanceof Flatten.Circle) { let [dist, shortest_segment] = Flatten.Distance.segment2circle(this, shape); return [dist, shortest_segment]; } if (shape instanceof Flatten.Line) { let [dist, shortest_segment] = Flatten.Distance.segment2line(this, shape); return [dist, shortest_segment]; } if (shape instanceof Flatten.Segment) { let [dist, shortest_segment] = Flatten.Distance.segment2segment(this, shape); return [dist, shortest_segment]; } if (shape instanceof Flatten.Arc) { let [dist, shortest_segment] = Flatten.Distance.segment2arc(this, shape); return [dist, shortest_segment]; } if (shape instanceof Flatten.Polygon) { let [dist, shortest_segment] = Flatten.Distance.shape2polygon(this, shape); return [dist, shortest_segment]; } if (shape instanceof Flatten.PlanarSet) { let [dist, shortest_segment] = Flatten.Distance.shape2planarSet(this, shape); return [dist, shortest_segment]; } if (shape instanceof Flatten.Multiline) { return Flatten.Distance.shape2multiline(this, shape); } } /** * Returns unit vector in the direction from start to end * @returns {Vector} */ tangentInStart() { let vec = new Flatten.Vector(this.start, this.end); return vec.normalize(); } /** * Return unit vector in the direction from end to start * @returns {Vector} */ tangentInEnd() { let vec = new Flatten.Vector(this.end, this.start); return vec.normalize(); } /** * Returns new segment with swapped start and end points * @returns {Segment} */ reverse() { return new Segment(this.end, this.start); } /** * When point belongs to segment, return array of two segments split by given point, * if point is inside segment. Returns clone of this segment if query point is incident * to start or end point of the segment. Returns empty array if point does not belong to segment * @param {Point} pt Query point * @returns {Segment[]} */ split(pt2) { if (this.start.equalTo(pt2)) return [null, this.clone()]; if (this.end.equalTo(pt2)) return [this.clone(), null]; return [ new Flatten.Segment(this.start, pt2), new Flatten.Segment(pt2, this.end) ]; } /** * Return middle point of the segment * @returns {Point} */ middle() { return new Flatten.Point((this.start.x + this.end.x) / 2, (this.start.y + this.end.y) / 2); } /** * Get point at given length * @param {number} length - The length along the segment * @returns {Point} */ pointAtLength(length) { if (length > this.length || length < 0) return null; if (length == 0) return this.start; if (length == this.length) return this.end; let factor = length / this.length; return new Flatten.Point( (this.end.x - this.start.x) * factor + this.start.x, (this.end.y - this.start.y) * factor + this.start.y ); } distanceToPoint(pt2) { let [dist, ...rest] = Flatten.Distance.point2segment(pt2, this); return dist; } definiteIntegral(ymin = 0) { let dx = this.end.x - this.start.x; let dy1 = this.start.y - ymin; let dy2 = this.end.y - ymin; return dx * (dy1 + dy2) / 2; } /** * Return new segment transformed using affine transformation matrix * @param {Matrix} matrix - affine transformation matrix * @returns {Segment} - transformed segment */ transform(matrix2 = new Flatten.Matrix()) { return new Segment(this.ps.transform(matrix2), this.pe.transform(matrix2)); } /** * Returns true if segment start is equal to segment end up to DP_TOL * @returns {boolean} */ isZeroLength() { return this.ps.equalTo(this.pe); } /** * Sort given array of points from segment start to end, assuming all points lay on the segment * @param {Point[]} - array of points * @returns {Point[]} new array sorted */ sortPoints(pts) { let line2 = new Flatten.Line(this.start, this.end); return line2.sortPoints(pts); } get name() { return "segment"; } /** * Return string to draw segment in svg * @param {Object} attrs - an object with attributes for svg path element, * like "stroke", "strokeWidth"
* Defaults are stroke:"black", strokeWidth:"1" * @returns {string} */ svg(attrs = {}) { return ` `; } }; Flatten.Segment = Segment$1; var segment = (...args) => new Flatten.Segment(...args); Flatten.segment = segment; var { vector } = Flatten; var Line$1 = class Line extends Shape { /** * Line may be constructed by point and normal vector or by two points that a line passes through * @param {Point} pt - point that a line passes through * @param {Vector|Point} norm - normal vector to a line or second point a line passes through */ constructor(...args) { super(); this.pt = new Flatten.Point(); this.norm = new Flatten.Vector(0, 1); if (args.length === 0) { return; } if (args.length === 1 && args[0] instanceof Object && args[0].name === "line") { let { pt: pt2, norm } = args[0]; this.pt = new Flatten.Point(pt2); this.norm = new Flatten.Vector(norm); return; } if (args.length === 2) { let a1 = args[0]; let a22 = args[1]; if (a1 instanceof Flatten.Point && a22 instanceof Flatten.Point) { this.pt = a1; this.norm = Line.points2norm(a1, a22); if (this.norm.dot(vector(this.pt.x, this.pt.y)) >= 0) { this.norm.invert(); } return; } if (a1 instanceof Flatten.Point && a22 instanceof Flatten.Vector) { if (Flatten.Utils.EQ_0(a22.x) && Flatten.Utils.EQ_0(a22.y)) { throw Errors.ILLEGAL_PARAMETERS; } this.pt = a1.clone(); this.norm = a22.clone(); this.norm = this.norm.normalize(); if (this.norm.dot(vector(this.pt.x, this.pt.y)) >= 0) { this.norm.invert(); } return; } if (a1 instanceof Flatten.Vector && a22 instanceof Flatten.Point) { if (Flatten.Utils.EQ_0(a1.x) && Flatten.Utils.EQ_0(a1.y)) { throw Errors.ILLEGAL_PARAMETERS; } this.pt = a22.clone(); this.norm = a1.clone(); this.norm = this.norm.normalize(); if (this.norm.dot(vector(this.pt.x, this.pt.y)) >= 0) { this.norm.invert(); } return; } } throw Errors.ILLEGAL_PARAMETERS; } /** * Return new cloned instance of line * @returns {Line} */ clone() { return new Flatten.Line(this.pt, this.norm); } /* The following methods need for implementation of Edge interface /** * Line has no start point * @returns {undefined} */ get start() { return void 0; } /** * Line has no end point */ get end() { return void 0; } /** * Return positive infinity number as length * @returns {number} */ get length() { return Number.POSITIVE_INFINITY; } /** * Returns infinite box * @returns {Box} */ get box() { return new Flatten.Box( Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY ); } /** * Middle point is undefined * @returns {undefined} */ get middle() { return void 0; } /** * Slope of the line - angle in radians between line and axe x from 0 to 2PI * @returns {number} - slope of the line */ get slope() { let vec = new Flatten.Vector(this.norm.y, -this.norm.x); return vec.slope; } /** * Get coefficients [A,B,C] of a standard line equation in the form Ax + By = C * @code [A, B, C] = line.standard * @returns {number[]} - array of coefficients */ get standard() { let A2 = this.norm.x; let B3 = this.norm.y; let C2 = this.norm.dot(vector(this.pt.x, this.pt.y)); return [A2, B3, C2]; } /** * Return true if parallel or incident to other line * @param {Line} other_line - line to check * @returns {boolean} */ parallelTo(other_line) { return Flatten.Utils.EQ_0(this.norm.cross(other_line.norm)); } /** * Returns true if incident to other line * @param {Line} other_line - line to check * @returns {boolean} */ incidentTo(other_line) { return this.parallelTo(other_line) && this.pt.on(other_line); } /** * Returns true if point belongs to line * @param {Point} pt Query point * @returns {boolean} */ contains(pt2) { if (this.pt.equalTo(pt2)) { return true; } let vec = new Flatten.Vector(this.pt, pt2); return Flatten.Utils.EQ_0(this.norm.dot(vec)); } /** * Return coordinate of the point that lies on the line in the transformed * coordinate system where center is the projection of the point(0,0) to * the line and axe y is collinear to the normal vector.
* This method assumes that point lies on the line and does not check it * @param {Point} pt - point on a line * @returns {number} */ coord(pt2) { return vector(pt2.x, pt2.y).cross(this.norm); } /** * Returns array of intersection points * @param {Shape} shape - shape to intersect with * @returns {Point[]} */ intersect(shape) { if (shape instanceof Flatten.Point) { return this.contains(shape) ? [shape] : []; } if (shape instanceof Flatten.Line) { return intersectLine2Line(this, shape); } if (shape instanceof Flatten.Ray) { return intersectRay2Line(shape, this); } if (shape instanceof Flatten.Circle) { return intersectLine2Circle(this, shape); } if (shape instanceof Flatten.Box) { return intersectLine2Box(this, shape); } if (shape instanceof Flatten.Segment) { return intersectSegment2Line(shape, this); } if (shape instanceof Flatten.Arc) { return intersectLine2Arc(this, shape); } if (shape instanceof Flatten.Polygon) { return intersectLine2Polygon(this, shape); } if (shape instanceof Flatten.Multiline) { return intersectShape2Multiline(this, shape); } } /** * Calculate distance and shortest segment from line to shape and returns array [distance, shortest_segment] * @param {Shape} shape Shape of the one of the types Point, Circle, Segment, Arc, Polygon * @returns {[number, Segment]} */ distanceTo(shape) { if (shape instanceof Flatten.Point) { let [distance, shortest_segment] = Flatten.Distance.point2line(shape, this); shortest_segment = shortest_segment.reverse(); return [distance, shortest_segment]; } if (shape instanceof Flatten.Circle) { let [distance, shortest_segment] = Flatten.Distance.circle2line(shape, this); shortest_segment = shortest_segment.reverse(); return [distance, shortest_segment]; } if (shape instanceof Flatten.Segment) { let [distance, shortest_segment] = Flatten.Distance.segment2line(shape, this); return [distance, shortest_segment.reverse()]; } if (shape instanceof Flatten.Arc) { let [distance, shortest_segment] = Flatten.Distance.arc2line(shape, this); return [distance, shortest_segment.reverse()]; } if (shape instanceof Flatten.Polygon) { let [distance, shortest_segment] = Flatten.Distance.shape2polygon(this, shape); return [distance, shortest_segment]; } } /** * Split line with a point or array of points and return array of shapes * Assumed (but not checked) that all points lay on the line * @param {Point | Point[]} pt * @returns {MultilineShapes} */ split(pt2) { if (pt2 instanceof Flatten.Point) { return [new Flatten.Ray(pt2, this.norm), new Flatten.Ray(pt2, this.norm)]; } else { let multiline2 = new Flatten.Multiline([this]); let sorted_points = this.sortPoints(pt2); multiline2.split(sorted_points); return multiline2.toShapes(); } } /** * Return new line rotated by angle * @param {number} angle - angle in radians * @param {Point} center - center of rotation */ rotate(angle, center = new Flatten.Point()) { return new Flatten.Line( this.pt.rotate(angle, center), this.norm.rotate(angle) ); } /** * Return new line transformed by affine transformation matrix * @param {Matrix} m - affine transformation matrix (a,b,c,d,tx,ty) * @returns {Line} */ transform(m3) { return new Flatten.Line( this.pt.transform(m3), this.norm.clone() ); } /** * Sort given array of points that lay on a line with respect to coordinate on a line * The method assumes that points lay on the line and does not check this * @param {Point[]} pts - array of points * @returns {Point[]} new array sorted */ sortPoints(pts) { return pts.slice().sort((pt1, pt2) => { if (this.coord(pt1) < this.coord(pt2)) { return -1; } if (this.coord(pt1) > this.coord(pt2)) { return 1; } return 0; }); } get name() { return "line"; } /** * Return string to draw svg segment representing line inside given box * @param {Box} box Box representing drawing area * @param {Object} attrs - an object with attributes of svg circle element */ svg(box2, attrs = {}) { let ip = intersectLine2Box(this, box2); if (ip.length === 0) return ""; let ps2 = ip[0]; let pe = ip.length === 2 ? ip[1] : ip.find((pt2) => !pt2.equalTo(ps2)); if (pe === void 0) pe = ps2; let segment2 = new Flatten.Segment(ps2, pe); return segment2.svg(attrs); } static points2norm(pt1, pt2) { if (pt1.equalTo(pt2)) { throw Errors.ILLEGAL_PARAMETERS; } let vec = new Flatten.Vector(pt1, pt2); let unit = vec.normalize(); return unit.rotate90CCW(); } }; Flatten.Line = Line$1; var line = (...args) => new Flatten.Line(...args); Flatten.line = line; var Circle$1 = class Circle extends Shape { /** * Class private property * @type {string} */ /** * * @param {Point} pc - circle center point * @param {number} r - circle radius */ constructor(...args) { super(); this.pc = new Flatten.Point(); this.r = 1; if (args.length === 1 && args[0] instanceof Object && args[0].name === "circle") { let { pc, r: r4 } = args[0]; this.pc = new Flatten.Point(pc); this.r = r4; } else { let [pc, r4] = [...args]; if (pc && pc instanceof Flatten.Point) this.pc = pc.clone(); if (r4 !== void 0) this.r = r4; } } /** * Return new cloned instance of circle * @returns {Circle} */ clone() { return new Flatten.Circle(this.pc.clone(), this.r); } /** * Circle center * @returns {Point} */ get center() { return this.pc; } /** * Circle bounding box * @returns {Box} */ get box() { return new Flatten.Box( this.pc.x - this.r, this.pc.y - this.r, this.pc.x + this.r, this.pc.y + this.r ); } /** * Return true if circle contains shape: no point of shape lies outside of the circle * @param {Shape} shape - test shape * @returns {boolean} */ contains(shape) { if (shape instanceof Flatten.Point) { return Flatten.Utils.LE(shape.distanceTo(this.center)[0], this.r); } if (shape instanceof Flatten.Segment) { return Flatten.Utils.LE(shape.start.distanceTo(this.center)[0], this.r) && Flatten.Utils.LE(shape.end.distanceTo(this.center)[0], this.r); } if (shape instanceof Flatten.Arc) { return this.intersect(shape).length === 0 && Flatten.Utils.LE(shape.start.distanceTo(this.center)[0], this.r) && Flatten.Utils.LE(shape.end.distanceTo(this.center)[0], this.r); } if (shape instanceof Flatten.Circle) { return this.intersect(shape).length === 0 && Flatten.Utils.LE(shape.r, this.r) && Flatten.Utils.LE(shape.center.distanceTo(this.center)[0], this.r); } } /** * Transform circle to closed arc * @param {boolean} counterclockwise * @returns {Arc} */ toArc(counterclockwise = true) { return new Flatten.Arc(this.center, this.r, Math.PI, -Math.PI, counterclockwise); } /** * Method scale is supported only for uniform scaling of the circle with (0,0) center * @param {number} sx * @param {number} sy * @returns {Circle} */ scale(sx, sy) { if (sx !== sy) throw Errors.OPERATION_IS_NOT_SUPPORTED; if (!(this.pc.x === 0 && this.pc.y === 0)) throw Errors.OPERATION_IS_NOT_SUPPORTED; return new Flatten.Circle(this.pc, this.r * sx); } /** * Return new circle transformed using affine transformation matrix * @param {Matrix} matrix - affine transformation matrix * @returns {Circle} */ transform(matrix2 = new Flatten.Matrix()) { return new Flatten.Circle(this.pc.transform(matrix2), this.r); } /** * Returns array of intersection points between circle and other shape * @param {Shape} shape Shape of the one of supported types * @returns {Point[]} */ intersect(shape) { if (shape instanceof Flatten.Point) { return this.contains(shape) ? [shape] : []; } if (shape instanceof Flatten.Line) { return intersectLine2Circle(shape, this); } if (shape instanceof Flatten.Ray) { return intersectRay2Circle(shape, this); } if (shape instanceof Flatten.Segment) { return intersectSegment2Circle(shape, this); } if (shape instanceof Flatten.Circle) { return intersectCircle2Circle(shape, this); } if (shape instanceof Flatten.Box) { return intersectCircle2Box(this, shape); } if (shape instanceof Flatten.Arc) { return intersectArc2Circle(shape, this); } if (shape instanceof Flatten.Polygon) { return intersectCircle2Polygon(this, shape); } if (shape instanceof Flatten.Multiline) { return intersectShape2Multiline(this, shape); } } /** * Calculate distance and shortest segment from circle to shape and return array [distance, shortest segment] * @param {Shape} shape Shape of the one of supported types Point, Line, Circle, Segment, Arc, Polygon or Planar Set * @returns {number} distance from circle to shape * @returns {Segment} shortest segment between circle and shape (started at circle, ended at shape) */ distanceTo(shape) { if (shape instanceof Flatten.Point) { let [distance, shortest_segment] = Flatten.Distance.point2circle(shape, this); shortest_segment = shortest_segment.reverse(); return [distance, shortest_segment]; } if (shape instanceof Flatten.Circle) { let [distance, shortest_segment] = Flatten.Distance.circle2circle(this, shape); return [distance, shortest_segment]; } if (shape instanceof Flatten.Line) { let [distance, shortest_segment] = Flatten.Distance.circle2line(this, shape); return [distance, shortest_segment]; } if (shape instanceof Flatten.Segment) { let [distance, shortest_segment] = Flatten.Distance.segment2circle(shape, this); shortest_segment = shortest_segment.reverse(); return [distance, shortest_segment]; } if (shape instanceof Flatten.Arc) { let [distance, shortest_segment] = Flatten.Distance.arc2circle(shape, this); shortest_segment = shortest_segment.reverse(); return [distance, shortest_segment]; } if (shape instanceof Flatten.Polygon) { let [distance, shortest_segment] = Flatten.Distance.shape2polygon(this, shape); return [distance, shortest_segment]; } if (shape instanceof Flatten.PlanarSet) { let [dist, shortest_segment] = Flatten.Distance.shape2planarSet(this, shape); return [dist, shortest_segment]; } if (shape instanceof Flatten.Multiline) { let [dist, shortest_segment] = Flatten.Distance.shape2multiline(this, shape); return [dist, shortest_segment]; } } get name() { return "circle"; } /** * Return string to draw circle in svg * @param {Object} attrs - an object with attributes of svg circle element * @returns {string} */ svg(attrs = {}) { return ` `; } }; Flatten.Circle = Circle$1; var circle = (...args) => new Flatten.Circle(...args); Flatten.circle = circle; var Arc = class extends Shape { /** * * @param {Point} pc - arc center * @param {number} r - arc radius * @param {number} startAngle - start angle in radians from 0 to 2*PI * @param {number} endAngle - end angle in radians from 0 to 2*PI * @param {boolean} counterClockwise - arc direction, true - clockwise, false - counterclockwise */ constructor(...args) { super(); this.pc = new Flatten.Point(); this.r = 1; this.startAngle = 0; this.endAngle = 2 * Math.PI; this.counterClockwise = true; if (args.length === 0) return; if (args.length === 1 && args[0] instanceof Object && args[0].name === "arc") { let { pc, r: r4, startAngle, endAngle, counterClockwise } = args[0]; this.pc = new Flatten.Point(pc.x, pc.y); this.r = r4; this.startAngle = startAngle; this.endAngle = endAngle; this.counterClockwise = counterClockwise; } else { let [pc, r4, startAngle, endAngle, counterClockwise] = [...args]; if (pc && pc instanceof Flatten.Point) this.pc = pc.clone(); if (r4 !== void 0) this.r = r4; if (startAngle !== void 0) this.startAngle = startAngle; if (endAngle !== void 0) this.endAngle = endAngle; if (counterClockwise !== void 0) this.counterClockwise = counterClockwise; } } /** * Return new cloned instance of arc * @returns {Arc} */ clone() { return new Flatten.Arc(this.pc.clone(), this.r, this.startAngle, this.endAngle, this.counterClockwise); } /** * Get sweep angle in radians. Sweep angle is non-negative number from 0 to 2*PI * @returns {number} */ get sweep() { let startAngle = this.startAngle; let endAngle = this.endAngle; if (Flatten.Utils.EQ(Math.abs(startAngle - endAngle), Flatten.PIx2)) { return Flatten.PIx2; } if (Math.abs(startAngle) > Flatten.PIx2) { startAngle -= Math.trunc(startAngle / Flatten.PIx2) * Flatten.PIx2; } if (startAngle < 0) { startAngle += Flatten.PIx2; } if (Math.abs(endAngle) > Flatten.PIx2) { endAngle -= Math.trunc(endAngle / Flatten.PIx2) * Flatten.PIx2; } if (endAngle < 0) { endAngle += Flatten.PIx2; } let sweep = this.counterClockwise ? endAngle - startAngle : startAngle - endAngle; if (sweep < 0) { sweep += Flatten.PIx2; } return sweep; } /** * Get start point of arc * @returns {Point} */ get start() { let p0 = new Flatten.Point(this.pc.x + this.r, this.pc.y); return p0.rotate(this.startAngle, this.pc); } /** * Get end point of arc * @returns {Point} */ get end() { let p0 = new Flatten.Point(this.pc.x + this.r, this.pc.y); return p0.rotate(this.endAngle, this.pc); } /** * Get center of arc * @returns {Point} */ get center() { return this.pc.clone(); } get vertices() { return [this.start.clone(), this.end.clone()]; } /** * Get arc length * @returns {number} */ get length() { return Math.abs(this.sweep * this.r); } /** * Get bounding box of the arc * @returns {Box} */ get box() { let func_arcs = this.breakToFunctional(); let box2 = func_arcs.reduce((acc, arc2) => acc.merge(arc2.start.box), new Flatten.Box()); box2 = box2.merge(this.end.box); return box2; } /** * Returns true if arc contains point, false otherwise * @param {Point} pt - point to test * @returns {boolean} */ contains(pt2) { if (!Flatten.Utils.EQ(this.pc.distanceTo(pt2)[0], this.r)) return false; if (pt2.equalTo(this.start)) return true; let angle = new Flatten.Vector(this.pc, pt2).slope; let test_arc = new Flatten.Arc(this.pc, this.r, this.startAngle, angle, this.counterClockwise); return Flatten.Utils.LE(test_arc.length, this.length); } /** * When given point belongs to arc, return array of two arcs split by this point. If points is incident * to start or end point of the arc, return clone of the arc. If point does not belong to the arcs, return * empty array. * @param {Point} pt Query point * @returns {Arc[]} */ split(pt2) { if (this.start.equalTo(pt2)) return [null, this.clone()]; if (this.end.equalTo(pt2)) return [this.clone(), null]; let angle = new Flatten.Vector(this.pc, pt2).slope; return [ new Flatten.Arc(this.pc, this.r, this.startAngle, angle, this.counterClockwise), new Flatten.Arc(this.pc, this.r, angle, this.endAngle, this.counterClockwise) ]; } /** * Return middle point of the arc * @returns {Point} */ middle() { let endAngle = this.counterClockwise ? this.startAngle + this.sweep / 2 : this.startAngle - this.sweep / 2; let arc2 = new Flatten.Arc(this.pc, this.r, this.startAngle, endAngle, this.counterClockwise); return arc2.end; } /** * Get point at given length * @param {number} length - The length along the arc * @returns {Point} */ pointAtLength(length) { if (length > this.length || length < 0) return null; if (length === 0) return this.start; if (length === this.length) return this.end; let factor = length / this.length; let endAngle = this.counterClockwise ? this.startAngle + this.sweep * factor : this.startAngle - this.sweep * factor; let arc2 = new Flatten.Arc(this.pc, this.r, this.startAngle, endAngle, this.counterClockwise); return arc2.end; } /** * Returns chord height ("sagitta") of the arc * @returns {number} */ chordHeight() { return (1 - Math.cos(Math.abs(this.sweep / 2))) * this.r; } /** * Returns array of intersection points between arc and other shape * @param {Shape} shape Shape of the one of supported types
* @returns {Point[]} */ intersect(shape) { if (shape instanceof Flatten.Point) { return this.contains(shape) ? [shape] : []; } if (shape instanceof Flatten.Line) { return intersectLine2Arc(shape, this); } if (shape instanceof Flatten.Ray) { return intersectRay2Arc(shape, this); } if (shape instanceof Flatten.Circle) { return intersectArc2Circle(this, shape); } if (shape instanceof Flatten.Segment) { return intersectSegment2Arc(shape, this); } if (shape instanceof Flatten.Box) { return intersectArc2Box(this, shape); } if (shape instanceof Flatten.Arc) { return intersectArc2Arc(this, shape); } if (shape instanceof Flatten.Polygon) { return intersectArc2Polygon(this, shape); } if (shape instanceof Flatten.Multiline) { return intersectShape2Multiline(this, shape); } } /** * Calculate distance and shortest segment from arc to shape and return array [distance, shortest segment] * @param {Shape} shape Shape of the one of supported types Point, Line, Circle, Segment, Arc, Polygon or Planar Set * @returns {number} distance from arc to shape * @returns {Segment} shortest segment between arc and shape (started at arc, ended at shape) */ distanceTo(shape) { if (shape instanceof Flatten.Point) { let [dist, shortest_segment] = Flatten.Distance.point2arc(shape, this); shortest_segment = shortest_segment.reverse(); return [dist, shortest_segment]; } if (shape instanceof Flatten.Circle) { let [dist, shortest_segment] = Flatten.Distance.arc2circle(this, shape); return [dist, shortest_segment]; } if (shape instanceof Flatten.Line) { let [dist, shortest_segment] = Flatten.Distance.arc2line(this, shape); return [dist, shortest_segment]; } if (shape instanceof Flatten.Segment) { let [dist, shortest_segment] = Flatten.Distance.segment2arc(shape, this); shortest_segment = shortest_segment.reverse(); return [dist, shortest_segment]; } if (shape instanceof Flatten.Arc) { let [dist, shortest_segment] = Flatten.Distance.arc2arc(this, shape); return [dist, shortest_segment]; } if (shape instanceof Flatten.Polygon) { let [dist, shortest_segment] = Flatten.Distance.shape2polygon(this, shape); return [dist, shortest_segment]; } if (shape instanceof Flatten.PlanarSet) { let [dist, shortest_segment] = Flatten.Distance.shape2planarSet(this, shape); return [dist, shortest_segment]; } if (shape instanceof Flatten.Multiline) { return Flatten.Distance.shape2multiline(this, shape); } } /** * Breaks arc in extreme point 0, pi/2, pi, 3*pi/2 and returns array of sub-arcs * @returns {Arc[]} */ breakToFunctional() { let func_arcs_array = []; let angles = [0, Math.PI / 2, Math.PI, 3 * Math.PI / 2]; let startAngle = this.startAngle; let endAngle = this.endAngle; if (Flatten.Utils.EQ(Math.abs(startAngle - endAngle), Flatten.PIx2)) { endAngle = startAngle; } if (Math.abs(startAngle) > Flatten.PIx2) { startAngle -= Math.trunc(startAngle / Flatten.PIx2) * Flatten.PIx2; } if (startAngle < 0) { startAngle += Flatten.PIx2; } if (Math.abs(endAngle) > Flatten.PIx2) { endAngle -= Math.trunc(endAngle / Flatten.PIx2) * Flatten.PIx2; } if (endAngle < 0) { endAngle += Flatten.PIx2; } let prev = startAngle; let next; let firstj; let d2; if (this.counterClockwise) { firstj = Math.ceil(startAngle / (Math.PI / 2)) % 4; d2 = 1; } else { firstj = Math.floor(startAngle / (Math.PI / 2)) % 4; d2 = -1; } for (let i4 = 0, j2 = firstj; i4 < 4; i4++, j2 = (j2 + d2 + 4) % 4) { next = angles[j2]; if (next === prev) { continue; } let incrementalSweep = this.counterClockwise ? next - startAngle : startAngle - next; if (incrementalSweep < 0) { incrementalSweep += Flatten.PIx2; } if (incrementalSweep > this.sweep) { break; } func_arcs_array.push(new Flatten.Arc(this.pc, this.r, prev, next, this.counterClockwise)); prev = next; } if (func_arcs_array.length === 0) { func_arcs_array.push(this); return func_arcs_array; } next = endAngle; if (prev !== next) { func_arcs_array.push(new Flatten.Arc(this.pc, this.r, prev, next, this.counterClockwise)); } return func_arcs_array; } /** * Return tangent unit vector in the start point in the direction from start to end * @returns {Vector} */ tangentInStart() { let vec = new Flatten.Vector(this.pc, this.start); let angle = this.counterClockwise ? Math.PI / 2 : -Math.PI / 2; return vec.rotate(angle).normalize(); } /** * Return tangent unit vector in the end point in the direction from end to start * @returns {Vector} */ tangentInEnd() { let vec = new Flatten.Vector(this.pc, this.end); let angle = this.counterClockwise ? -Math.PI / 2 : Math.PI / 2; return vec.rotate(angle).normalize(); } /** * Returns new arc with swapped start and end angles and reversed direction * @returns {Arc} */ reverse() { return new Flatten.Arc(this.pc, this.r, this.endAngle, this.startAngle, !this.counterClockwise); } /** * Return new arc transformed using affine transformation matrix
* @param {Matrix} matrix - affine transformation matrix * @returns {Arc} */ transform(matrix2 = new Flatten.Matrix()) { let newStart = this.start.transform(matrix2); let newEnd = this.end.transform(matrix2); let newCenter = this.pc.transform(matrix2); let newDirection = this.counterClockwise; if (matrix2.a * matrix2.d < 0) { newDirection = !newDirection; } return Flatten.Arc.arcSE(newCenter, newStart, newEnd, newDirection); } static arcSE(center, start, end, counterClockwise) { let { vector: vector2 } = Flatten; let startAngle = vector2(center, start).slope; let endAngle = vector2(center, end).slope; if (Flatten.Utils.EQ(startAngle, endAngle)) { endAngle += 2 * Math.PI; counterClockwise = true; } let r4 = vector2(center, start).length; return new Flatten.Arc(center, r4, startAngle, endAngle, counterClockwise); } definiteIntegral(ymin = 0) { let f_arcs = this.breakToFunctional(); let area = f_arcs.reduce((acc, arc2) => acc + arc2.circularSegmentDefiniteIntegral(ymin), 0); return area; } circularSegmentDefiniteIntegral(ymin) { let segment2 = new Flatten.Segment(this.start, this.end); let areaTrapez = segment2.definiteIntegral(ymin); let areaCircularSegment = Flatten.Utils.EQ(this.sweep, Flatten.PIx2) ? 0 : this.circularSegmentArea(); return this.counterClockwise ? areaTrapez - areaCircularSegment : areaTrapez + areaCircularSegment; } circularSegmentArea() { return 0.5 * this.r * this.r * (this.sweep - Math.sin(this.sweep)); } /** * Sort given array of points from arc start to end, assuming all points lay on the arc * @param {Point[]} pts array of points * @returns {Point[]} new array sorted */ sortPoints(pts) { let { vector: vector2 } = Flatten; return pts.slice().sort((pt1, pt2) => { let slope1 = vector2(this.pc, pt1).slope; let slope2 = vector2(this.pc, pt2).slope; if (slope1 < slope2) { return -1; } if (slope1 > slope2) { return 1; } return 0; }); } get name() { return "arc"; } /** * Return string to draw arc in svg * @param {Object} attrs - an object with attributes of svg path element * @returns {string} */ svg(attrs = {}) { let largeArcFlag = this.sweep <= Math.PI ? "0" : "1"; let sweepFlag = this.counterClockwise ? "1" : "0"; if (Flatten.Utils.EQ(this.sweep, 2 * Math.PI)) { let circle2 = new Flatten.Circle(this.pc, this.r); return circle2.svg(attrs); } else { return ` `; } } }; Flatten.Arc = Arc; var arc = (...args) => new Flatten.Arc(...args); Flatten.arc = arc; var Box = class _Box extends Shape { /** * * @param {number} xmin - minimal x coordinate * @param {number} ymin - minimal y coordinate * @param {number} xmax - maximal x coordinate * @param {number} ymax - maximal y coordinate */ constructor(xmin = void 0, ymin = void 0, xmax = void 0, ymax = void 0) { super(); this.xmin = xmin; this.ymin = ymin; this.xmax = xmax; this.ymax = ymax; } /** * Return new cloned instance of box * @returns {Box} */ clone() { return new _Box(this.xmin, this.ymin, this.xmax, this.ymax); } /** * Property low need for interval tree interface * @returns {Point} */ get low() { return new Flatten.Point(this.xmin, this.ymin); } /** * Property high need for interval tree interface * @returns {Point} */ get high() { return new Flatten.Point(this.xmax, this.ymax); } /** * Property max returns the box itself ! * @returns {Box} */ get max() { return this.clone(); } /** * Return center of the box * @returns {Point} */ get center() { return new Flatten.Point((this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2); } /** * Return the width of the box * @returns {number} */ get width() { return Math.abs(this.xmax - this.xmin); } /** * Return the height of the box * @returns {number} */ get height() { return Math.abs(this.ymax - this.ymin); } /** * Return property box like all other shapes * @returns {Box} */ get box() { return this.clone(); } /** * Returns true if not intersected with other box * @param {Box} other_box - other box to test * @returns {boolean} */ not_intersect(other_box) { return this.xmax < other_box.xmin || this.xmin > other_box.xmax || this.ymax < other_box.ymin || this.ymin > other_box.ymax; } /** * Returns true if intersected with other box * @param {Box} other_box - Query box * @returns {boolean} */ intersect(other_box) { return !this.not_intersect(other_box); } /** * Returns new box merged with other box * @param {Box} other_box - Other box to merge with * @returns {Box} */ merge(other_box) { return new _Box( this.xmin === void 0 ? other_box.xmin : Math.min(this.xmin, other_box.xmin), this.ymin === void 0 ? other_box.ymin : Math.min(this.ymin, other_box.ymin), this.xmax === void 0 ? other_box.xmax : Math.max(this.xmax, other_box.xmax), this.ymax === void 0 ? other_box.ymax : Math.max(this.ymax, other_box.ymax) ); } /** * Defines predicate "less than" between two boxes. Need for interval index * @param {Box} other_box - other box * @returns {boolean} - true if this box less than other box, false otherwise */ less_than(other_box) { if (this.low.lessThan(other_box.low)) return true; if (this.low.equalTo(other_box.low) && this.high.lessThan(other_box.high)) return true; return false; } /** * Returns true if this box is equal to other box, false otherwise * @param {Box} other_box - query box * @returns {boolean} */ equal_to(other_box) { return this.low.equalTo(other_box.low) && this.high.equalTo(other_box.high); } output() { return this.clone(); } comparable_less_than(pt1, pt2) { return pt1.lessThan(pt2); } /** * Set new values to the box object * @param {number} xmin - mininal x coordinate * @param {number} ymin - minimal y coordinate * @param {number} xmax - maximal x coordinate * @param {number} ymax - maximal y coordinate */ set(xmin, ymin, xmax, ymax) { this.xmin = xmin; this.ymin = ymin; this.xmax = xmax; this.ymax = ymax; } /** * Return new extended box * @param {number} extension - positive number, how much to extend the box * @returns {Box} */ extend(extension) { if (extension <= 0) return this.clone(); return new _Box( this.xmin - extension, this.ymin - extension, this.xmax + extension, this.ymax + extension ); } /** * Transform box into array of points from low left corner in counterclockwise * @returns {Point[]} */ toPoints() { return [ new Flatten.Point(this.xmin, this.ymin), new Flatten.Point(this.xmax, this.ymin), new Flatten.Point(this.xmax, this.ymax), new Flatten.Point(this.xmin, this.ymax) ]; } /** * Transform box into array of segments from low left corner in counterclockwise * @returns {Segment[]} */ toSegments() { let pts = this.toPoints(); return [ new Flatten.Segment(pts[0], pts[1]), new Flatten.Segment(pts[1], pts[2]), new Flatten.Segment(pts[2], pts[3]), new Flatten.Segment(pts[3], pts[0]) ]; } /** * Box rotation is not supported * Attempt to rotate box throws error * @param {number} angle - angle in radians * @param {Point} [center=(0,0)] center */ rotate(angle, center = new Flatten.Point()) { throw Errors.OPERATION_IS_NOT_SUPPORTED; } /** * Return new box transformed using affine transformation matrix * New box is a bounding box of transformed corner points * @param {Matrix} m - affine transformation matrix * @returns {Box} */ transform(m3 = new Flatten.Matrix()) { const transformed_points = this.toPoints().map((pt2) => pt2.transform(m3)); return transformed_points.reduce( (new_box, pt2) => new_box.merge(pt2.box), new _Box() ); } /** * Return true if box contains shape: no point of shape lies outside the box * @param {AnyShape} shape - test shape * @returns {boolean} */ contains(shape) { if (shape instanceof Flatten.Point) { return shape.x >= this.xmin && shape.x <= this.xmax && shape.y >= this.ymin && shape.y <= this.ymax; } if (shape instanceof Flatten.Segment) { return shape.vertices.every((vertex) => this.contains(vertex)); } if (shape instanceof Flatten.Box) { return shape.toSegments().every((segment2) => this.contains(segment2)); } if (shape instanceof Flatten.Circle) { return this.contains(shape.box); } if (shape instanceof Flatten.Arc) { return shape.vertices.every((vertex) => this.contains(vertex)) && this.toSegments().every((segment2) => intersectSegment2Arc(segment2, shape).length === 0); } if (shape instanceof Flatten.Line || shape instanceof Flatten.Ray) { return false; } if (shape instanceof Flatten.Multiline) { return shape.toShapes().every((shape2) => this.contains(shape2)); } if (shape instanceof Flatten.Polygon) { return this.contains(shape.box); } } /** * Calculate distance and shortest segment from box to shape and return as array [distance, shortest segment] * @param {Shape} shape Shape of the one of supported types Point, Line, Circle, Segment, Arc, Polygon or Planar Set * @returns {number} distance from box to shape * @returns {Segment} shortest segment between box and shape (started at box, ended at shape) */ distanceTo(shape) { const distanceInfos = this.toSegments().map((segment2) => segment2.distanceTo(shape)); let shortestDistanceInfo = [ Number.MAX_SAFE_INTEGER, null ]; distanceInfos.forEach((distanceInfo) => { if (distanceInfo[0] < shortestDistanceInfo[0]) { shortestDistanceInfo = distanceInfo; } }); return shortestDistanceInfo; } get name() { return "box"; } /** * Return string to draw box in svg * @param {Object} attrs - an object with attributes of svg rectangle element * @returns {string} */ svg(attrs = {}) { const width = this.xmax - this.xmin; const height = this.ymax - this.ymin; return ` `; } }; Flatten.Box = Box; var box = (...args) => new Flatten.Box(...args); Flatten.box = box; var Edge = class { /** * Construct new instance of edge * @param {Shape} shape Shape of type Segment or Arc */ constructor(shape) { this.shape = shape; this.next = void 0; this.prev = void 0; this.face = void 0; this.arc_length = 0; this.bvStart = void 0; this.bvEnd = void 0; this.bv = void 0; this.overlap = void 0; } /** * Get edge start point */ get start() { return this.shape.start; } /** * Get edge end point */ get end() { return this.shape.end; } /** * Get edge length */ get length() { return this.shape.length; } /** * Get bounding box of the edge * @returns {Box} */ get box() { return this.shape.box; } get isSegment() { return this.shape instanceof Flatten.Segment; } get isArc() { return this.shape instanceof Flatten.Arc; } get isLine() { return this.shape instanceof Flatten.Line; } get isRay() { return this.shape instanceof Flatten.Ray; } /** * Get middle point of the edge * @returns {Point} */ middle() { return this.shape.middle(); } /** * Get point at given length * @param {number} length - The length along the edge * @returns {Point} */ pointAtLength(length) { return this.shape.pointAtLength(length); } /** * Returns true if point belongs to the edge, false otherwise * @param {Point} pt - test point */ contains(pt2) { return this.shape.contains(pt2); } /** * Set inclusion flag of the edge with respect to another polygon * Inclusion flag is one of Flatten.INSIDE, Flatten.OUTSIDE, Flatten.BOUNDARY * @param polygon */ setInclusion(polygon2) { if (this.bv !== void 0) return this.bv; if (this.shape instanceof Flatten.Line || this.shape instanceof Flatten.Ray) { this.bv = Flatten.OUTSIDE; return this.bv; } if (this.bvStart === void 0) { this.bvStart = ray_shoot(polygon2, this.start); } if (this.bvEnd === void 0) { this.bvEnd = ray_shoot(polygon2, this.end); } if (this.bvStart === Flatten.OUTSIDE || this.bvEnd == Flatten.OUTSIDE) { this.bv = Flatten.OUTSIDE; } else if (this.bvStart === Flatten.INSIDE || this.bvEnd == Flatten.INSIDE) { this.bv = Flatten.INSIDE; } else { let bvMiddle = ray_shoot(polygon2, this.middle()); this.bv = bvMiddle; } return this.bv; } /** * Set overlapping between two coincident boundary edges * Overlapping flag is one of Flatten.OVERLAP_SAME or Flatten.OVERLAP_OPPOSITE * @param edge */ setOverlap(edge) { let flag = void 0; let shape1 = this.shape; let shape2 = edge.shape; if (shape1 instanceof Flatten.Segment && shape2 instanceof Flatten.Segment) { if (shape1.start.equalTo(shape2.start) && shape1.end.equalTo(shape2.end)) { flag = Flatten.OVERLAP_SAME; } else if (shape1.start.equalTo(shape2.end) && shape1.end.equalTo(shape2.start)) { flag = Flatten.OVERLAP_OPPOSITE; } } else if (shape1 instanceof Flatten.Arc && shape2 instanceof Flatten.Arc) { if (shape1.start.equalTo(shape2.start) && shape1.end.equalTo(shape2.end) && /*shape1.counterClockwise === shape2.counterClockwise &&*/ shape1.middle().equalTo(shape2.middle())) { flag = Flatten.OVERLAP_SAME; } else if (shape1.start.equalTo(shape2.end) && shape1.end.equalTo(shape2.start) && /*shape1.counterClockwise !== shape2.counterClockwise &&*/ shape1.middle().equalTo(shape2.middle())) { flag = Flatten.OVERLAP_OPPOSITE; } } else if (shape1 instanceof Flatten.Segment && shape2 instanceof Flatten.Arc || shape1 instanceof Flatten.Arc && shape2 instanceof Flatten.Segment) { if (shape1.start.equalTo(shape2.start) && shape1.end.equalTo(shape2.end) && shape1.middle().equalTo(shape2.middle())) { flag = Flatten.OVERLAP_SAME; } else if (shape1.start.equalTo(shape2.end) && shape1.end.equalTo(shape2.start) && shape1.middle().equalTo(shape2.middle())) { flag = Flatten.OVERLAP_OPPOSITE; } } if (this.overlap === void 0) this.overlap = flag; if (edge.overlap === void 0) edge.overlap = flag; } svg() { if (this.shape instanceof Flatten.Segment) { return ` L${this.shape.end.x},${this.shape.end.y}`; } else if (this.shape instanceof Flatten.Arc) { let arc2 = this.shape; let largeArcFlag; let sweepFlag = arc2.counterClockwise ? "1" : "0"; if (Flatten.Utils.EQ(arc2.sweep, 2 * Math.PI)) { let sign = arc2.counterClockwise ? 1 : -1; let halfArc1 = new Flatten.Arc(arc2.pc, arc2.r, arc2.startAngle, arc2.startAngle + sign * Math.PI, arc2.counterClockwise); let halfArc2 = new Flatten.Arc(arc2.pc, arc2.r, arc2.startAngle + sign * Math.PI, arc2.endAngle, arc2.counterClockwise); largeArcFlag = "0"; return ` A${halfArc1.r},${halfArc1.r} 0 ${largeArcFlag},${sweepFlag} ${halfArc1.end.x},${halfArc1.end.y} A${halfArc2.r},${halfArc2.r} 0 ${largeArcFlag},${sweepFlag} ${halfArc2.end.x},${halfArc2.end.y}`; } else { largeArcFlag = arc2.sweep <= Math.PI ? "0" : "1"; return ` A${arc2.r},${arc2.r} 0 ${largeArcFlag},${sweepFlag} ${arc2.end.x},${arc2.end.y}`; } } } toJSON() { return this.shape.toJSON(); } }; Flatten.Edge = Edge; var CircularLinkedList = class extends LinkedList { constructor(first, last) { super(first, last); this.setCircularLinks(); } setCircularLinks() { if (this.isEmpty()) return; this.last.next = this.first; this.first.prev = this.last; } [Symbol.iterator]() { let element = void 0; return { next: () => { let value = element ? element : this.first; let done = this.first ? element ? element === this.first : false : true; element = value ? value.next : void 0; return { value, done }; } }; } /** * Append new element to the end of the list * @param {LinkedListElement} element - new element to be appended * @returns {CircularLinkedList} */ append(element) { super.append(element); this.setCircularLinks(); return this; } /** * Insert new element to the list after elementBefore * @param {LinkedListElement} newElement - new element to be inserted * @param {LinkedListElement} elementBefore - element in the list to insert after it * @returns {CircularLinkedList} */ insert(newElement, elementBefore) { super.insert(newElement, elementBefore); this.setCircularLinks(); return this; } /** * Remove element from the list * @param {LinkedListElement} element - element to be removed from the list * @returns {CircularLinkedList} */ remove(element) { super.remove(element); return this; } }; var Face = class _Face extends CircularLinkedList { constructor(polygon2, ...args) { super(); this._box = void 0; this._orientation = void 0; if (args.length === 0) { return; } if (args.length === 1) { if (args[0] instanceof Array) { let shapes = args[0]; if (shapes.length === 0) return; if (shapes.every((shape) => { return shape instanceof Flatten.Point; })) { let segments = _Face.points2segments(shapes); this.shapes2face(polygon2.edges, segments); } else if (shapes.every((shape) => { return shape instanceof Array && shape.length === 2; })) { let points = shapes.map((shape) => new Flatten.Point(shape[0], shape[1])); let segments = _Face.points2segments(points); this.shapes2face(polygon2.edges, segments); } else if (shapes.every((shape) => { return shape instanceof Flatten.Segment || shape instanceof Flatten.Arc; })) { this.shapes2face(polygon2.edges, shapes); } else if (shapes.every((shape) => { return shape.name === "segment" || shape.name === "arc"; })) { let flattenShapes = []; for (let shape of shapes) { let flattenShape; if (shape.name === "segment") { flattenShape = new Flatten.Segment(shape); } else { flattenShape = new Flatten.Arc(shape); } flattenShapes.push(flattenShape); } this.shapes2face(polygon2.edges, flattenShapes); } } else if (args[0] instanceof _Face) { let face = args[0]; this.first = face.first; this.last = face.last; for (let edge of face) { polygon2.edges.add(edge); } } else if (args[0] instanceof Flatten.Circle) { this.shapes2face(polygon2.edges, [args[0].toArc(CCW)]); } else if (args[0] instanceof Flatten.Box) { let box2 = args[0]; this.shapes2face(polygon2.edges, [ new Flatten.Segment(new Flatten.Point(box2.xmin, box2.ymin), new Flatten.Point(box2.xmax, box2.ymin)), new Flatten.Segment(new Flatten.Point(box2.xmax, box2.ymin), new Flatten.Point(box2.xmax, box2.ymax)), new Flatten.Segment(new Flatten.Point(box2.xmax, box2.ymax), new Flatten.Point(box2.xmin, box2.ymax)), new Flatten.Segment(new Flatten.Point(box2.xmin, box2.ymax), new Flatten.Point(box2.xmin, box2.ymin)) ]); } } if (args.length === 2 && args[0] instanceof Flatten.Edge && args[1] instanceof Flatten.Edge) { this.first = args[0]; this.last = args[1]; this.last.next = this.first; this.first.prev = this.last; this.setArcLength(); } } /** * Return array of edges from first to last * @returns {PolygonEdge[]} */ get edges() { return this.toArray(); } /** * Return array of vertices from first to last * @returns {Point[]} */ get vertices() { return this.edges.map((edge) => edge.shape.start.clone()); } /** * Return array of shapes which comprise the face * @returns {Array} */ get shapes() { return this.edges.map((edge) => edge.shape.clone()); } /** * Return bounding box of the face * @returns {Box} */ get box() { if (this._box === void 0) { let box2 = new Flatten.Box(); for (let edge of this) { box2 = box2.merge(edge.box); } this._box = box2; } return this._box; } /** * Get all edges length * @returns {number} */ get perimeter() { return this.last.arc_length + this.last.length; } /** * Get point on face boundary at given length * @param {number} length - The length along the face boundary * @returns {Point} */ pointAtLength(length) { if (length > this.perimeter || length < 0) return null; let point2 = null; for (let edge of this) { if (length >= edge.arc_length && (edge === this.last || length < edge.next.arc_length)) { point2 = edge.pointAtLength(length - edge.arc_length); break; } } return point2; } static points2segments(points) { let segments = []; for (let i4 = 0; i4 < points.length; i4++) { if (points[i4].equalTo(points[(i4 + 1) % points.length])) continue; segments.push(new Flatten.Segment(points[i4], points[(i4 + 1) % points.length])); } return segments; } shapes2face(edges, shapes) { for (let shape of shapes) { let edge = new Flatten.Edge(shape); this.append(edge); edges.add(edge); } } /** * Append edge after the last edge of the face (and before the first edge).
* @param {Edge} edge - Edge to be appended to the linked list * @returns {Face} */ append(edge) { super.append(edge); this.setOneEdgeArcLength(edge); edge.face = this; return this; } /** * Insert edge newEdge into the linked list after the edge edgeBefore
* @param {Edge} newEdge - Edge to be inserted into linked list * @param {Edge} edgeBefore - Edge to insert newEdge after it * @returns {Face} */ insert(newEdge, edgeBefore) { super.insert(newEdge, edgeBefore); this.setOneEdgeArcLength(newEdge); newEdge.face = this; return this; } /** * Remove the given edge from the linked list of the face
* @param {Edge} edge - Edge to be removed * @returns {Face} */ remove(edge) { super.remove(edge); this.setArcLength(); return this; } /** * Merge current edge with the next edge. Given edge will be extended, * next edge after it will be removed. The distortion of the polygon * is on the responsibility of the user of this method * @param {Edge} edge - edge to be extended * @returns {Face} */ merge_with_next_edge(edge) { edge.shape.end.x = edge.next.shape.end.x; edge.shape.end.y = edge.next.shape.end.y; this.remove(edge.next); return this; } /** * Reverse orientation of the face: first edge become last and vice a verse, * all edges starts and ends swapped, direction of arcs inverted. If face was oriented * clockwise, it becomes counterclockwise and vice versa */ reverse() { let edges = []; let edge_tmp = this.last; do { edge_tmp.shape = edge_tmp.shape.reverse(); edges.push(edge_tmp); edge_tmp = edge_tmp.prev; } while (edge_tmp !== this.last); this.first = void 0; this.last = void 0; for (let edge of edges) { if (this.first === void 0) { edge.prev = edge; edge.next = edge; this.first = edge; this.last = edge; } else { edge.prev = this.last; this.last.next = edge; this.last = edge; this.last.next = this.first; this.first.prev = this.last; } this.setOneEdgeArcLength(edge); } if (this._orientation !== void 0) { this._orientation = void 0; this._orientation = this.orientation(); } } /** * Set arc_length property for each of the edges in the face. * Arc_length of the edge it the arc length from the first edge of the face */ setArcLength() { for (let edge of this) { this.setOneEdgeArcLength(edge); edge.face = this; } } setOneEdgeArcLength(edge) { if (edge === this.first) { edge.arc_length = 0; } else { edge.arc_length = edge.prev.arc_length + edge.prev.length; } } /** * Returns the absolute value of the area of the face * @returns {number} */ area() { return Math.abs(this.signedArea()); } /** * Returns signed area of the simple face. * Face is simple if it has no self intersections that change its orientation. * Then the area will be positive if the orientation of the face is clockwise, * and negative if orientation is counterclockwise. * It may be zero if polygon is degenerated. * @returns {number} */ signedArea() { let sArea = 0; let ymin = this.box.ymin; for (let edge of this) { sArea += edge.shape.definiteIntegral(ymin); } return sArea; } /** * Return face orientation: one of Flatten.ORIENTATION.CCW, Flatten.ORIENTATION.CW, Flatten.ORIENTATION.NOT_ORIENTABLE
* According to Green theorem the area of a closed curve may be calculated as double integral, * and the sign of the integral will be defined by the direction of the curve. * When the integral ("signed area") will be negative, direction is counterclockwise, * when positive - clockwise and when it is zero, polygon is not orientable. * See {@link https://mathinsight.org/greens_theorem_find_area} * @returns {number} */ orientation() { if (this._orientation === void 0) { let area = this.signedArea(); if (Flatten.Utils.EQ_0(area)) { this._orientation = ORIENTATION.NOT_ORIENTABLE; } else if (Flatten.Utils.LT(area, 0)) { this._orientation = ORIENTATION.CCW; } else { this._orientation = ORIENTATION.CW; } } return this._orientation; } /** * Returns true if face of the polygon is simple (no self-intersection points found) * NOTE: this method is incomplete because it does not exclude touching points. * Self intersection test should check if polygon change orientation in the test point. * @param {PlanarSet} edges - reference to polygon edges to provide search index * @returns {boolean} */ isSimple(edges) { let ip = _Face.getSelfIntersections(this, edges, true); return ip.length === 0; } static getSelfIntersections(face, edges, exitOnFirst = false) { let int_points = []; for (let edge1 of face) { let resp = edges.search(edge1.box); for (let edge2 of resp) { if (edge1 === edge2) continue; if (edge2.face !== face) continue; if (edge1.shape instanceof Flatten.Segment && edge2.shape instanceof Flatten.Segment && (edge1.next === edge2 || edge1.prev === edge2)) continue; let ip = edge1.shape.intersect(edge2.shape); for (let pt2 of ip) { if (pt2.equalTo(edge1.start) && pt2.equalTo(edge2.end) && edge2 === edge1.prev) continue; if (pt2.equalTo(edge1.end) && pt2.equalTo(edge2.start) && edge2 === edge1.next) continue; int_points.push(pt2); if (exitOnFirst) break; } if (int_points.length > 0 && exitOnFirst) break; } if (int_points.length > 0 && exitOnFirst) break; } return int_points; } /** * Returns edge which contains given point * @param {Point} pt - test point * @returns {Edge} */ findEdgeByPoint(pt2) { let edgeFound; for (let edge of this) { if (pt2.equalTo(edge.shape.start)) continue; if (pt2.equalTo(edge.shape.end) || edge.shape.contains(pt2)) { edgeFound = edge; break; } } return edgeFound; } /** * Returns new polygon created from one face * @returns {Polygon} */ toPolygon() { return new Flatten.Polygon(this.shapes); } toJSON() { return this.edges.map((edge) => edge.toJSON()); } /** * Returns string to be assigned to "d" attribute inside defined "path" * @returns {string} */ svg() { let svgStr = `M${this.first.start.x},${this.first.start.y}`; for (let edge of this) { svgStr += edge.svg(); } svgStr += ` z`; return svgStr; } }; Flatten.Face = Face; var Ray = class _Ray extends Shape { /** * Ray may be constructed by setting an origin point and a normal vector, so that any point x * on a ray fit an equation:
* (x - origin) * vector = 0
* Ray defined by constructor is a right semi-infinite line with respect to the normal vector
* If normal vector is omitted ray is considered horizontal (normal vector is (0,1)).
* Don't be confused: direction of the normal vector is orthogonal to the ray
* @param {Point} pt - start point * @param {Vector} norm - normal vector */ constructor(...args) { super(); this.pt = new Flatten.Point(); this.norm = new Flatten.Vector(0, 1); if (args.length === 0) { return; } if (args.length >= 1 && args[0] instanceof Flatten.Point) { this.pt = args[0].clone(); } if (args.length === 1) { return; } if (args.length === 2 && args[1] instanceof Flatten.Vector) { this.norm = args[1].clone(); return; } throw Errors.ILLEGAL_PARAMETERS; } /** * Return new cloned instance of ray * @returns {Ray} */ clone() { return new _Ray(this.pt, this.norm); } /** * Slope of the ray - angle in radians between ray and axe x from 0 to 2PI * @returns {number} - slope of the line */ get slope() { let vec = new Flatten.Vector(this.norm.y, -this.norm.x); return vec.slope; } /** * Returns half-infinite bounding box of the ray * @returns {Box} - bounding box */ get box() { let slope = this.slope; return new Flatten.Box( slope > Math.PI / 2 && slope < 3 * Math.PI / 2 ? Number.NEGATIVE_INFINITY : this.pt.x, slope >= 0 && slope <= Math.PI ? this.pt.y : Number.NEGATIVE_INFINITY, slope >= Math.PI / 2 && slope <= 3 * Math.PI / 2 ? this.pt.x : Number.POSITIVE_INFINITY, slope >= Math.PI && slope <= 2 * Math.PI || slope === 0 ? this.pt.y : Number.POSITIVE_INFINITY ); } /** * Return ray start point * @returns {Point} - ray start point */ get start() { return this.pt; } /** * Ray has no end point? * @returns {undefined} */ get end() { return void 0; } /** * Return positive infinity number as length * @returns {number} */ get length() { return Number.POSITIVE_INFINITY; } /** * Returns true if point belongs to ray * @param {Point} pt Query point * @returns {boolean} */ contains(pt2) { if (this.pt.equalTo(pt2)) { return true; } let vec = new Flatten.Vector(this.pt, pt2); return Flatten.Utils.EQ_0(this.norm.dot(vec)) && Flatten.Utils.GE(vec.cross(this.norm), 0); } /** * Return coordinate of the point that lies on the ray in the transformed * coordinate system where center is the projection of the point(0,0) to * the line containing this ray and axe y is collinear to the normal vector.
* This method assumes that point lies on the ray * @param {Point} pt - point on a ray * @returns {number} */ coord(pt2) { return vector$1(pt2.x, pt2.y).cross(this.norm); } /** * Split ray with point and return array of segment and new ray * @param {Point} pt * @returns [Segment,Ray] */ split(pt2) { if (!this.contains(pt2)) return []; if (this.pt.equalTo(pt2)) { return [this]; } return [ new Flatten.Segment(this.pt, pt2), new Flatten.Ray(pt2, this.norm) ]; } /** * Returns array of intersection points between ray and another shape * @param {Shape} shape - Shape to intersect with ray * @returns {Point[]} array of intersection points */ intersect(shape) { if (shape instanceof Flatten.Point) { return this.contains(shape) ? [shape] : []; } if (shape instanceof Flatten.Segment) { return intersectRay2Segment(this, shape); } if (shape instanceof Flatten.Arc) { return intersectRay2Arc(this, shape); } if (shape instanceof Flatten.Line) { return intersectRay2Line(this, shape); } if (shape instanceof Flatten.Ray) { return intersectRay2Ray(this, shape); } if (shape instanceof Flatten.Circle) { return intersectRay2Circle(this, shape); } if (shape instanceof Flatten.Box) { return intersectRay2Box(this, shape); } if (shape instanceof Flatten.Polygon) { return intersectRay2Polygon(this, shape); } if (shape instanceof Flatten.Multiline) { return intersectShape2Multiline(this, shape); } } /** * Return new line rotated by angle * @param {number} angle - angle in radians * @param {Point} center - center of rotation */ rotate(angle, center = new Flatten.Point()) { return new Flatten.Ray( this.pt.rotate(angle, center), this.norm.rotate(angle) ); } /** * Return new ray transformed by affine transformation matrix * @param {Matrix} m - affine transformation matrix (a,b,c,d,tx,ty) * @returns {Ray} */ transform(m3) { return new Flatten.Ray( this.pt.transform(m3), this.norm.clone() ); } get name() { return "ray"; } /** * Return string to draw svg segment representing ray inside given box * @param {Box} box Box representing drawing area * @param {Object} attrs - an object with attributes of svg segment element */ svg(box2, attrs = {}) { let line2 = new Flatten.Line(this.pt, this.norm); let ip = intersectLine2Box(line2, box2); ip = ip.filter((pt2) => this.contains(pt2)); if (ip.length === 0 || ip.length === 2) return ""; let segment2 = new Flatten.Segment(this.pt, ip[0]); return segment2.svg(attrs); } }; Flatten.Ray = Ray; var ray = (...args) => new Flatten.Ray(...args); Flatten.ray = ray; var Polygon$1 = class Polygon { /** * Constructor creates new instance of polygon. With no arguments new polygon is empty.
* Constructor accepts as argument array that define loop of shapes * or array of arrays in case of multi polygon
* Loop may be defined in different ways:
* - array of shapes of type Segment or Arc
* - array of points (Flatten.Point)
* - array of numeric pairs which represent points
* - box or circle object
* Alternatively, it is possible to use polygon.addFace method * @param {args} - array of shapes or array of arrays */ constructor() { this.faces = new Flatten.PlanarSet(); this.edges = new Flatten.PlanarSet(); let args = [...arguments]; if (args.length === 1 && (args[0] instanceof Array && args[0].length > 0 || args[0] instanceof Flatten.Circle || args[0] instanceof Flatten.Box)) { let argsArray = args[0]; if (args[0] instanceof Array && args[0].every((loop) => { return loop instanceof Array; })) { if (argsArray.every((el) => { return el instanceof Array && el.length === 2 && typeof el[0] === "number" && typeof el[1] === "number"; })) { this.faces.add(new Flatten.Face(this, argsArray)); } else { for (let loop of argsArray) { if (loop instanceof Array && loop[0] instanceof Array && loop[0].every((el) => { return el instanceof Array && el.length === 2 && typeof el[0] === "number" && typeof el[1] === "number"; })) { for (let loop1 of loop) { this.faces.add(new Flatten.Face(this, loop1)); } } else { this.faces.add(new Flatten.Face(this, loop)); } } } } else { this.faces.add(new Flatten.Face(this, argsArray)); } } } /** * (Getter) Returns bounding box of the polygon * @returns {Box} */ get box() { return [...this.faces].reduce((acc, face) => acc.merge(face.box), new Flatten.Box()); } /** * (Getter) Returns array of vertices * @returns {Array} */ get vertices() { return [...this.faces].flatMap((face) => face.vertices); } /** * Create new cloned instance of the polygon * @returns {Polygon} */ clone() { let polygon2 = new Polygon(); for (let face of this.faces) { polygon2.addFace(face.shapes); } return polygon2; } /** * Create a polygon from an array of polygons. Each polygon is an outer face with all containing inner faces * @param polygons * @returns {Polygon} */ createFromArray(polygons) { const newPolygon = new Polygon(); polygons.forEach((polygon2) => [...polygon2.faces].forEach((face) => newPolygon.addFace(face.shapes))); return newPolygon; } /** * Return true is polygon has no edges or faces * @returns {boolean} */ isEmpty() { return this.edges.size === 0 || this.faces.size === 0; } /** * Return true if polygon is valid for boolean operations * Polygon is valid if
* 1. All faces are simple polygons (there are no self-intersected polygons)
* 2. All faces are orientable and there is no island inside island or hole inside hole - TODO
* 3. There is no intersections between faces (excluding touching) - TODO
* @returns {boolean} */ isValid() { let valid = true; for (let face of this.faces) { if (!face.isSimple(this.edges)) { valid = false; break; } } return valid; } /** * Returns area of the polygon. Area of an island will be added, area of a hole will be subtracted * @returns {number} */ area() { let signedArea = [...this.faces].reduce((acc, face) => acc + face.signedArea(), 0); return Math.abs(signedArea); } /** * Add a new face to polygon. Returns added face * @param {Point[]|Segment[]|Arc[]|Circle|Box} args - new face may be create with one of the following ways:
* 1) array of points that describe closed path (edges are segments)
* 2) array of shapes (segments and arcs) which describe closed path
* 3) circle - will be added as counterclockwise arc
* 4) box - will be added as counterclockwise rectangle
* You can chain method face.reverse() is you need to change direction of the creates face * @returns {Face} */ addFace(...args) { let face = new Flatten.Face(this, ...args); this.faces.add(face); return face; } /** * Delete existing face from polygon * @param {Face} face Face to be deleted * @returns {boolean} */ deleteFace(face) { for (let edge of face) { this.edges.delete(edge); } return this.faces.delete(face); } /** * Clear all faces and create new faces from edges */ recreateFaces() { this.faces.clear(); for (let edge of this.edges) { edge.face = null; } let first; let unassignedEdgeFound = true; while (unassignedEdgeFound) { unassignedEdgeFound = false; for (let edge of this.edges) { if (edge.face === null) { first = edge; unassignedEdgeFound = true; break; } } if (unassignedEdgeFound) { let last = first; do { last = last.next; } while (last.next !== first); this.addFace(first, last); } } } /** * Delete chain of edges from the face. * @param {Face} face Face to remove chain * @param {Edge} edgeFrom Start of the chain of edges to be removed * @param {Edge} edgeTo End of the chain of edges to be removed */ removeChain(face, edgeFrom, edgeTo) { if (edgeTo.next === edgeFrom) { this.deleteFace(face); return; } for (let edge = edgeFrom; edge !== edgeTo.next; edge = edge.next) { face.remove(edge); this.edges.delete(edge); if (face.isEmpty()) { this.deleteFace(face); break; } } } /** * Add point as a new vertex and split edge. Point supposed to belong to an edge. * When edge is split, new edge created from the start of the edge to the new vertex * and inserted before current edge. * Current edge is trimmed and updated. * Method returns new edge added. If no edge added, it returns edge before vertex * @param {Point} pt Point to be added as a new vertex * @param {Edge} edge Edge to be split with new vertex and then trimmed from start * @returns {Edge} */ addVertex(pt2, edge) { let shapes = edge.shape.split(pt2); if (shapes[0] === null) return edge.prev; if (shapes[1] === null) return edge; let newEdge = new Flatten.Edge(shapes[0]); let edgeBefore = edge.prev; edge.face.insert(newEdge, edgeBefore); this.edges.delete(edge); this.edges.add(newEdge); edge.shape = shapes[1]; this.edges.add(edge); return newEdge; } /** * Merge given edge with next edge and remove vertex between them * @param {Edge} edge */ removeEndVertex(edge) { const edge_next = edge.next; if (edge_next === edge) return; edge.face.merge_with_next_edge(edge); this.edges.delete(edge_next); } /** * Cut polygon with multiline and return a new polygon * The cutting is done by intersection of multiline with edges of the polygon. * @param multiline * @returns {Polygon} */ cut(multiline2) { const polygons = this.splitToIslands(); const result = polygons.flatMap((polygon2) => polygon2._cutSingleIsland(multiline2)).filter((polygon2) => polygon2.isValid() && polygon2.isEmpty() === false); return this.createFromArray(result); } /** * Cut polygon with multiline and return a new polygon * @param {Multiline} multiline * @returns {Polygon} */ _cutSingleIsland(inputMultiline) { let newPoly = this.clone(); const multiline2 = inputMultiline.clone(); let intersections = { int_points1: [], int_points2: [], int_points1_sorted: [], int_points2_sorted: [] }; for (let edge1 of multiline2.edges) { for (let edge2 of newPoly.edges) { let ip = intersectEdge2Edge(edge1, edge2); for (let pt2 of ip) { addToIntPoints(edge1, pt2, intersections.int_points1); addToIntPoints(edge2, pt2, intersections.int_points2); } } } if (intersections.int_points1.length === 0) return newPoly; intersections.int_points1_sorted = getSortedArray(intersections.int_points1); intersections.int_points2_sorted = getSortedArray(intersections.int_points2); splitByIntersections(multiline2, intersections.int_points1_sorted); splitByIntersections(newPoly, intersections.int_points2_sorted); filterDuplicatedIntersections(intersections); intersections.int_points1_sorted = getSortedArray(intersections.int_points1); intersections.int_points2_sorted = getSortedArray(intersections.int_points2); initializeInclusionFlags(intersections.int_points1); calculateInclusionFlags(intersections.int_points1, newPoly); for (let int_point1 of intersections.int_points1_sorted) { if (int_point1.edge_before && int_point1.edge_after && int_point1.edge_before.bv === int_point1.edge_after.bv) { intersections.int_points2[int_point1.id] = -1; int_point1.id = -1; } } intersections.int_points1 = intersections.int_points1.filter((int_point) => int_point.id >= 0); intersections.int_points2 = intersections.int_points2.filter((int_point) => int_point.id >= 0); intersections.int_points1.forEach((int_point, index) => { int_point.id = index; }); intersections.int_points2.forEach((int_point, index) => { int_point.id = index; }); if (intersections.int_points1.length === 0) return newPoly; intersections.int_points1_sorted = getSortedArray(intersections.int_points1); intersections.int_points2_sorted = getSortedArray(intersections.int_points2); let int_point1_prev; let int_point1_curr; for (let i4 = 1; i4 < intersections.int_points1_sorted.length; i4++) { int_point1_curr = intersections.int_points1_sorted[i4]; int_point1_prev = intersections.int_points1_sorted[i4 - 1]; if (int_point1_curr.edge_before && int_point1_curr.edge_before.bv === INSIDE$2) { let edgeFrom = int_point1_prev.edge_after; let edgeTo = int_point1_curr.edge_before; let newEdges = multiline2.getChain(edgeFrom, edgeTo); insertBetweenIntPoints(intersections.int_points2[int_point1_prev.id], intersections.int_points2[int_point1_curr.id], newEdges); newEdges.forEach((edge) => newPoly.edges.add(edge)); newEdges = newEdges.reverse().map((edge) => new Flatten.Edge(edge.shape.reverse())); for (let k = 0; k < newEdges.length - 1; k++) { newEdges[k].next = newEdges[k + 1]; newEdges[k + 1].prev = newEdges[k]; } insertBetweenIntPoints(intersections.int_points2[int_point1_curr.id], intersections.int_points2[int_point1_prev.id], newEdges); newEdges.forEach((edge) => newPoly.edges.add(edge)); } } newPoly.recreateFaces(); return newPoly; } /** * A special case of cut() function * The return is a polygon cut with line * @param {Line} line - cutting line * @returns {Polygon} newPoly - resulted polygon */ cutWithLine(line2) { let multiline2 = new Multiline$1([line2]); return this.cut(multiline2); } /** * Returns the first found edge of polygon that contains given point * If point is a vertex, return the edge where the point is an end vertex, not a start one * @param {Point} pt * @returns {Edge} */ findEdgeByPoint(pt2) { let edge; for (let face of this.faces) { edge = face.findEdgeByPoint(pt2); if (edge !== void 0) break; } return edge; } /** * Split polygon into array of polygons, where each polygon is an outer face with all * containing inner faces * @returns {Flatten.Polygon[]} */ splitToIslands() { if (this.isEmpty()) return []; let polygons = this.toArray(); polygons.sort((polygon1, polygon2) => polygon2.area() - polygon1.area()); let orientation = [...polygons[0].faces][0].orientation(); let newPolygons = polygons.filter((polygon2) => [...polygon2.faces][0].orientation() === orientation); for (let polygon2 of polygons) { let face = [...polygon2.faces][0]; if (face.orientation() === orientation) continue; for (let islandPolygon of newPolygons) { if (face.shapes.every((shape) => islandPolygon.contains(shape))) { islandPolygon.addFace(face.shapes); break; } } } return newPolygons; } /** * Rearrange polygon to ensure that all outer faces go first and all inner faces (holes) go after * @returns {Polygon} */ rearrange() { if (this.faces.size <= 1) return this.clone(); const islands = this.splitToIslands(); const newPolygon = new Polygon(); islands.forEach((island) => { island.faces.forEach((face) => newPolygon.addFace(face.shapes)); }); return newPolygon; } /** * Helper method to get orientation of the polygon as the first face orientation * Assume that polygon is properly arranged and the first face is the outer face * @returns {Flatten.ORIENTATION.PolygonOrientationType} */ orientation() { if (this.isEmpty()) return ORIENTATION.NOT_ORIENTABLE; return [...this.faces][0].orientation(); } /** * Helper method to check if face is outer face of the polygon * @param face * @returns {boolean} */ isOuter(face) { return face.orientation() === this.orientation(); } /** * Helper method to check if a polygon is a multi-polygon (has more than one outer face) * @returns {boolean} */ isMultiPolygon() { let outerCounter = 0; this.faces.forEach((face) => { if (this.isOuter(face)) outerCounter++; }); return outerCounter > 1; } /** * Reverse orientation of all faces to opposite * @returns {Polygon} */ reverse() { for (let face of this.faces) { face.reverse(); } return this; } /** * Returns true if polygon contains shape: no point of shape lay outside of the polygon, * false otherwise * @param {Shape} shape - test shape * @returns {boolean} */ contains(shape) { if (shape instanceof Flatten.Point) { let rel = ray_shoot(this, shape); return rel === INSIDE$2 || rel === BOUNDARY$1; } else { return cover(this, shape); } } /** * Return distance and shortest segment between polygon and other shape as array [distance, shortest_segment] * @param {Shape} shape Shape of one of the types Point, Circle, Line, Segment, Arc or Polygon * @returns {Number | Segment} */ distanceTo(shape) { if (shape instanceof Flatten.Point) { let [dist, shortest_segment] = Flatten.Distance.point2polygon(shape, this); shortest_segment = shortest_segment.reverse(); return [dist, shortest_segment]; } if (shape instanceof Flatten.Circle || shape instanceof Flatten.Line || shape instanceof Flatten.Segment || shape instanceof Flatten.Arc) { let [dist, shortest_segment] = Flatten.Distance.shape2polygon(shape, this); shortest_segment = shortest_segment.reverse(); return [dist, shortest_segment]; } if (shape instanceof Flatten.Polygon) { let min_dist_and_segment = [Number.POSITIVE_INFINITY, new Flatten.Segment()]; let dist, shortest_segment; for (let edge of this.edges) { let min_stop = min_dist_and_segment[0]; [dist, shortest_segment] = Flatten.Distance.shape2planarSet(edge.shape, shape.edges, min_stop); if (Flatten.Utils.LT(dist, min_stop)) { min_dist_and_segment = [dist, shortest_segment]; } } return min_dist_and_segment; } } /** * Return array of intersection points between polygon and other shape * @param shape Shape of the one of supported types
* @returns {Point[]} */ intersect(shape) { if (shape instanceof Flatten.Point) { return this.contains(shape) ? [shape] : []; } if (shape instanceof Flatten.Line) { return intersectLine2Polygon(shape, this); } if (shape instanceof Flatten.Ray) { return intersectRay2Polygon(shape, this); } if (shape instanceof Flatten.Circle) { return intersectCircle2Polygon(shape, this); } if (shape instanceof Flatten.Segment) { return intersectSegment2Polygon(shape, this); } if (shape instanceof Flatten.Arc) { return intersectArc2Polygon(shape, this); } if (shape instanceof Flatten.Polygon) { return intersectPolygon2Polygon(shape, this); } if (shape instanceof Flatten.Multiline) { return intersectMultiline2Polygon(shape, this); } } /** * Returns new polygon translated by vector vec * @param {Vector} vec * @returns {Polygon} */ translate(vec) { let newPolygon = new Polygon(); for (let face of this.faces) { newPolygon.addFace(face.shapes.map((shape) => shape.translate(vec))); } return newPolygon; } /** * Return new polygon rotated by given angle around given point * If point omitted, rotate around origin (0,0) * Positive value of angle defines rotation counterclockwise, negative - clockwise * @param {number} angle - rotation angle in radians * @param {Point} center - rotation center, default is (0,0) * @returns {Polygon} - new rotated polygon */ rotate(angle = 0, center = new Flatten.Point()) { let newPolygon = new Polygon(); for (let face of this.faces) { newPolygon.addFace(face.shapes.map((shape) => shape.rotate(angle, center))); } return newPolygon; } /** * Return new polygon with coordinates multiplied by scaling factor * @param {number} sx - x-axis scaling factor * @param {number} sy - y-axis scaling factor * @returns {Polygon} */ scale(sx, sy) { let newPolygon = new Polygon(); for (let face of this.faces) { newPolygon.addFace(face.shapes.map((shape) => shape.scale(sx, sy))); } return newPolygon; } /** * Return new polygon transformed using affine transformation matrix * @param {Matrix} matrix - affine transformation matrix * @returns {Polygon} - new polygon */ transform(matrix2 = new Flatten.Matrix()) { let newPolygon = new Polygon(); for (let face of this.faces) { newPolygon.addFace(face.shapes.map((shape) => shape.transform(matrix2))); } return newPolygon; } /** * This method returns an object that defines how data will be * serialized when called JSON.stringify() method * @returns {Object} */ toJSON() { return [...this.faces].map((face) => face.toJSON()); } /** * Transform all faces into array of polygons * @returns {Flatten.Polygon[]} */ toArray() { return [...this.faces].map((face) => face.toPolygon()); } /** * Return string to be assigned to 'd' attribute of element * @returns {string} */ dpath() { return [...this.faces].reduce((acc, face) => acc + face.svg(), ""); } /** * Return string to draw polygon in svg * @param attrs - an object with attributes for svg path element * @returns {string} */ svg(attrs = {}) { let svgStr = ` `; return svgStr; } }; Flatten.Polygon = Polygon$1; var polygon = (...args) => new Flatten.Polygon(...args); Flatten.polygon = polygon; var { Circle: Circle2, Line: Line2, Point: Point$2, Vector: Vector2, Utils } = Flatten; var Inversion = class _Inversion { /** * Inversion constructor * @param {Circle} inversion_circle inversion circle */ constructor(inversion_circle) { this.circle = inversion_circle; } get inversion_circle() { return this.circle; } static inversePoint(inversion_circle, point2) { const v2 = new Vector2(inversion_circle.pc, point2); const k2 = inversion_circle.r * inversion_circle.r; const len2 = v2.dot(v2); const reflected_point = Utils.EQ_0(len2) ? new Point$2(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY) : inversion_circle.pc.translate(v2.multiply(k2 / len2)); return reflected_point; } static inverseCircle(inversion_circle, circle2) { const dist = inversion_circle.pc.distanceTo(circle2.pc)[0]; if (Utils.EQ(dist, circle2.r)) { let d2 = inversion_circle.r * inversion_circle.r / (2 * circle2.r); let v2 = new Vector2(inversion_circle.pc, circle2.pc); v2 = v2.normalize(); let pt2 = inversion_circle.pc.translate(v2.multiply(d2)); return new Line2(pt2, v2); } else { let v2 = new Vector2(inversion_circle.pc, circle2.pc); let s2 = inversion_circle.r * inversion_circle.r / (v2.dot(v2) - circle2.r * circle2.r); let pc = inversion_circle.pc.translate(v2.multiply(s2)); let r4 = Math.abs(s2) * circle2.r; return new Circle2(pc, r4); } } static inverseLine(inversion_circle, line2) { const [dist, shortest_segment] = inversion_circle.pc.distanceTo(line2); if (Utils.EQ_0(dist)) { return line2.clone(); } else { let r4 = inversion_circle.r * inversion_circle.r / (2 * dist); let v2 = new Vector2(inversion_circle.pc, shortest_segment.end); v2 = v2.multiply(r4 / dist); return new Circle2(inversion_circle.pc.translate(v2), r4); } } inverse(shape) { if (shape instanceof Point$2) { return _Inversion.inversePoint(this.circle, shape); } else if (shape instanceof Circle2) { return _Inversion.inverseCircle(this.circle, shape); } else if (shape instanceof Line2) { return _Inversion.inverseLine(this.circle, shape); } } }; Flatten.Inversion = Inversion; var inversion = (circle2) => new Flatten.Inversion(circle2); Flatten.inversion = inversion; var Distance = class _Distance { /** * Calculate distance and shortest segment between points * @param pt1 * @param pt2 * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static point2point(pt1, pt2) { return pt1.distanceTo(pt2); } /** * Calculate distance and shortest segment between point and line * @param pt * @param line * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static point2line(pt2, line2) { let closest_point = pt2.projectionOn(line2); let vec = new Flatten.Vector(pt2, closest_point); return [vec.length, new Flatten.Segment(pt2, closest_point)]; } /** * Calculate distance and shortest segment between point and circle * @param pt * @param circle * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static point2circle(pt2, circle2) { let [dist2center, shortest_dist] = pt2.distanceTo(circle2.center); if (Flatten.Utils.EQ_0(dist2center)) { return [circle2.r, new Flatten.Segment(pt2, circle2.toArc().start)]; } else { let dist = Math.abs(dist2center - circle2.r); let v2 = new Flatten.Vector(circle2.pc, pt2).normalize().multiply(circle2.r); let closest_point = circle2.pc.translate(v2); return [dist, new Flatten.Segment(pt2, closest_point)]; } } /** * Calculate distance and shortest segment between point and segment * @param pt * @param segment * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static point2segment(pt2, segment2) { if (segment2.start.equalTo(segment2.end)) { return _Distance.point2point(pt2, segment2.start); } let v_seg = new Flatten.Vector(segment2.start, segment2.end); let v_ps2pt = new Flatten.Vector(segment2.start, pt2); let v_pe2pt = new Flatten.Vector(segment2.end, pt2); let start_sp = v_seg.dot(v_ps2pt); let end_sp = -v_seg.dot(v_pe2pt); let dist; let closest_point; if (Flatten.Utils.GE(start_sp, 0) && Flatten.Utils.GE(end_sp, 0)) { let v_unit = segment2.tangentInStart(); dist = Math.abs(v_unit.cross(v_ps2pt)); closest_point = segment2.start.translate(v_unit.multiply(v_unit.dot(v_ps2pt))); return [dist, new Flatten.Segment(pt2, closest_point)]; } else if (start_sp < 0) { return pt2.distanceTo(segment2.start); } else { return pt2.distanceTo(segment2.end); } } /** * Calculate distance and shortest segment between point and arc * @param pt * @param arc * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static point2arc(pt2, arc2) { let circle2 = new Flatten.Circle(arc2.pc, arc2.r); let dist_and_segment = []; let dist, shortest_segment; [dist, shortest_segment] = _Distance.point2circle(pt2, circle2); if (shortest_segment.end.on(arc2)) { dist_and_segment.push(_Distance.point2circle(pt2, circle2)); } dist_and_segment.push(_Distance.point2point(pt2, arc2.start)); dist_and_segment.push(_Distance.point2point(pt2, arc2.end)); _Distance.sort(dist_and_segment); return dist_and_segment[0]; } /** * Calculate distance and shortest segment between point and edge * @param pt * @param edge * @returns {[number, Flatten.Segment]} */ static point2edge(pt2, edge) { return edge.shape instanceof Flatten.Segment ? _Distance.point2segment(pt2, edge.shape) : _Distance.point2arc(pt2, edge.shape); } /** * Calculate distance and shortest segment between segment and line * @param seg * @param line * @returns {[number, Flatten.Segment]} */ static segment2line(seg, line2) { let ip = seg.intersect(line2); if (ip.length > 0) { return [0, new Flatten.Segment(ip[0], ip[0])]; } let dist_and_segment = []; dist_and_segment.push(_Distance.point2line(seg.start, line2)); dist_and_segment.push(_Distance.point2line(seg.end, line2)); _Distance.sort(dist_and_segment); return dist_and_segment[0]; } /** * Calculate distance and shortest segment between two segments * @param seg1 * @param seg2 * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static segment2segment(seg1, seg2) { let ip = intersectSegment2Segment(seg1, seg2); if (ip.length > 0) { return [0, new Flatten.Segment(ip[0], ip[0])]; } let dist_and_segment = []; let dist_tmp, shortest_segment_tmp; [dist_tmp, shortest_segment_tmp] = _Distance.point2segment(seg2.start, seg1); dist_and_segment.push([dist_tmp, shortest_segment_tmp.reverse()]); [dist_tmp, shortest_segment_tmp] = _Distance.point2segment(seg2.end, seg1); dist_and_segment.push([dist_tmp, shortest_segment_tmp.reverse()]); dist_and_segment.push(_Distance.point2segment(seg1.start, seg2)); dist_and_segment.push(_Distance.point2segment(seg1.end, seg2)); _Distance.sort(dist_and_segment); return dist_and_segment[0]; } /** * Calculate distance and shortest segment between segment and circle * @param seg * @param circle * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static segment2circle(seg, circle2) { let ip = seg.intersect(circle2); if (ip.length > 0) { return [0, new Flatten.Segment(ip[0], ip[0])]; } let line2 = new Flatten.Line(seg.ps, seg.pe); let [dist, shortest_segment] = _Distance.point2line(circle2.center, line2); if (Flatten.Utils.GE(dist, circle2.r) && shortest_segment.end.on(seg)) { return _Distance.point2circle(shortest_segment.end, circle2); } else { let [dist_from_start, shortest_segment_from_start] = _Distance.point2circle(seg.start, circle2); let [dist_from_end, shortest_segment_from_end] = _Distance.point2circle(seg.end, circle2); return Flatten.Utils.LT(dist_from_start, dist_from_end) ? [dist_from_start, shortest_segment_from_start] : [dist_from_end, shortest_segment_from_end]; } } /** * Calculate distance and shortest segment between segment and arc * @param seg * @param arc * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static segment2arc(seg, arc2) { let ip = seg.intersect(arc2); if (ip.length > 0) { return [0, new Flatten.Segment(ip[0], ip[0])]; } let line2 = new Flatten.Line(seg.ps, seg.pe); let circle2 = new Flatten.Circle(arc2.pc, arc2.r); let [dist_from_center, shortest_segment_from_center] = _Distance.point2line(circle2.center, line2); if (Flatten.Utils.GE(dist_from_center, circle2.r) && shortest_segment_from_center.end.on(seg)) { let [dist_from_projection, shortest_segment_from_projection] = _Distance.point2circle(shortest_segment_from_center.end, circle2); if (shortest_segment_from_projection.end.on(arc2)) { return [dist_from_projection, shortest_segment_from_projection]; } } let dist_and_segment = []; dist_and_segment.push(_Distance.point2arc(seg.start, arc2)); dist_and_segment.push(_Distance.point2arc(seg.end, arc2)); let dist_tmp, segment_tmp; [dist_tmp, segment_tmp] = _Distance.point2segment(arc2.start, seg); dist_and_segment.push([dist_tmp, segment_tmp.reverse()]); [dist_tmp, segment_tmp] = _Distance.point2segment(arc2.end, seg); dist_and_segment.push([dist_tmp, segment_tmp.reverse()]); _Distance.sort(dist_and_segment); return dist_and_segment[0]; } /** * Calculate distance and shortest segment between two circles * @param circle1 * @param circle2 * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static circle2circle(circle1, circle2) { let ip = circle1.intersect(circle2); if (ip.length > 0) { return [0, new Flatten.Segment(ip[0], ip[0])]; } if (circle1.center.equalTo(circle2.center)) { let arc1 = circle1.toArc(); let arc2 = circle2.toArc(); return _Distance.point2point(arc1.start, arc2.start); } else { let line2 = new Flatten.Line(circle1.center, circle2.center); let ip1 = line2.intersect(circle1); let ip2 = line2.intersect(circle2); let dist_and_segment = []; dist_and_segment.push(_Distance.point2point(ip1[0], ip2[0])); dist_and_segment.push(_Distance.point2point(ip1[0], ip2[1])); dist_and_segment.push(_Distance.point2point(ip1[1], ip2[0])); dist_and_segment.push(_Distance.point2point(ip1[1], ip2[1])); _Distance.sort(dist_and_segment); return dist_and_segment[0]; } } /** * Calculate distance and shortest segment between two circles * @param circle * @param line * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static circle2line(circle2, line2) { let ip = circle2.intersect(line2); if (ip.length > 0) { return [0, new Flatten.Segment(ip[0], ip[0])]; } let [dist_from_center, shortest_segment_from_center] = _Distance.point2line(circle2.center, line2); let [dist, shortest_segment] = _Distance.point2circle(shortest_segment_from_center.end, circle2); shortest_segment = shortest_segment.reverse(); return [dist, shortest_segment]; } /** * Calculate distance and shortest segment between arc and line * @param arc * @param line * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static arc2line(arc2, line2) { let ip = line2.intersect(arc2); if (ip.length > 0) { return [0, new Flatten.Segment(ip[0], ip[0])]; } let circle2 = new Flatten.Circle(arc2.center, arc2.r); let [dist_from_center, shortest_segment_from_center] = _Distance.point2line(circle2.center, line2); if (Flatten.Utils.GE(dist_from_center, circle2.r)) { let [dist_from_projection, shortest_segment_from_projection] = _Distance.point2circle(shortest_segment_from_center.end, circle2); if (shortest_segment_from_projection.end.on(arc2)) { return [dist_from_projection, shortest_segment_from_projection]; } } else { let dist_and_segment = []; dist_and_segment.push(_Distance.point2line(arc2.start, line2)); dist_and_segment.push(_Distance.point2line(arc2.end, line2)); _Distance.sort(dist_and_segment); return dist_and_segment[0]; } } /** * Calculate distance and shortest segment between arc and circle * @param arc * @param circle2 * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static arc2circle(arc2, circle2) { let ip = arc2.intersect(circle2); if (ip.length > 0) { return [0, new Flatten.Segment(ip[0], ip[0])]; } let circle1 = new Flatten.Circle(arc2.center, arc2.r); let [dist, shortest_segment] = _Distance.circle2circle(circle1, circle2); if (shortest_segment.start.on(arc2)) { return [dist, shortest_segment]; } else { let dist_and_segment = []; dist_and_segment.push(_Distance.point2circle(arc2.start, circle2)); dist_and_segment.push(_Distance.point2circle(arc2.end, circle2)); _Distance.sort(dist_and_segment); return dist_and_segment[0]; } } /** * Calculate distance and shortest segment between two arcs * @param arc1 * @param arc2 * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static arc2arc(arc1, arc2) { let ip = arc1.intersect(arc2); if (ip.length > 0) { return [0, new Flatten.Segment(ip[0], ip[0])]; } let circle1 = new Flatten.Circle(arc1.center, arc1.r); let circle2 = new Flatten.Circle(arc2.center, arc2.r); let [dist, shortest_segment] = _Distance.circle2circle(circle1, circle2); if (shortest_segment.start.on(arc1) && shortest_segment.end.on(arc2)) { return [dist, shortest_segment]; } else { let dist_and_segment = []; let dist_tmp, segment_tmp; [dist_tmp, segment_tmp] = _Distance.point2arc(arc1.start, arc2); if (segment_tmp.end.on(arc2)) { dist_and_segment.push([dist_tmp, segment_tmp]); } [dist_tmp, segment_tmp] = _Distance.point2arc(arc1.end, arc2); if (segment_tmp.end.on(arc2)) { dist_and_segment.push([dist_tmp, segment_tmp]); } [dist_tmp, segment_tmp] = _Distance.point2arc(arc2.start, arc1); if (segment_tmp.end.on(arc1)) { dist_and_segment.push([dist_tmp, segment_tmp.reverse()]); } [dist_tmp, segment_tmp] = _Distance.point2arc(arc2.end, arc1); if (segment_tmp.end.on(arc1)) { dist_and_segment.push([dist_tmp, segment_tmp.reverse()]); } [dist_tmp, segment_tmp] = _Distance.point2point(arc1.start, arc2.start); dist_and_segment.push([dist_tmp, segment_tmp]); [dist_tmp, segment_tmp] = _Distance.point2point(arc1.start, arc2.end); dist_and_segment.push([dist_tmp, segment_tmp]); [dist_tmp, segment_tmp] = _Distance.point2point(arc1.end, arc2.start); dist_and_segment.push([dist_tmp, segment_tmp]); [dist_tmp, segment_tmp] = _Distance.point2point(arc1.end, arc2.end); dist_and_segment.push([dist_tmp, segment_tmp]); _Distance.sort(dist_and_segment); return dist_and_segment[0]; } } /** * Calculate distance and shortest segment between point and polygon * @param point * @param polygon * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static point2polygon(point2, polygon2) { let min_dist_and_segment = [Number.POSITIVE_INFINITY, new Flatten.Segment()]; for (let edge of polygon2.edges) { let [dist, shortest_segment] = _Distance.point2edge(point2, edge); if (Flatten.Utils.LT(dist, min_dist_and_segment[0])) { min_dist_and_segment = [dist, shortest_segment]; } } return min_dist_and_segment; } static shape2polygon(shape, polygon2) { let min_dist_and_segment = [Number.POSITIVE_INFINITY, new Flatten.Segment()]; for (let edge of polygon2.edges) { let [dist, shortest_segment] = shape.distanceTo(edge.shape); if (Flatten.Utils.LT(dist, min_dist_and_segment[0])) { min_dist_and_segment = [dist, shortest_segment]; } } return min_dist_and_segment; } /** * Calculate distance and shortest segment between two polygons * @param polygon1 * @param polygon2 * @returns {[number, Flatten.Segment]} - distance and shortest segment */ static polygon2polygon(polygon1, polygon2) { let min_dist_and_segment = [Number.POSITIVE_INFINITY, new Flatten.Segment()]; for (let edge1 of polygon1.edges) { for (let edge2 of polygon2.edges) { let [dist, shortest_segment] = edge1.shape.distanceTo(edge2.shape); if (Flatten.Utils.LT(dist, min_dist_and_segment[0])) { min_dist_and_segment = [dist, shortest_segment]; } } } return min_dist_and_segment; } /** * Returns [mindist, maxdist] array of squared minimal and maximal distance between boxes * Minimal distance by x is * (box2.xmin - box1.xmax), if box1 is left to box2 * (box1.xmin - box2.xmax), if box2 is left to box1 * 0, if box1 and box2 are intersected by x * Minimal distance by y is defined in the same way * * Maximal distance is estimated as a sum of squared dimensions of the merged box * * @param box1 * @param box2 * @returns {Number | Number} - minimal and maximal distance */ static box2box_minmax(box1, box2) { let mindist_x = Math.max(Math.max(box1.xmin - box2.xmax, 0), Math.max(box2.xmin - box1.xmax, 0)); let mindist_y = Math.max(Math.max(box1.ymin - box2.ymax, 0), Math.max(box2.ymin - box1.ymax, 0)); let mindist = mindist_x * mindist_x + mindist_y * mindist_y; let box3 = box1.merge(box2); let dx = box3.xmax - box3.xmin; let dy = box3.ymax - box3.ymin; let maxdist = dx * dx + dy * dy; return [mindist, maxdist]; } static minmax_tree_process_level(shape, level, min_stop, tree) { let mindist, maxdist; for (let node of level) { [mindist, maxdist] = _Distance.box2box_minmax(shape.box, node.item.key); for (let value of node.item.values) { if (value instanceof Flatten.Edge) { tree.insert([mindist, maxdist], value.shape); } else { tree.insert([mindist, maxdist], value); } } if (Flatten.Utils.LT(maxdist, min_stop)) { min_stop = maxdist; } } if (level.length === 0) return min_stop; let new_level_left = level.map((node) => node.left.isNil() ? void 0 : node.left).filter((node) => node !== void 0); let new_level_right = level.map((node) => node.right.isNil() ? void 0 : node.right).filter((node) => node !== void 0); let new_level = [...new_level_left, ...new_level_right].filter((node) => { let [mindist2, maxdist2] = _Distance.box2box_minmax(shape.box, node.max); return Flatten.Utils.LE(mindist2, min_stop); }); min_stop = _Distance.minmax_tree_process_level(shape, new_level, min_stop, tree); return min_stop; } /** * Calculates sorted tree of [mindist, maxdist] intervals between query shape * and shapes of the planar set. * @param shape * @param set */ static minmax_tree(shape, set2, min_stop) { let tree = new IntervalTree(); let level = [set2.index.root]; let squared_min_stop = min_stop < Number.POSITIVE_INFINITY ? min_stop * min_stop : Number.POSITIVE_INFINITY; squared_min_stop = _Distance.minmax_tree_process_level(shape, level, squared_min_stop, tree); return tree; } static minmax_tree_calc_distance(shape, node, min_dist_and_segment) { let min_dist_and_segment_new, stop; if (node != null && !node.isNil()) { [min_dist_and_segment_new, stop] = _Distance.minmax_tree_calc_distance(shape, node.left, min_dist_and_segment); if (stop) { return [min_dist_and_segment_new, stop]; } if (Flatten.Utils.LT(min_dist_and_segment_new[0], Math.sqrt(node.item.key.low))) { return [min_dist_and_segment_new, true]; } let [dist, shortest_segment] = _Distance.distanceToArray(shape, node.item.values); if (Flatten.Utils.LT(dist, min_dist_and_segment_new[0])) { min_dist_and_segment_new = [dist, shortest_segment]; } [min_dist_and_segment_new, stop] = _Distance.minmax_tree_calc_distance(shape, node.right, min_dist_and_segment_new); return [min_dist_and_segment_new, stop]; } return [min_dist_and_segment, false]; } /** * Calculates distance between shape and Planar Set of shapes * @param shape * @param {PlanarSet} set * @param {Number} min_stop * @returns {*} */ static shape2planarSet(shape, set2, min_stop = Number.POSITIVE_INFINITY) { let min_dist_and_segment = [min_stop, new Flatten.Segment()]; let stop = false; if (set2 instanceof Flatten.PlanarSet) { let tree = _Distance.minmax_tree(shape, set2, min_stop); [min_dist_and_segment, stop] = _Distance.minmax_tree_calc_distance(shape, tree.root, min_dist_and_segment); } return min_dist_and_segment; } static sort(dist_and_segment) { dist_and_segment.sort((d1, d2) => { if (Flatten.Utils.LT(d1[0], d2[0])) { return -1; } if (Flatten.Utils.GT(d1[0], d2[0])) { return 1; } return 0; }); } static distance(shape1, shape2) { return shape1.distanceTo(shape2); } static distanceToArray(shape1, shapes) { let min_dist_and_segment = [Number.POSITIVE_INFINITY, new Flatten.Segment()]; for (let shape2 of shapes) { let [dist, shortest_segment] = shape1.distanceTo(shape2); if (Flatten.Utils.LT(dist, min_dist_and_segment[0])) { min_dist_and_segment = [dist, shortest_segment]; } } return min_dist_and_segment; } /** * Calculate distance and shortest segment any shape and multiline * @param shape * @param multiline * @returns {[number, Flatten.Segment]} */ static shape2multiline(shape, multiline2) { let min_dist_and_segment = [Number.POSITIVE_INFINITY, new Flatten.Segment()]; for (let edge of multiline2) { let [dist, shortest_segment] = _Distance.distance(shape, edge.shape); if (Flatten.Utils.LT(dist, min_dist_and_segment[0])) { min_dist_and_segment = [dist, shortest_segment]; } } return min_dist_and_segment; } /** * Calculate distance and shortest segment between two multilines * @param multiline1 * @param multiline2 * @returns {[number, Flatten.Segment]} */ static multiline2multiline(multiline1, multiline2) { let min_dist_and_segment = [Number.POSITIVE_INFINITY, new Flatten.Segment()]; for (let edge1 of multiline1) { for (let edge2 of multiline2) { let [dist, shortest_segment] = _Distance.distance(edge1.shape, edge2.shape); if (Flatten.Utils.LT(dist, min_dist_and_segment[0])) { min_dist_and_segment = [dist, shortest_segment]; } } } return min_dist_and_segment; } }; Flatten.Distance = Distance; var { Multiline: Multiline2, Point: Point$1, Segment: Segment2, Polygon: Polygon2 } = Flatten; function parseSinglePoint(pointStr) { return new Point$1(pointStr.split(" ").map(Number)); } function parseMultiPoint(multipointStr) { return multipointStr.split(", ").map(parseSinglePoint); } function parseLineString(lineStr) { const points = parseMultiPoint(lineStr); let segments = []; for (let i4 = 0; i4 < points.length - 1; i4++) { segments.push(new Segment2(points[i4], points[i4 + 1])); } return new Multiline2(segments); } function parseMultiLineString(multilineStr) { const lineStrings = multilineStr.replace(/\(\(/, "").replace(/\)\)$/, "").split("), ("); return lineStrings.map(parseLineString); } function parseSinglePolygon(polygonStr) { const facesStr = polygonStr.replace(/\(\(/, "").replace(/\)\)$/, "").split("), ("); const polygon2 = new Polygon2(); let orientation; facesStr.forEach((facesStr2, idx) => { let points = facesStr2.split(", ").map((coordStr) => { return new Point$1(coordStr.split(" ").map(Number)); }); const face = polygon2.addFace(points); if (idx === 0) { orientation = face.orientation(); } else { if (face.orientation() === orientation) { face.reverse(); } } }); return polygon2; } function parseMutliPolygon(multiPolygonString) { const polygonStrings = multiPolygonString.split(/\)\), \(\(/).map((polygon3) => "((" + polygon3 + "))"); const polygons = polygonStrings.map(parseSinglePolygon); const polygon2 = new Polygon2(); const faces = polygons.reduce((acc, polygon3) => [...acc, ...polygon3?.faces], []); faces.forEach((face) => polygon2.addFace([...face?.shapes])); return polygon2; } function parsePolygon(wkt) { if (wkt.startsWith("POLYGON")) { const polygonStr = wkt.replace(/^POLYGON /, ""); return parseSinglePolygon(polygonStr); } else { const multiPolygonString = wkt.replace(/^MULTIPOLYGON \(\(\((.*)\)\)\)$/, "$1"); return parseMutliPolygon(multiPolygonString); } } function parseArrayOfPoints(str) { const arr = str.split("\n").map((x4) => x4.match(/\(([^)]+)\)/)[1]); return arr.map(parseSinglePoint); } function parseArrayOfLineStrings(str) { const arr = str.split("\n").map((x4) => x4.match(/\(([^)]+)\)/)[1]); return arr.map(parseLineString).reduce((acc, x4) => [...acc, ...x4], []); } function parseWKT(str) { if (str.startsWith("POINT")) { const pointStr = str.replace(/^POINT \(/, "").replace(/\)$/, ""); return parseSinglePoint(pointStr); } else if (str.startsWith("MULTIPOINT")) { const multiPointStr = str.replace(/^MULTIPOINT \(/, "").replace(/\)$/, ""); return parseMultiPoint(multiPointStr); } else if (str.startsWith("LINESTRING")) { const lineStr = str.replace(/^LINESTRING \(/, "").replace(/\)$/, ""); return parseLineString(lineStr); } else if (str.startsWith("MULTILINESTRING")) { const multilineStr = str.replace(/^MULTILINESTRING /, ""); return parseMultiLineString(multilineStr); } else if (str.startsWith("POLYGON") || str.startsWith("MULTIPOLYGON")) { return parsePolygon(str); } else if (str.startsWith("GEOMETRYCOLLECTION")) { const regex = /(?POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON) \((?:[^\(\)]|\([^\)]*\))*\)/g; const wktArray = str.match(regex); if (wktArray[0].startsWith("GEOMETRYCOLLECTION")) { wktArray[0] = wktArray[0].replace("GEOMETRYCOLLECTION (", ""); } const flArray = wktArray.map(parseWKT).map((x4) => x4 instanceof Array ? x4 : [x4]); return flArray.reduce((acc, x4) => [...acc, ...x4], []); } else if (isArrayOfPoints(str)) { return parseArrayOfPoints(str); } else if (isArrayOfLines(str)) { return parseArrayOfLineStrings(str); } return []; } function isArrayOfPoints(str) { return str.split("\n")?.every((str2) => str2.includes("POINT")); } function isArrayOfLines(str) { return str.split("\n")?.every((str2) => str2.includes("LINESTRING")); } function isWktString(str) { return str.startsWith("POINT") || isArrayOfPoints(str) || str.startsWith("LINESTRING") || isArrayOfLines(str) || str.startsWith("MULTILINESTRING") || str.startsWith("POLYGON") || str.startsWith("MULTIPOINT") || str.startsWith("MULTIPOLYGON") || str.startsWith("GEOMETRYCOLLECTION"); } Flatten.isWktString = isWktString; Flatten.parseWKT = parseWKT; Flatten.BooleanOperations = BooleanOperations; Flatten.Relations = Relations; // src/tools/workspace-files.ts var KNOWN_SOURCE_FILES = { aml: "aml.xml", bss: "bss.md", rules: "rules.yml", behaviors: "behaviors.yml", brief: "design-brief.md" }; var ALLOWED_EXTENSIONS = /* @__PURE__ */ new Set([ ".aml", ".xml", ".md", ".markdown", ".yml", ".yaml", ".json", ".txt", ".csv", ".ts", ".tsx", ".js", ".mjs", ".cjs", ".html", ".css", ".py", ".pyw", ".bss", ".rules", ".behaviors" ]); function isAllowedWorkspaceTextFile(path) { const name24 = path.split("/").pop() ?? ""; if (!name24.includes(".")) return false; const ext = name24.slice(name24.lastIndexOf(".")).toLowerCase(); return ALLOWED_EXTENSIONS.has(ext); } function sanitizeRelativePath(file2) { if (typeof file2 !== "string") return null; const trimmed = file2.trim(); if (!trimmed || trimmed.length > 512 || trimmed.includes("\0")) return null; if (trimmed.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(trimmed)) return null; const parts = trimmed.split(/[\\/]/); if (parts.some((p2) => p2 === ".." || p2 === "")) return null; if (!parts[parts.length - 1].includes(".")) return null; return parts.join("/"); } function canonicalSyncPath(rawKey) { const trimmed = typeof rawKey === "string" ? rawKey.trim() : ""; if (!trimmed) return null; const lower = trimmed.toLowerCase(); for (const [key, name24] of Object.entries(KNOWN_SOURCE_FILES)) { if (lower === key || lower === name24) return name24; } return sanitizeRelativePath(trimmed); } function resolveWorkspaceFile(file2) { const trimmed = (file2 ?? "").trim().replace(/\\/g, "/"); if (!trimmed) { return { kind: "error", error: "file \u4E0D\u80FD\u4E3A\u7A7A\uFF08\u652F\u6301 aml/bss/rules/behaviors/brief \u6216\u5DE5\u4F5C\u533A\u76F8\u5BF9\u8DEF\u5F84\uFF09" }; } const lower = trimmed.toLowerCase(); const knownEntry = Object.entries(KNOWN_SOURCE_FILES).find(([key, name24]) => key === lower || name24 === lower); if (knownEntry) return { kind: "known", key: knownEntry[0] }; const path = sanitizeRelativePath(trimmed); if (!path) { return { kind: "error", error: 'file \u5FC5\u987B\u662F\u5DE5\u4F5C\u533A\u76F8\u5BF9\u6587\u4EF6\u8DEF\u5F84\uFF08\u4E0D\u5141\u8BB8\u7EDD\u5BF9\u8DEF\u5F84 / ".." \u7A7F\u8D8A\uFF09\uFF0C\u5982 "AGENTS.md"\u3001"docs/notes.md"\u3002' }; } const ext = path.slice(path.lastIndexOf(".")).toLowerCase(); if (!ALLOWED_EXTENSIONS.has(ext)) { return { kind: "error", error: `\u4E0D\u652F\u6301\u7684\u6587\u4EF6\u7C7B\u578B "${ext}"\u3002\u5F53\u524D\u767D\u540D\u5355\uFF1A${[...ALLOWED_EXTENSIONS].join(" / ")}` }; } return { kind: "generic", path }; } function resolveWorkspaceRoot(execOpts) { const c2 = execOpts?.context ?? {}; const root = c2?.syncWorkspaceRoot ?? c2?.workspaceRoot ?? execOpts?.syncWorkspaceRoot ?? execOpts?.workspaceRoot; return typeof root === "string" && root.length > 0 ? root : void 0; } function resolveWorkspaceChild(root, relPath) { const rel = (relPath ?? "").trim(); if (!rel) return { ok: false, error: "\u8DEF\u5F84\u4E3A\u7A7A" }; if (rel.startsWith("/") || rel.startsWith("\\") || /^[A-Za-z]:[\\/]/.test(rel)) { return { ok: false, error: `\u8DEF\u5F84\u300C${rel}\u300D\u975E\u6CD5\uFF1A\u4E0D\u5141\u8BB8\u7EDD\u5BF9\u8DEF\u5F84` }; } const segments = rel.split(/[\\/]+/); if (segments.some((seg) => seg === "..")) { return { ok: false, error: `\u8DEF\u5F84\u300C${rel}\u300D\u975E\u6CD5\uFF1A\u4E0D\u5141\u8BB8 ".." \u6BB5` }; } const normalized = segments.filter((seg) => seg && seg !== ".").join("/"); const base = root.replace(/[\\/]+$/, ""); if (!normalized || !base || !`${base}/${normalized}`.startsWith(`${base}/`)) { return { ok: false, error: `\u8DEF\u5F84\u300C${rel}\u300D\u975E\u6CD5\uFF1A\u76EE\u6807\u9003\u51FA\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55` }; } return { ok: true, absPath: `${base}/${normalized}` }; } // src/tools/solid-scripts.ts function extractSolidScriptPaths(aml) { const out = []; const seen = /* @__PURE__ */ new Set(); if (typeof aml !== "string" || !aml) return out; const re2 = /]*?\bscript="([^"]*)"/g; let m3; while ((m3 = re2.exec(aml)) !== null) { const p2 = (m3[1] ?? "").trim(); if (p2 && !seen.has(p2)) { seen.add(p2); out.push(p2); } } return out; } async function collectSolidScripts(aml, read) { const paths = extractSolidScriptPaths(aml); const scripts = {}; const problems = []; if (!paths.length) return { scripts, problems }; if (!read) { for (const p2 of paths) { problems.push(`\u300C${p2}\u300D\uFF1A\u65E0\u5DE5\u4F5C\u533A\u8BFB\u53D6\u901A\u9053\uFF08\u5BBF\u4E3B\u672A\u6CE8\u5165 getWorkspaceFile\uFF09`); } return { scripts, problems }; } for (const p2 of paths) { const safe = sanitizeRelativePath(p2); if (!safe) { problems.push(`\u300C${p2}\u300D\uFF1A\u975E\u6CD5\u5DE5\u4F5C\u533A\u8DEF\u5F84\uFF08\u4E0D\u5141\u8BB8\u7EDD\u5BF9\u8DEF\u5F84 / ".." \u7A7F\u8D8A / \u76EE\u5F55\u5F62\u5F0F\uFF09`); continue; } try { const text2 = await read(safe); if (typeof text2 === "string" && text2.length > 0) { scripts[p2] = text2; } else { problems.push(`\u300C${p2}\u300D\uFF1A\u5DE5\u4F5C\u533A\u672A\u627E\u5230\u8BE5\u6587\u4EF6\uFF08\u6216\u4E3A\u7A7A\u6587\u4EF6\uFF09`); } } catch (err2) { const msg = err2 instanceof Error ? err2.message : String(err2); problems.push(`\u300C${p2}\u300D\uFF1A\u8BFB\u53D6\u5931\u8D25\uFF08${msg.slice(0, 160)}\uFF09`); } } return { scripts, problems }; } function missingSolidScriptPaths(aml, provided) { const paths = extractSolidScriptPaths(aml); if (!paths.length) return []; return paths.filter((p2) => { const v2 = provided?.[p2]; return typeof v2 !== "string" || v2.length === 0; }); } function formatMissingSolidScripts(paths) { return `AML \u5F15\u7528\u4E86 \u4F46\u672A\u968F\u8BF7\u6C42\u643A\u5E26\u811A\u672C\u5185\u5BB9\uFF1A${paths.join("\u3001")}\u3002 GSA \u662F\u7F16\u8BD1\u670D\u52A1\u3001\u65E0\u5DE5\u4F5C\u533A\u8BBF\u95EE\u6743\uFF1A\u7F3A\u811A\u672C\u65F6\u5B83\u4E0D\u4F1A\u62A5\u9519\uFF0C\u800C\u662F\u6309\u300C\u65E0\u5B9E\u4F53\u51E0\u4F55\u300D\u7EE7\u7EED\uFF08issue MESH-GEO-007\uFF09\uFF0C\u8868\u73B0\u4E3A\u7F16\u8BD1\u901A\u8FC7\u4F46\u5F62\u4F53\u4E22\u5931\u3001\u5BA1\u8BA1 fatal \u4E0E\u8D28\u91CF\u95E8\u7981\u5F02\u5E38\u3002 \u8BF7\u628A\u811A\u672C\u5199\u5165\u5DE5\u4F5C\u533A\uFF08\u5982 geometry/shapes.py\uFF09\uFF0C\u6216\u7531\u5BBF\u4E3B\u8BFB\u53D6\u540E\u968F\u8BF7\u6C42\u643A\u5E26\uFF08\u952E\u540D\u5FC5\u987B\u4E0E AML \u58F0\u660E\u4E00\u5B57\u4E0D\u5DEE\uFF0C\u542B\u76EE\u5F55\u524D\u7F00\uFF09\u3002`; } // src/gsa/converter.ts function genId() { return "xxxxxxxxxxxx".replace( /x/g, () => Math.floor(Math.random() * 16).toString(16) ); } function computeCentroid(pts) { const n5 = pts.length; if (n5 === 0) return [0, 0, 0]; const [sx, sy, sz] = pts.reduce(([a3, b5, c2], p2) => [a3 + p2[0], b5 + (p2[1] ?? 0), c2 + (p2[2] ?? 0)], [0, 0, 0]); return [sx / n5, sy / n5, sz / n5]; } function floorPlanOutline(spaces) { const profiles = (spaces ?? []).map((s2) => s2?.profile).filter((p2) => Array.isArray(p2) && p2.length >= 3); if (profiles.length > 0) { const united = unionProfiles(profiles); if (united) return united; let best = null; let bestArea = -1; for (const p2 of profiles) { let a3 = 0; for (let i4 = 0; i4 < p2.length; i4++) { const q2 = p2[(i4 + 1) % p2.length]; a3 += p2[i4][0] * q2[1] - q2[0] * p2[i4][1]; } const area = Math.abs(a3) / 2; if (area > bestArea) { bestArea = area; best = p2; } } if (best) return best.map((pt2) => [pt2[0], pt2[1], 0]); } const pts = []; for (const space of spaces) { const p2 = space.profile; if (p2) pts.push(...p2); } if (pts.length === 0) return []; const distinct = pts.filter( (p2, i4, arr) => arr.findIndex((a3) => a3[0] === p2[0] && a3[1] === p2[1]) === i4 ); if (distinct.length <= 3) { const xs2 = distinct.map((p2) => p2[0]); const ys2 = distinct.map((p2) => p2[1]); return [ [Math.min(...xs2), Math.max(...ys2), 0], [Math.max(...xs2), Math.max(...ys2), 0], [Math.max(...xs2), Math.min(...ys2), 0], [Math.min(...xs2), Math.min(...ys2), 0] ]; } const sorted = distinct.sort((a3, b5) => a3[1] - b5[1] || a3[0] - b5[0]); const cross = (o3, a3, b5) => (a3[0] - o3[0]) * (b5[1] - o3[1]) - (a3[1] - o3[1]) * (b5[0] - o3[0]); const lower = []; for (const p2 of sorted) { while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p2) <= 0) lower.pop(); lower.push(p2); } const upper = []; for (const p2 of sorted.reverse()) { while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p2) <= 0) upper.pop(); upper.push(p2); } const fullHull = [...lower.slice(0, -1), ...upper.slice(0, -1)]; return fullHull.map((p2) => [p2[0], p2[1], 0]); } function spaceTypeToProgram(gsaType) { const map2 = { office: "Office", lobby: "Lobby", corridor: "Circulation", circulation: "Circulation", service: "Service", meeting: "Meeting", wc: "Restroom", bathroom: "Restroom", kitchen: "Kitchen", storage: "Storage", bedroom: "Bedroom", living: "Living", living_dining: "Living Dining", balcony: "Balcony" }; return map2[gsaType?.toLowerCase()] || void 0; } function spaceTypeToSlabType(gsaType) { const map2 = { terrace: "terrace", balcony: "balcony", courtyard: "courtyard", porch: "porch", arcade: "arcade" }; return map2[gsaType?.toLowerCase()]; } var MERGEABLE_SPACE_TYPES = /* @__PURE__ */ new Set([ "corridor", "circulation", "lobby", "entrance", "foyer", "hallway", "dining", "living" ]); var PUBLIC_CORE_TYPES = /* @__PURE__ */ new Set([ "stair", "stairs", "elevator", "elevator_lobby", "lobby", "vestibule", "shaft", "core", "service" ]); function isPublicCoreSpace(space) { const type = String(space.type || "").toLowerCase(); if (PUBLIC_CORE_TYPES.has(type)) return true; const name24 = String(space.name || ""); return /楼梯|电梯厅|候梯|前室|竖井|管井|风井|电井|缆井|井道|公共走廊/.test(name24); } function touchesShaft(profile, shaftProfiles, minSharedM) { if (!profile || profile.length < 3) return false; for (const sp of shaftProfiles) { for (let i4 = 0; i4 < profile.length; i4++) { const a1 = profile[i4], a22 = profile[(i4 + 1) % profile.length]; for (let j2 = 0; j2 < sp.length; j2++) { if (segmentOverlapLength(a1, a22, sp[j2], sp[(j2 + 1) % sp.length]) >= minSharedM) return true; } } } return false; } var MERGE_SEMANTIC_EDGE_TYPES = /* @__PURE__ */ new Set(["door", "flows", "walk"]); function toFlattenPolygon(profile) { if (!profile || profile.length < 3) return null; const xs2 = profile.map((p2) => p2[0]); const ys2 = profile.map((p2) => p2[1]); if (Math.max(...xs2) - Math.min(...xs2) < 1e-6 || Math.max(...ys2) - Math.min(...ys2) < 1e-6) return null; const poly = new Flatten.Polygon(); poly.addFace(profile.map((p2) => new Flatten.Point(p2[0], p2[1]))); return poly; } function unionProfiles(profiles) { const polys = profiles.map(toFlattenPolygon).filter((p2) => p2 !== null); if (polys.length === 0) return null; let current = polys[0]; try { for (const other of polys.slice(1)) { current = Flatten.BooleanOperations.unify(current, other); } } catch { return null; } if (!current || current.isEmpty()) return null; let singleFace = null; for (const face of current.faces) { if (Math.abs(face.area()) < 1e-6) continue; if (singleFace) return null; singleFace = face; } if (!singleFace) return null; const pts = singleFace.vertices.map((v2) => [Math.round(v2.x * 1e3) / 1e3, Math.round(v2.y * 1e3) / 1e3, 0]); if (pts.length > 1 && pts[0][0] === pts[pts.length - 1][0] && pts[0][1] === pts[pts.length - 1][1]) pts.pop(); const simplified = pts.filter((p2, i4) => { const prev = pts[(i4 - 1 + pts.length) % pts.length]; const next = pts[(i4 + 1) % pts.length]; const cross = (p2[0] - prev[0]) * (next[1] - prev[1]) - (p2[1] - prev[1]) * (next[0] - prev[0]); return Math.abs(cross) > 1e-6; }); return simplified.length >= 3 ? simplified : null; } function segmentOverlapLength(a1, a22, b1, b22) { const ax = a22[0] - a1[0], ay = a22[1] - a1[1]; const aLen = Math.hypot(ax, ay); if (aLen < 1e-9) return 0; const ux = ax / aLen, uy = ay / aLen; const dist = (p2) => Math.abs((p2[0] - a1[0]) * uy - (p2[1] - a1[1]) * ux); if (dist(b1) > 1e-3 || dist(b22) > 1e-3) return 0; const t4 = (p2) => (p2[0] - a1[0]) * ux + (p2[1] - a1[1]) * uy; const lo = Math.max(0, Math.min(t4(b1), t4(b22))); const hi2 = Math.min(aLen, Math.max(t4(b1), t4(b22))); return Math.max(0, hi2 - lo); } function isSharedBoundary(bProfile, otherProfile) { if (bProfile.length < 2 || otherProfile.length < 3) return false; const p1 = bProfile[0], p2 = bProfile[bProfile.length - 1]; const bLen = Math.hypot(p2[0] - p1[0], p2[1] - p1[1]); if (bLen < 1e-6) return false; for (let i4 = 0; i4 < otherProfile.length; i4++) { const q1 = otherProfile[i4], q2 = otherProfile[(i4 + 1) % otherProfile.length]; const shared = segmentOverlapLength(p1, p2, q1, q2); if (shared <= 1e-3) continue; const qLen = Math.hypot(q2[0] - q1[0], q2[1] - q1[1]); if (shared > 0.5 * Math.min(bLen, qLen)) return true; } return false; } function computeMergeGroups(spaces, adjacency, cfg, warnings) { const result = /* @__PURE__ */ new Map(); const candidates = /* @__PURE__ */ new Map(); const candUnit = /* @__PURE__ */ new Map(); for (const s2 of spaces) { const enclosure = s2.enclosure || "indoor"; if (enclosure !== "indoor" || s2.type === "void") continue; if (s2.z_bounds && s2.z_bounds.length >= 2) continue; const directive = String(s2.merge ?? s2.metadata?.merge ?? "").toLowerCase(); if (directive === "never") continue; if (directive !== "traffic" && isPublicCoreSpace(s2)) continue; const unit = cfg.unitOf?.get(s2.id); if (directive !== "traffic") { if (!cfg.mergeableTypes.has((s2.type || "").toLowerCase())) continue; if (cfg.unitOf && !unit) continue; if (cfg.publicSpaceIds?.has(s2.id)) continue; } candidates.set(s2.id, s2); if (cfg.unitOf) candUnit.set(s2.id, unit ?? "__explicit__"); } if (candidates.size < 2) return result; const parent = new Map([...candidates.keys()].map((id) => [id, id])); const find = (x4) => { let root = x4; while (parent.get(root) !== root) root = parent.get(root); let cur = x4; while (parent.get(cur) !== cur) { const next = parent.get(cur); parent.set(cur, root); cur = next; } return root; }; for (const pair of adjacency) { if (!pair.from || !pair.to || !candidates.has(pair.from) || !candidates.has(pair.to)) continue; if (cfg.unitOf && candUnit.get(pair.from) !== candUnit.get(pair.to)) continue; const t4 = (pair.type || "").toLowerCase(); const connected = MERGE_SEMANTIC_EDGE_TYPES.has(t4) || (pair.shared_length_m ?? 0) >= cfg.minSharedLengthM; if (connected) parent.set(find(pair.from), find(pair.to)); } const groups = /* @__PURE__ */ new Map(); for (const id of candidates.keys()) { const root = find(id); const list = groups.get(root); if (list) list.push(candidates.get(id)); else groups.set(root, [candidates.get(id)]); } for (const members of groups.values()) { if (members.length < 2) continue; const region = unionProfiles(members.map((m3) => m3.profile || [])); if (!region) { warnings.push( `\u4EA4\u901A\u7A7A\u95F4\u5408\u5E76\u5931\u8D25\uFF1A${members.map((m3) => m3.id).join(" + ")} \u7684\u8F6E\u5ED3\u5E76\u96C6\u4E0D\u662F\u5355\u4E00\u8FDE\u901A\u533A\u57DF\uFF0C\u5DF2\u6309\u672A\u5408\u5E76\u5904\u7406` ); continue; } const area = members.reduce((n5, m3) => n5 + (m3.area?.value || 0), 0); let cx = 0, cy = 0, wSum = 0; for (const m3 of members) { const w3 = m3.area?.value || 0 || 1; const c2 = computeCentroid(m3.profile || []); cx += c2[0] * w3; cy += c2[1] * w3; wSum += w3; } const representative = members.reduce((a3, b5) => (b5.area?.value || 0) > (a3.area?.value || 0) ? b5 : a3); const group = { representativeId: representative.id, members, region, area, centroid: [cx / wSum, cy / wSum, 0] }; for (const m3 of members) result.set(m3.id, group); } return result; } function aperturePerformance(ap) { const openratio = typeof ap.open_ratio === "number" && Number.isFinite(ap.open_ratio) ? ap.open_ratio : typeof ap.openratio === "number" ? ap.openratio : 1; const operable = typeof ap.operable === "boolean" ? ap.operable : false; const trans = typeof ap.transparency === "number" && Number.isFinite(ap.transparency) ? ap.transparency : typeof ap.trans === "number" ? ap.trans : 0.6; const properties = typeof ap.opening_type === "string" && ap.opening_type ? { opening_type: ap.opening_type } : void 0; return { openratio, operable, trans, properties }; } function gsaProjectToBuilding(gsa, options) { const templateMetaByLevel = /* @__PURE__ */ new Map(); for (const use of gsa.uses || []) { for (const rl of use.resolved_levels || []) { templateMetaByLevel.set(rl, { template_id: use.template ?? rl.metadata?._template_id, use_id: use.id ?? rl.metadata?._use_id }); } } const levels = [...gsa.levels || [], ...templateMetaByLevel.keys()].sort((a3, b5) => (a3.elevation?.value ?? 0) - (b5.elevation?.value ?? 0)); const allApertures = []; const allRooms = []; const allSlabs = []; const warnings = []; const usedApertureIds = /* @__PURE__ */ new Set(); const mergeCfg = (() => { const m3 = options?.mergeTrafficSpaces; if (!m3 || !options?.adjacency?.length) return null; const mergeableTypes = new Set(MERGEABLE_SPACE_TYPES); let minSharedLengthM = 0.9; if (typeof m3 === "object") { if (m3.mergeableTypes) { mergeableTypes.clear(); for (const t4 of m3.mergeableTypes) mergeableTypes.add(t4.toLowerCase()); } if (typeof m3.minSharedLengthM === "number") minSharedLengthM = m3.minSharedLengthM; } return { mergeableTypes, minSharedLengthM }; })(); const shaftAdjacentIds = (() => { if (!mergeCfg) return void 0; const shaftProfiles = (gsa.shafts || []).map((s2) => s2.profile || []).filter((p2) => p2.length >= 3); if (shaftProfiles.length === 0) return /* @__PURE__ */ new Set(); const ids = /* @__PURE__ */ new Set(); for (const lvl of levels) { for (const s2 of lvl.spaces || []) { if (!s2.id) continue; if (touchesShaft(s2.profile || [], shaftProfiles, mergeCfg.minSharedLengthM)) ids.add(s2.id); } } return ids; })(); const collectSpaceApertures = (srcSpace, roomId, level, dropBoundaryDoor) => { const apertureIds = []; for (const b5 of srcSpace.boundaries || []) { const bAps = b5.apertures || []; for (let api = 0; api < bAps.length; api++) { const ap = bAps[api]; if (typeof ap.type === "string" && ap.type.toUpperCase() === "DOOR" && dropBoundaryDoor && dropBoundaryDoor(b5.profile || [], b5)) continue; const rawId = ap.id || `AP-${genId()}`; const apId = usedApertureIds.has(rawId) ? `${rawId}-${genId()}` : rawId; usedApertureIds.add(apId); apertureIds.push(apId); apCounter++; const apW = typeof ap.width === "object" ? ap.width?.value : ap.width ?? 1.5; const apH = typeof ap.height === "object" ? ap.height?.value : ap.height ?? 1.5; const apSill = typeof ap.sill_height === "object" ? ap.sill_height?.value : ap.sill_height ?? 0.9; const apType = typeof ap.type === "string" ? ap.type.toUpperCase() : "WINDOW"; const gsaFaceIdx = ap.face_index; const gsaUvRect = ap.uv_rect; const uCenter = gsaUvRect?.[0] ?? (api + 1) / (bAps.length + 1); if (!gsaUvRect && bAps.length > 1) { warnings.push( `\u7A97 "${apId}" \u7F3A\u5C11 GSA \u5B9A\u4F4D\uFF08uv_rect\uFF09\uFF0C\u5DF2\u6309\u540C\u5899 ${bAps.length} \u7A97\u5747\u5E03\u515C\u5E95\u653E\u7F6E\uFF08u=${uCenter.toFixed(2)}\uFF09\uFF0C\u4F4D\u7F6E\u53EF\u80FD\u4E0E AML \u58F0\u660E\u4E0D\u4E00\u81F4` ); } const bProfile = b5.profile || []; let planCrv = []; if (bProfile.length >= 2) { const p1x = bProfile[0][0], p1y = bProfile[0][1]; const p2x = bProfile[bProfile.length - 1][0], p2y = bProfile[bProfile.length - 1][1]; const isHorizontal = Math.abs(p2y - p1y) < 0.01; const mx = p1x + (p2x - p1x) * uCenter, my = p1y + (p2y - p1y) * uCenter; const mz = level.elevation?.value ?? 0; if (isHorizontal) { planCrv = [ [mx - apW / 2, my, mz + apSill], [mx + apW / 2, my, mz + apSill], [mx + apW / 2, my, mz + apSill + apH], [mx - apW / 2, my, mz + apSill + apH] ]; } else { planCrv = [ [mx, my - apW / 2, mz + apSill], [mx, my + apW / 2, mz + apSill], [mx, my + apW / 2, mz + apSill + apH], [mx, my - apW / 2, mz + apSill + apH] ]; } } const isWindow = apType === "WINDOW"; const bIdx = gsaFaceIdx != null ? gsaFaceIdx : srcSpace.boundaries ? srcSpace.boundaries.indexOf(b5) : 0; const uvRect = gsaUvRect || (() => { const bLen = bProfile.length >= 2 ? Math.sqrt( (bProfile[bProfile.length - 1][0] - bProfile[0][0]) ** 2 + (bProfile[bProfile.length - 1][1] - bProfile[0][1]) ** 2 ) : 1; const levelH = level.height?.value ?? 3; return [ // u: 归一化中心点(缺 GSA 定位时按同墙多窗均布,与 plan_crv 一致) uCenter, levelH > 0 ? apSill / levelH : 0.3, // v: 窗台/墙高 bLen > 0 ? apW / bLen : 0.4, // w: 窗宽/墙长 levelH > 0 ? apH / levelH : 0.5 // h: 窗高/墙高 ]; })(); const hostId = roomId; const bSemantic = b5.physical_properties?.semantic_type; const onExteriorWall = bSemantic === "external_wall" ? true : bSemantic === "internal_wall" ? false : void 0; const bNeighborId = b5.metadata?.neighbor_id; const neighborSpaces = typeof bNeighborId === "string" && bNeighborId.trim() ? bNeighborId.split(",") : void 0; const perf = aperturePerformance(ap); const toOutside = ap.to_outside === true || ap.to_outside === "true" || ap.to_outside === "1"; allApertures.push({ identifier: apId, display_name: ap.name || apId, geometry_type: isWindow ? "window" : "door", type: isWindow || toOutside ? "external" : "internal", rooms: [roomId], parent: roomId, openratio: perf.openratio, operable: perf.operable, trans: isWindow ? perf.trans : 0, pressure: 1, sill_height: apSill, width: apW, height: apH, area: apW * apH, plan_crv: planCrv, ...perf.properties ? { properties: perf.properties } : {}, hosting: { primary_host_id: hostId, face_index: bIdx, uv_rect: uvRect, context: "EXTERIOR", ...onExteriorWall !== void 0 ? { on_exterior_wall: onExteriorWall } : {}, ...neighborSpaces ? { neighbor_spaces: neighborSpaces } : {}, ...toOutside ? { to_outside: true } : {} } }); } } for (const ap of srcSpace.apertures || []) { if (apertureIds.includes(ap.id || "")) continue; const rawId = ap.id || `AP-${genId()}`; const apId = usedApertureIds.has(rawId) ? `${rawId}-${genId()}` : rawId; usedApertureIds.add(apId); apertureIds.push(apId); const apW = typeof ap.width === "object" ? ap.width?.value : ap.width ?? 1.5; const apH = typeof ap.height === "object" ? ap.height?.value : ap.height ?? 1.5; const apSill = typeof ap.sill_height === "object" ? ap.sill_height?.value : ap.sill_height ?? 0.9; const apType = typeof ap.type === "string" ? ap.type.toUpperCase() : "WINDOW"; const isWindow2 = apType === "WINDOW"; const perf2 = aperturePerformance(ap); const toOutside2 = ap.to_outside === true || ap.to_outside === "true" || ap.to_outside === "1"; const gsaPlanCrv = ap.plan_crv ?? ap.metadata?.plan_crv; const planCrv2 = Array.isArray(gsaPlanCrv) && gsaPlanCrv.length >= 2 ? gsaPlanCrv : []; const gsaPoly = ap.metadata?.plan_crv_poly; const planCrvPoly = Array.isArray(gsaPoly) && gsaPoly.length >= 3 ? gsaPoly : []; const gsaPatch = ap.metadata?.patch_grid; const patchGrid = Array.isArray(gsaPatch) && gsaPatch.length >= 2 ? gsaPatch : []; const apUv = ap.uv_rect; const amlDecl = { ...ap.expressions?.host ? { host: String(ap.expressions.host) } : {}, ...Array.isArray(apUv) && apUv.length >= 2 ? { u: String(apUv[0]), v: String(apUv[1]) } : {} }; allApertures.push({ identifier: apId, display_name: ap.name || apId, geometry_type: isWindow2 ? "window" : "door", type: isWindow2 || toOutside2 ? "external" : "internal", rooms: [roomId], parent: roomId, openratio: perf2.openratio, operable: perf2.operable, trans: isWindow2 ? perf2.trans : 0, pressure: 1, sill_height: apSill, width: apW, height: apH, area: apW * apH, plan_crv: planCrv2, ...planCrvPoly.length ? { plan_crv_poly: planCrvPoly } : {}, ...patchGrid.length ? { patch_grid: patchGrid } : {}, ...Object.keys(amlDecl).length ? { metadata: { aml_decl: amlDecl } } : {}, ...perf2.properties ? { properties: perf2.properties } : {}, hosting: { primary_host_id: roomId, face_index: 0, // 面集宿主洞口用 GSA 求值出的真实 uv_rect([u,v,w,h]),缺省才回退占位 uv_rect: Array.isArray(apUv) && apUv.length >= 4 ? apUv : [0.5, 0.3, 0.4, 0.5], context: "EXTERIOR", ...toOutside2 ? { to_outside: true } : {} } }); } return apertureIds; }; const levelMap = /* @__PURE__ */ new Map(); for (const lvl of levels) { levelMap.set(lvl.id, { elevation: lvl.elevation?.value ?? 0, height: lvl.height?.value ?? 3 }); } const processedCrossLevelSpaces = /* @__PURE__ */ new Set(); let apCounter = 0; const floors = levels.map((level, si2) => { const spaces = level.spaces || []; const outline = floorPlanOutline(spaces); const containerDecl = new Map( (level.containers || []).filter((c2) => !!c2.id).map((c2) => [c2.id, c2]) ); const rooms = []; const slabs = []; const explicitGroups = /* @__PURE__ */ new Map(); const explicitSpaceIds = /* @__PURE__ */ new Set(); if ((level.rooms || []).length > 0) { const spaceById = new Map(spaces.map((s2) => [s2.id, s2])); for (const room of level.rooms || []) { const members = (room.contains_ids || []).map((mid) => spaceById.get(mid)).filter(Boolean); if (members.length === 0) { if (room.id) warnings.push(`room "${room.id}" \u672A\u89E3\u6790\u5230\u540C\u5C42\u6210\u5458 space\uFF0C\u5DF2\u5FFD\u7565\uFF08\u68C0\u67E5 contains \u5F15\u7528\uFF09`); continue; } if (members.some((m3) => m3.z_bounds && m3.z_bounds.length >= 2)) { if (room.id) warnings.push(`room "${room.id}" \u542B\u8DE8\u5C42\u6210\u5458\u7A7A\u95F4\uFF0C\u6682\u4E0D\u652F\u6301\uFF0C\u5DF2\u5FFD\u7565\u663E\u5F0F\u62FC\u5408`); continue; } const region = room.profile && room.profile.length >= 3 ? room.profile : unionProfiles(members.map((m3) => m3.profile || [])); if (!region || region.length < 3) { if (room.id) warnings.push(`room "${room.id}" \u7684\u6210\u5458\u5E76\u96C6\u4E0D\u662F\u5355\u4E00\u8FDE\u901A\u533A\u57DF\uFF0C\u5DF2\u5FFD\u7565\u663E\u5F0F\u62FC\u5408`); continue; } const area = room.area?.value ?? members.reduce((n5, m3) => n5 + (m3.area?.value || 0), 0); let cx = 0, cy = 0, wSum = 0; for (const m3 of members) { const w3 = m3.area?.value || 0 || 1; const c2 = computeCentroid(m3.profile || []); cx += c2[0] * w3; cy += c2[1] * w3; wSum += w3; } const declaredId = room.id || members[0].id; const group = { representativeId: members[0].id, declaredId, declaredName: room.name, declaredType: room.type, members, region, area, centroid: [cx / wSum, cy / wSum, 0] }; for (const m3 of members) { explicitGroups.set(m3.id, group); explicitSpaceIds.add(m3.id); } } } const mergeBySpace = (() => { if (!mergeCfg) return /* @__PURE__ */ new Map(); const remaining = spaces.filter((s2) => !explicitSpaceIds.has(s2.id)); if (remaining.length < 2) return /* @__PURE__ */ new Map(); const unitOf = /* @__PURE__ */ new Map(); for (const s2 of remaining) { const key = s2.metadata?._use_id ?? s2.metadata?._template_id; if (s2.id && key) unitOf.set(s2.id, String(key)); } const templateMode = unitOf.size > 0; return computeMergeGroups(remaining, options.adjacency, { ...mergeCfg, unitOf: templateMode ? unitOf : void 0, publicSpaceIds: templateMode ? void 0 : shaftAdjacentIds }, warnings); })(); const effectiveMerge = explicitGroups.size > 0 ? new Map([...mergeBySpace, ...explicitGroups]) : mergeBySpace; for (const space of spaces) { const enclosure = space.enclosure || "indoor"; const mergeGroup = effectiveMerge.get(space.id); if (mergeGroup && mergeGroup.representativeId !== space.id) continue; if (enclosure === "void" || space.type === "void") { const ceilH2 = space.ceiling_height?.value || level.height?.value || 3; const slab = { identifier: space.id, display_name: space.name || space.id, type: "void", enclosure: "void", floorId: level.id, polygon: space.profile || [], elevation: level.elevation?.value ?? 0, height: ceilH2, axis: space.axis || "default", geometry_driver: { type: "planar_extrude", height: ceilH2, direction: [0, 0, 1], outline: space.profile || [] }, metadata: {} }; slabs.push(slab); allSlabs.push(slab); continue; } const isBalcony = (enclosure === "semi-indoor" || enclosure === "outdoor") && (space.type || "").toLowerCase() === "balcony"; if ((enclosure === "semi-indoor" || enclosure === "outdoor") && !isBalcony) { const area2 = space.area?.value || 0; const ceilH2 = space.ceiling_height?.value || level.height?.value || 3; const slabType = spaceTypeToSlabType(space.type || "") || (enclosure === "semi-indoor" ? "arcade" : "terrace"); const slab = { identifier: space.id, display_name: space.name || space.id, type: slabType, enclosure, floorId: level.id, polygon: space.profile || [], elevation: level.elevation?.value ?? 0, height: ceilH2, axis: space.axis || "default", geometry_driver: { type: "planar_extrude", height: ceilH2, direction: [0, 0, 1], outline: space.profile || [] }, metadata: {} }; slabs.push(slab); allSlabs.push(slab); continue; } const centroid = mergeGroup ? mergeGroup.centroid : computeCentroid(space.profile || []); const area = mergeGroup ? mergeGroup.area : space.area?.value || 0; const ceilH = space.ceiling_height?.value || level.height?.value || 3; const declaredId = mergeGroup?.declaredId; const roomId = declaredId || space.id; const region = mergeGroup ? mergeGroup.region : space.profile || []; const program = spaceTypeToProgram(mergeGroup?.declaredType || space.type || ""); if (space.z_bounds && space.z_bounds.length >= 2) { if (processedCrossLevelSpaces.has(space.id)) continue; processedCrossLevelSpaces.add(space.id); const firstLevel = levelMap.get(space.z_bounds[0]); const lastLevel = levelMap.get(space.z_bounds[space.z_bounds.length - 1]); if (firstLevel && lastLevel) { const zMin = firstLevel.elevation; const zMax = lastLevel.elevation + lastLevel.height; const crossRoom = { identifier: space.id, display_name: space.name || space.id, source_type: "PLANAR_EXTRUDE", program_type: spaceTypeToProgram(space.type || ""), region: space.profile || [], point: computeCentroid(space.profile || []), elevation: zMin, height: zMax - zMin, floorArea: space.area?.value || 0, volume: space.metadata?.solid?.volume_m3 > 0 ? space.metadata.solid.volume_m3 : (space.area?.value || 0) * (zMax - zMin), spanFloors: space.z_bounds, enclosure: "void", axis: space.axis || "default", geometry_driver: { type: "planar_extrude", height: zMax - zMin, direction: [0, 0, 1], outline: space.profile || [] }, // metadata 不能丢:`metadata.solid`( 面集事实)是跨层异形体 // (如整体 loft 塔楼)渲染真几何的唯一来源,丢了就退化成棱柱 metadata: { ...space.metadata?.solid ? { solid: space.metadata.solid } : {} } }; allRooms.push(crossRoom); rooms.push(space.id); continue; } warnings.push( `\u7A7A\u95F4 "${space.id}" \u7684 z_bounds \u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 level\uFF08${space.z_bounds.join(" \u2192 ")}\uFF09\uFF0C\u5DF2\u964D\u7EA7\u4E3A\u666E\u901A\u5355\u5C42\u623F\u95F4` ); } let apertureIds = []; const memberApertureIds = /* @__PURE__ */ new Map(); if (mergeGroup) { const memberIds = new Set(mergeGroup.members.map((m3) => m3.id)); for (const member of mergeGroup.members) { const others = mergeGroup.members.filter((m3) => m3.id !== member.id); const dropIfInsideGroup = (bProfile, boundary) => { const rawNeighbor = boundary?.metadata?.neighbor_id; const neighbors = typeof rawNeighbor === "string" ? rawNeighbor.split(",").map((n5) => n5.trim()).filter(Boolean) : []; if (neighbors.length === 1 && memberIds.has(neighbors[0])) return true; return others.some((o3) => isSharedBoundary(bProfile, o3.profile || [])); }; const ids = collectSpaceApertures(member, roomId, level, dropIfInsideGroup); memberApertureIds.set(member.id, ids); apertureIds.push(...ids); } } else { apertureIds = collectSpaceApertures(space, roomId, level); } const room = { identifier: roomId, display_name: mergeGroup?.declaredName || space.name || roomId, source_type: "PLANAR_EXTRUDE", parent: level.id, program_type: isBalcony ? "balcony" : program, // 构造集选择:GSA 侧未识别属性统一落入 metadata(key 为 snake_case), // 房间级优先于整栋级;未声明时保持 undefined,由下游按气候区回退选集 construction_set_id: space.metadata?.construction_set ?? space.construction_set_id ?? void 0, apertures: apertureIds, shades: [], patio: isBalcony, main_zone: true, region, point: centroid, area, // 面积/体积口径:solid 空间取面集真值(体积=build123d 实体、 // 面积=含内环的真 footprint),取不到才回退棱柱估算 volume: space.metadata?.solid?.volume_m3 > 0 ? space.metadata.solid.volume_m3 : area * ceilH, ...space.metadata?.solid?.footprint_area_m2 > 0 ? { area: space.metadata.solid.footprint_area_m2 } : {}, daylight_height: ceilH, axis: space.axis || "default", geometry_driver: { type: "planar_extrude", height: ceilH, direction: [0, 0, 1], outline: region }, // 合并组:记录组成 space 完整信息,供 Building→AML 回写展开为多个独立 // 拆分容器:children room 记录 parent_space,供回写还原父容器声明 metadata: { // 复杂形体()面集事实与**可渲染面环**透传:前端按面三角化即可 // 画出真实外形(曲屋面/扭转面),而不是 profile 的棱柱近似。 ...space.metadata?.solid ? { solid: space.metadata.solid } : {}, // parent_id 有两种语义:GSA 后处理把"所属 level"也写进 parent_id // (postprocess: space.parent_id = level.id),只有指向真实拆分容器 // (level.containers)时才映射 parent_space——否则回写会虚构出 // 与 level 同 id 的 容器(PARSE-DSL-002 id 冲突) ...space.parent_id && containerDecl.has(space.parent_id) ? { parent_space: space.parent_id } : {}, ...space.parent_id && containerDecl.get(space.parent_id)?.name ? { parent_name: containerDecl.get(space.parent_id).name } : {}, ...space.parent_id && containerDecl.get(space.parent_id)?.type ? { parent_type: containerDecl.get(space.parent_id).type } : {}, ...mergeGroup ? { ...declaredId ? { declared_room: true } : {}, ...declaredId && mergeGroup.declaredType ? { merged_room_type: mergeGroup.declaredType } : {}, merged_space_ids: mergeGroup.members.map((m3) => m3.id), merged_spaces: mergeGroup.members.map((m3) => ({ id: m3.id, name: m3.name, type: m3.type, profile: m3.profile || [], area: m3.area?.value || 0, aperture_ids: memberApertureIds.get(m3.id) ?? [] })) } : {} } }; allRooms.push(room); rooms.push(roomId); } return { identifier: level.id, display_name: level.name || `Floor ${si2 + 1}`, base_point: [0, 0, level.elevation?.value ?? 0], story: si2, height: level.height?.value ?? 3, repeat: 1, rooms: rooms.map( (id) => allRooms.find((r4) => r4.identifier === id) ), slabs, outline, // 模板克隆楼层写入溯源标记;显式楼层保持 undefined ...templateMetaByLevel.has(level) ? { metadata: templateMetaByLevel.get(level) } : {} }; }); const roomFloorMap = /* @__PURE__ */ new Map(); floors.forEach((f2, fi2) => { (f2.rooms || []).forEach((r4) => { if (r4?.identifier) roomFloorMap.set(r4.identifier, fi2); }); }); const floorsWithAps = floors.map((f2, fi2) => ({ ...f2, apertures: allApertures.filter( (a3) => (a3.rooms || []).some((rid) => roomFloorMap.get(rid) === fi2) ) })); function mapDoteSystem(src) { if (!src?.dimensions) return void 0; const pOrg = src.placement?.origin; const sysOrigin = pOrg ? [pOrg[0] ?? 0, pOrg[1] ?? 0] : void 0; return { id: src.id, ref_system: src.ref_system, placement: src.placement ? { origin: src.placement.origin || [0, 0, 0], rotation: src.placement.rotation?.value ?? src.placement.rotation } : void 0, dimensions: src.dimensions.map((dim) => ({ id: dim.id, labels: dim.labels, spacings: (dim.spacings || []).map((s2) => s2.value ?? s2), angle: dim.angle?.value ?? (dim.angle === "0deg" ? 0 : dim.angle ?? 0), dim_type: dim.dim_type || "cartesian", ...dim.origin ? { origin: dim.origin } : sysOrigin ? { origin: sysOrigin } : {} })) }; } const designReference = {}; const anyDoteBounds = (gsa.levels || []).some((l13) => (l13.spaces || []).some((s2) => s2.dote_bounds || (s2.boundaries || []).some((b5) => b5.dote_bounds))); const isSynthGrid = (ds2) => ds2?.id === "AUTO-DOTE" && !anyDoteBounds; if (gsa.dote_system && !isSynthGrid(gsa.dote_system)) designReference.dote_system = mapDoteSystem(gsa.dote_system); if (gsa.dote_systems) { designReference.dote_systems = {}; for (const [id, ds2] of Object.entries(gsa.dote_systems)) { if (isSynthGrid(ds2)) continue; const mapped = mapDoteSystem(ds2); if (mapped) designReference.dote_systems[id] = mapped; } } const findParam = (name24) => { const p2 = gsa.params; if (Array.isArray(p2)) { return p2.find((x4) => String(x4?.name || "").toUpperCase() === name24)?.value; } if (p2 && typeof p2 === "object") { const hit = Object.entries(p2).find(([k]) => k.toUpperCase() === name24)?.[1]; return hit && typeof hit === "object" && "value" in hit ? hit.value : hit; } return void 0; }; const parseNum = (v2) => { const n5 = parseFloat(String(v2 ?? "").replace(/[a-z]+/gi, "")); return Number.isFinite(n5) ? n5 : 0; }; const northAngle = parseNum(findParam("NORTH_ANGLE")); const siteBasePoint = (() => { const v2 = findParam("SITE_BASE_POINT"); if (v2 == null) return [0, 0, 0]; if (Array.isArray(v2)) return [parseNum(v2[0]), parseNum(v2[1]), parseNum(v2[2])]; const parts = String(v2).split(/[,,\s]+/).filter(Boolean); return [parseNum(parts[0]), parseNum(parts[1]), 0]; })(); return { version: "0.1.0", identifier: gsa.id || `BLD-${genId()}`, display_name: gsa.name || "GSA Building", // 整栋构造集选择(AML 以 construction-set 声明,编译前经 BSS 亦可注入) construction_set_id: gsa.metadata?.construction_set ?? gsa.construction_set_id ?? null, site_base_point: siteBasePoint, north_angle: northAngle, floors: floorsWithAps, rooms: allRooms, slabs: allSlabs, apertures: allApertures, mass_entities: [], masses: [], shades: [], global_settings: {}, ...warnings.length > 0 ? { warnings } : {}, ...Object.keys(designReference).length > 0 ? { axis_system: designReference } : {} }; } async function compileAml(aml, options) { const sanitizedAml = aml.replace(/\\([\\`*_{}\[\]()#+\-.!|>])/g, "$1"); const missingScripts = missingSolidScriptPaths(sanitizedAml, options?.solidScripts); if (missingScripts.length) { const err2 = new Error(formatMissingSolidScripts(missingScripts)); err2.gsaCompileError = true; throw err2; } const url2 = `${options?.gsaUrl || "http://localhost:8000"}/api/v1/compile`; const body = { aml: sanitizedAml, bss: options?.bss || void 0, rules: options?.rules || void 0, behaviors: options?.behaviors || void 0, // 工作区几何脚本( 的内容,按相对路径携带: // workspace 云工作区的脚本不依赖 GSA 服务器本地文件) solid_scripts: options?.solidScripts || void 0, lod: options?.lod ?? 200 }; if (options?.compileLevel) body.compile_level = options.compileLevel; if (options?.minPassageWidth !== void 0) body.min_passage_width = options.minPassageWidth; try { const res = await fetch(url2, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), // 复杂形体( 按层切分后 N 个空间各自求值)编译可到分钟级, // 30s 会把大模型误杀在响应前(实测 10 空间分层塔 ~100s); // 缓存冷(脚本哈希变化/清缓存)时曲面轮廓摊成数百墙段, // 求解+审计再翻倍(实测 marilyn 冷编译 >180s 被 180s 默认误杀),放宽到 8min signal: AbortSignal.timeout(options?.timeoutMs ?? 48e4) }); if (!res.ok) { const text2 = await res.text().catch(() => ""); let payload = null; try { payload = JSON.parse(text2); } catch { } if (payload?.status === "budget_exceeded") { const budgetErr = new Error( `${payload.message || text2.slice(0, 300)}\uFF08\u63D0\u793A\uFF1A\u8BE5\u6B21\u7F16\u8BD1\u4ECD\u5728\u670D\u52A1\u7AEF\u540E\u53F0\u7EE7\u7EED\uFF0C\u7A0D\u540E\u91CD\u8BD5\u540C\u4E00\u8F93\u5165\u53EF\u76F4\u63A5\u547D\u4E2D\u4F1A\u8BDD\u7F13\u5B58\uFF0C\u65E0\u9700\u91CD\u65B0\u6392\u961F\u7B49\u5B8C\u6574\u65F6\u957F\uFF1B\u670D\u52A1\u7AEF\u8FD0\u884C\u6001\u89C1 GET /api/v1/compile/status\uFF09` ); budgetErr.gsaCompileError = true; throw budgetErr; } throw new Error(`HTTP ${res.status}: ${text2.slice(0, 200)}`); } const response = await res.json(); return { ...response, params: response.params || [] }; } catch (err2) { if (err2?.gsaCompileError) throw err2; if (err2?.name === "TimeoutError" || err2?.name === "AbortError") { const secs = Math.round((options?.timeoutMs ?? 48e4) / 1e3); throw new Error( `GSA \u7F16\u8BD1\u5BA2\u6237\u7AEF\u7B49\u5F85\u8D85\u65F6\uFF08${secs}s\uFF0C\u672A\u6536\u5230\u670D\u52A1\u7AEF\u9884\u7B97\u54CD\u5E94\uFF09\u2014\u2014\u670D\u52A1\u7AEF\u53EF\u80FD\u4ECD\u5728\u7F16\u8BD1\u3002\u7A0D\u540E\u91CD\u8BD5\u540C\u4E00\u8F93\u5165\u53EF\u547D\u4E2D\u4F1A\u8BDD\u7F13\u5B58\uFF1B\u670D\u52A1\u7AEF\u8FD0\u884C\u6001\u89C1 GET /api/v1/compile/status` ); } throw new Error(`GSA \u7F16\u8BD1\u5931\u8D25: ${err2.message || String(err2)}`); } } // src/tools/experience-select.ts function entryContent(e5) { const s2 = typeof e5?.solution === "string" ? e5.solution.trim() : ""; if (s2) return s2; return typeof e5?.amlPattern === "string" ? e5.amlPattern.trim() : ""; } function formatExperienceLine(e5) { const cat = e5?.category || "experience"; const problem = typeof e5?.problem === "string" ? e5.problem.trim() : ""; const content = entryContent(e5); const effect = typeof e5?.effect === "string" && e5.effect.trim() ? `\uFF08${e5.effect.trim()}\uFF09` : ""; const body = problem && content ? `${problem} \u2192 ${content}` : problem || content; return `- [${cat}] ${body}${effect}`; } function scoreEntry(e5, query) { if (!query || query.length < 2) return 0; const q2 = query.toLowerCase(); let score = 0; const code = typeof e5?.errorCode === "string" ? e5.errorCode : ""; if (code && query.toUpperCase().includes(code)) score += 5; const tags = Array.isArray(e5?.tags) ? e5.tags : []; for (const t4 of tags) { if (typeof t4 === "string" && t4.length >= 2 && q2.includes(t4.toLowerCase())) score += 3; } const topic = typeof e5?.topic === "string" ? e5.topic.toLowerCase() : ""; if (topic && q2.includes(topic)) score += 2; const problem = typeof e5?.problem === "string" ? e5.problem.toLowerCase() : ""; if (problem && (problem.includes(q2) || problem.length >= 20 && q2.includes(problem.slice(0, 20)))) score += 1; return score; } var VACUOUS_SOLUTION = /^(编译成功|edit_source 编辑已应用|成功|ok|done)[。!!]?$/i; var CHITCHAT_WORDS = /(继续|好的?|好嘞|谢谢|嗯+|ok|okay|重启|试试|你好|hello|^hi$)/i; function looksLikeChitChat(text2) { if (typeof text2 !== "string") return false; const t4 = text2.trim(); return t4.length > 0 && t4.length <= 20 && CHITCHAT_WORDS.test(t4); } function selectExperiences(experiences, opts = {}) { if (!Array.isArray(experiences) || experiences.length === 0) return []; const maxItems = opts.maxItems ?? 5; const charBudget = opts.charBudget ?? 800; const measure = opts.measure ?? "line"; const query = (opts.query ?? "").trim(); let list = experiences.filter((e5) => { if (!e5 || typeof e5 !== "object" || !entryContent(e5)) return false; const p2 = typeof e5.problem === "string" ? e5.problem.trim() : ""; const s2 = typeof e5.solution === "string" ? e5.solution.trim() : ""; if (p2 && s2 && p2 === s2) return false; if (VACUOUS_SOLUTION.test(s2)) return false; if (looksLikeChitChat(p2)) return false; return true; }); const byKey = /* @__PURE__ */ new Map(); for (const e5 of list) { const contentKey = e5.errorCode || e5.topic || entryContent(e5).slice(0, 80) || e5.problem || ""; const key = `${e5.category || ""}|${contentKey}`; const prev = byKey.get(key); if (!prev || (e5.timestamp ?? 0) > (prev.timestamp ?? 0)) byKey.set(key, e5); } list = Array.from(byKey.values()); const scored = list.map((e5) => ({ e: e5, score: scoreEntry(e5, query) })); scored.sort((a3, b5) => b5.score - a3.score || (b5.e.timestamp ?? 0) - (a3.e.timestamp ?? 0)); const eligible = opts.failureRequiresQueryHit ? scored.filter(({ e: e5, score }) => e5.category !== "failure" || score > 0) : scored; const picked = []; let used = 0; for (const { e: e5 } of eligible) { if (picked.length >= maxItems) break; const len = measure === "json" ? JSON.stringify(e5)?.length ?? 0 : formatExperienceLine(e5).length; if (used + len > charBudget && picked.length > 0) continue; used += len; picked.push(e5); } return picked; } // src/tools/experience-inject.ts var DEFAULT_GSA_URL = "http://localhost:8000"; var MAX_SECTION_CHARS = 1500; var ERROR_CODE_RE = /^([A-Z]+-[A-Z]+-\d+|[A-Z]+-\d+)$/; function getGsaUrl() { try { if (typeof localStorage !== "undefined") { return localStorage.getItem("ant:gsa_url") || DEFAULT_GSA_URL; } } catch { } return DEFAULT_GSA_URL; } var _experiencesCache = /* @__PURE__ */ new Map(); function invalidateExperiencesCache() { _experiencesCache.clear(); } async function fetchExperiences(gsaUrl) { const cached2 = _experiencesCache.get(gsaUrl); if (cached2 !== void 0) return cached2; let experiences = []; try { const res = await fetch(`${gsaUrl}/experiences`, { signal: AbortSignal.timeout(3e3) }); if (res.ok) { const data = await res.json(); if (Array.isArray(data?.experiences)) experiences = data.experiences; } } catch { } _experiencesCache.set(gsaUrl, experiences); return experiences; } function buildExperienceSection(experiences) { if (!Array.isArray(experiences) || experiences.length === 0) return ""; const patterns = selectExperiences( experiences.filter((e5) => e5?.category === "aml_pattern"), { maxItems: 5, charBudget: Number.MAX_SAFE_INTEGER } ).filter((e5) => typeof e5.amlPattern === "string" && e5.amlPattern.trim()).map((e5) => `- ${e5.amlPattern.trim()}`); const failures = selectExperiences( experiences.filter((e5) => { if (e5?.category !== "failure") return false; const code = typeof e5?.errorCode === "string" ? e5.errorCode : ""; return ERROR_CODE_RE.test(code); }), { maxItems: 5, charBudget: Number.MAX_SAFE_INTEGER } ).map((e5) => { const code = e5.errorCode; const summary = typeof e5.problem === "string" && e5.problem.trim() || typeof e5.message === "string" && e5.message.trim() || typeof e5.summary === "string" && e5.summary.trim() || typeof e5.title === "string" && e5.title.trim() || code; return `- ${code}: ${summary} \u2192 ${e5.solution.trim()}`; }); const successes = selectExperiences( experiences.filter((e5) => { if (e5?.category !== "success") return false; const s2 = typeof e5?.solution === "string" ? e5.solution : ""; return s2.includes(" 0) { sections.push("### \u5DF2\u77E5\u7F16\u8BD1\u9519\u8BEF\u53CA\u4FEE\u590D\u65B9\u6CD5\n" + failures.join("\n")); } if (successes.length > 0) { sections.push("### \u6210\u529F\u7ED3\u6784\u9AA8\u67B6\u53C2\u8003\n" + successes.join("\n")); } if (sections.length === 0) return ""; const header = "## \u5EFA\u7B51\u7ECF\u9A8C\u5E93\uFF08\u5386\u53F2\u7ECF\u9A8C\uFF0C\u4F9B\u53C2\u8003\uFF09\n\u4EE5\u4E0B\u4E3A\u5386\u53F2\u7ECF\u9A8C\uFF0C\u53EF\u80FD\u53CD\u6620\u65E7\u89C4\u5219\uFF1B\u95E8\u7A97\u5206\u9636\u6BB5\uFF08massing/structure \u4E0D\u5199 aperture/wwr\uFF09\u4E0E\u6A21\u677F\u590D\u7528\uFF08\u6807\u51C6\u5C42\u5FC5\u987B template+use\uFF09\u4EE5 instructions \u4E3A\u51C6"; let out = header; for (const section of sections) { const lines = section.split("\n"); let block = lines[0]; for (const line2 of lines.slice(1)) { if (out.length + block.length + line2.length + 2 > MAX_SECTION_CHARS) break; block += "\n" + line2; } if (out.length + block.length + 2 > MAX_SECTION_CHARS) break; out += "\n\n" + block; } return out === header ? "" : out; } var TYPE_ALIASES = { \u4E3B\u5367: "master", \u4E3B\u4EBA\u623F: "master", master: "master", \u5367\u5BA4: "bedroom", \u5BA2\u5385: "living", \u8D77\u5C45\u5BA4: "living", living: "living", \u53A8\u623F: "kitchen", kitchen: "kitchen", \u536B\u751F\u95F4: "bathroom", \u6D74\u5BA4: "bathroom", bathroom: "bathroom", \u9910\u5385: "dining", dining: "dining", \u9633\u53F0: "balcony", balcony: "balcony", \u4E66\u623F: "study", study: "study", \u6B21\u5367: "second", \u5BA2\u623F: "guest", guest: "guest", \u513F\u7AE5\u623F: "child", child: "child", \u7384\u5173: "entrance", \u95E8\u5385: "entrance", entrance: "entrance", \u50A8\u85CF: "storage", \u50A8\u7269: "storage", storage: "storage" }; function normalizeTypeKey(raw) { const key = String(raw ?? "").trim().toLowerCase(); if (!key) return ""; return TYPE_ALIASES[key] ?? key; } var _exampleCatalogCache = /* @__PURE__ */ new Map(); async function fetchExampleCatalog(gsaUrl) { const cached2 = _exampleCatalogCache.get(gsaUrl); if (cached2 !== void 0) return cached2; let cases = []; try { const res = await fetch(`${gsaUrl}/api/v1/examples?kind=project`, { signal: AbortSignal.timeout(5e3) }); if (res.ok) { const data = await res.json(); if (Array.isArray(data?.examples)) cases = data.examples; } } catch { } _exampleCatalogCache.set(gsaUrl, cases); return cases; } async function fetchRealExample(gsaUrl, id) { try { const res = await fetch(`${gsaUrl}/api/v1/examples/${encodeURIComponent(id)}`, { signal: AbortSignal.timeout(5e3) }); if (!res.ok) return null; return await res.json(); } catch { } return null; } function isUsableRealCase(e5) { if (e5.kind !== "project" || e5.id === "office_tower") return false; const meta = e5.meta; return !!meta && typeof meta.room_counts === "object" && meta.room_counts !== null; } function typeSimilarity(query, cand) { let inter = 0; let qTotal = 0; for (const [t4, n5] of Object.entries(query)) { qTotal += n5; inter += Math.min(n5, cand[t4] ?? 0); } const cTotal = Object.values(cand).reduce((a3, b5) => a3 + b5, 0); if (qTotal <= 0 || cTotal <= 0) return 0; return 2 * inter / (qTotal + cTotal); } function areaPenalty(query, cand) { let penalty = 0; let n5 = 0; for (const [t4, qArea] of Object.entries(query)) { const cArea = cand[t4]; if (!cArea || cArea <= 0) continue; n5 += 1; penalty += Math.min(1, Math.abs(qArea - cArea) / Math.max(qArea, cArea, 1)); } return n5 > 0 ? penalty / n5 : 0; } function scoreRealExample(query, cand) { const meta = cand.meta; if (!meta || !meta.room_counts) return -Infinity; const qCounts = query.typeCounts ?? {}; let score = 0; if (Object.keys(qCounts).length > 0) { score += 5 * typeSimilarity(qCounts, meta.room_counts); } if (query.roomCount != null && meta.rooms != null) { score -= 1.5 * Math.abs(query.roomCount - meta.rooms); } if (query.doors != null && meta.doors != null) { score -= 0.4 * Math.abs(query.doors - meta.doors); } if (query.areaM2 && Object.keys(query.areaM2).length > 0 && meta.area_m2) { score -= 2 * areaPenalty(query.areaM2, meta.area_m2); } return score; } function selectSimilarRealExamples(catalog, query, limit = 2) { return catalog.filter(isUsableRealCase).map((e5) => ({ e: e5, score: scoreRealExample(query, e5) })).filter((x4) => Number.isFinite(x4.score)).sort((a3, b5) => b5.score - a3.score).slice(0, limit).map((x4) => x4.e); } function renderRealCase(full) { const meta = full.meta ?? {}; const counts = meta.room_counts ?? {}; const typeList = Object.entries(counts).map(([t4, n5]) => `${t4}\xD7${n5}`).join("\u3001"); const stats = []; if (meta.area_m2) stats.push(`- \u9762\u79EF\u53C2\u8003\uFF08\u33A1/\u7C7B\u578B\uFF09: ${JSON.stringify(meta.area_m2)}`); if (meta.issue_profile) stats.push(`- \u8D28\u91CF\u753B\u50CF: ${JSON.stringify(meta.issue_profile)}`); const summary = [ `### ${full.id}\uFF08${meta.rooms ?? "?"} \u623F ${meta.doors ?? "?"} \u95E8 \xB7 ${typeList}\uFF09`, ...stats, "", "> \u53C2\u8003\u8981\u70B9\uFF1A\u623F\u95F4\u6784\u6210\u3001\u9762\u79EF\u6BD4\u4F8B\u4E0E\u95E8-\u5899\u62D3\u6251\uFF1B\u5750\u6807/\u623F\u95F4 id \u4E0E\u5F53\u524D\u8BBE\u8BA1\u65E0\u5173\uFF0C\u7981\u6B62\u7167\u6284\u3002" ].join("\n"); const aml = full.aml || ""; if (!aml) return summary; return `${summary} \`\`\`aml ${aml} \`\`\``; } var MAX_REAL_SECTION_CHARS = 14e3; async function buildRealExampleSection(gsaUrl, query, limit = 2) { const hasQuery = query.roomCount != null && query.roomCount > 0 || query.typeCounts && Object.keys(query.typeCounts).length > 0; if (!hasQuery) return ""; const catalog = await fetchExampleCatalog(gsaUrl); const selected = selectSimilarRealExamples(catalog, query, limit); if (selected.length === 0) return ""; const parts = []; let budget = MAX_REAL_SECTION_CHARS; for (const sel of selected) { const full = await fetchRealExample(gsaUrl, sel.id); if (!full?.aml) continue; const rendered = renderRealCase(full); if (rendered.length > budget) break; parts.push(rendered); budget -= rendered.length; } if (parts.length === 0) return ""; const queryDesc = [ query.roomCount != null ? `${query.roomCount} \u623F` : "", query.doors != null ? `${query.doors} \u95E8` : "", query.typeCounts ? Object.entries(query.typeCounts).map(([t4, n5]) => `${t4}\xD7${n5}`).join("\u3001") : "" ].filter(Boolean).join(" \xB7 "); return [ "## \u76F8\u4F3C\u771F\u5B9E\u6237\u578B\u53C2\u8003\uFF08\u81EA\u52A8\u68C0\u7D22\uFF0C\u6BD4\u4F8B/\u62D3\u6251\u5148\u9A8C\uFF09", queryDesc ? `\u68C0\u7D22\u4F9D\u636E\uFF1A${queryDesc}` : "", "", ...parts ].join("\n"); } // src/tools/skill-sources.ts function mergeSkillDefaultSources(skills) { const out = {}; for (const skill of skills || []) { const src = skill?.sources; if (!src) continue; if (out.bss === void 0 && src.bss !== void 0) out.bss = src.bss; if (out.rules === void 0 && src.rules !== void 0) out.rules = src.rules; if (out.behaviors === void 0 && src.behaviors !== void 0) out.behaviors = src.behaviors; } return out; } // src/tools/analyze.gsa.ts async function resolveAnalysisSources(ctx, params) { let host2; if (ctx.getCurrentSources) { try { host2 = await ctx.getCurrentSources(); } catch { } } const defaults = mergeSkillDefaultSources(ctx.skills); const out = { aml: params.aml || host2?.aml, rules: params.rules || host2?.rules || defaults.rules, bss: params.bss || host2?.bss || defaults.bss, behaviors: params.behaviors || host2?.behaviors || defaults.behaviors }; if (!out.aml && ctx.getCurrentAml) { try { const cur = await ctx.getCurrentAml(); if (cur) out.aml = cur; } catch { } } return out; } async function compileForAnalysis(ctx, params) { const src = await resolveAnalysisSources(ctx, params); if (!src.aml) { throw new Error("\u65E0\u53EF\u7528 AML\uFF1A\u8BF7\u5148\u7F16\u5199\u5E76 apply_design \u7F16\u8BD1\uFF0C\u6216\u4F20\u5165 aml \u53C2\u6570\u3002"); } const gsaUrl = params.gsaUrl || getGsaUrl(); const { scripts, problems } = await collectSolidScripts(src.aml, ctx.getWorkspaceFile); if (problems.length) { throw new Error( " \u51E0\u4F55\u811A\u672C\u672A\u5C31\u7EEA\uFF0C\u5DF2\u4E2D\u6B62\u7F16\u8BD1\uFF08\u907F\u514D\u9759\u9ED8\u964D\u7EA7\u4E3A\u65E0\u5B9E\u4F53\u51E0\u4F55\uFF09\uFF1A\n- " + problems.join("\n- ") ); } const res = await compileAml(src.aml, { gsaUrl, bss: src.bss, rules: src.rules, behaviors: src.behaviors, compileLevel: params.compile_level ?? "full", ...Object.keys(scripts).length ? { solidScripts: scripts } : {} }); return { issues: res.issues || [], quality_gate: res.quality_gate, lint_result: res.lint_result, // 规则报告需要 AML 文本判 selector 是否命中;随编译一并带出,避免二次解析源码 amlText: src.aml }; } var SEVERITY_ORDER = ["fatal", "error", "warning", "info", "other"]; function severityName(s2) { const v2 = (s2 || "").toLowerCase(); return SEVERITY_ORDER.includes(v2) ? v2 : "other"; } function aggregateIssues(issues) { const bySeverity = { fatal: 0, error: 0, warning: 0, info: 0, other: 0 }; const byCode = /* @__PURE__ */ new Map(); for (const issue2 of issues) { const sev = severityName(issue2.severity); bySeverity[sev]++; const code = issue2.code || "(\u65E0 code)"; const g2 = byCode.get(code) || { code, severity: sev, count: 0, targets: [] }; g2.count++; if (sev === "fatal" || sev === "error") g2.severity = sev; if (!g2.title && issue2.title) g2.title = issue2.title; if (!g2.message && issue2.message) g2.message = issue2.message; if (!g2.suggested_fix && issue2.suggested_fix) g2.suggested_fix = issue2.suggested_fix; if (!g2.fix_strategy && issue2.fix_strategy) g2.fix_strategy = issue2.fix_strategy; if (issue2.target_id && !g2.targets.includes(issue2.target_id)) g2.targets.push(issue2.target_id); for (const t4 of issue2.affected_entities || []) { if (!g2.targets.includes(t4)) g2.targets.push(t4); } byCode.set(code, g2); } const codeGroups = [...byCode.values()].sort((a3, b5) => SEVERITY_ORDER.indexOf(a3.severity) - SEVERITY_ORDER.indexOf(b5.severity) || b5.count - a3.count).slice(0, 25); return { bySeverity, codeGroups }; } async function buildGsaIssueReport(ctx, params, precompiled) { try { const compiled = precompiled; const { issues, quality_gate, lint_result } = compiled ?? await compileForAnalysis(ctx, params); const { bySeverity, codeGroups } = aggregateIssues(issues); const infoIssues = issues.filter((i4) => severityName(i4.severity) === "info").slice(0, 20).map((i4) => ({ code: i4.code, message: i4.message, target: i4.target_id })); const summary = [ `GSA \u7F16\u8BD1\u5206\u6790\uFF1Afatal ${bySeverity.fatal} / error ${bySeverity.error} / warning ${bySeverity.warning} / info ${bySeverity.info}`, quality_gate ? `\u8D28\u91CF\u95E8\u7981\uFF1A${quality_gate.status ?? "?"}\uFF08\u5C31\u7EEA\u5EA6 ${quality_gate.readiness_score ?? "?"}/100\uFF09` : "", lint_result ? `lint\uFF1A${lint_result.score ?? "?"} \u5206\uFF08${lint_result.grade ?? "?"}\uFF09` : "" ].filter(Boolean).join("\uFF1B"); return { total: issues.length, by_severity: bySeverity, quality_gate, lint_result: lint_result ? { score: lint_result.score, grade: lint_result.grade } : void 0, code_groups: codeGroups, info_issues: infoIssues, summary, hint: "fatal/error \u9700\u4FEE\u590D\uFF1Bwarning \u5EFA\u8BAE\u5904\u7406\uFF1Binfo \u4E3A\u63D0\u793A\u6027\u4FE1\u606F\uFF08\u5982\u81EA\u52A8 void \u586B\u5145\u3001\u515C\u5E95\u5B9A\u4F4D\uFF09\u3002\u6309 code_groups \u7684 suggested_fix \u7528 edit_source \u5B9A\u5411\u4FEE\u590D\u3002" }; } catch (err2) { return { error: err2 instanceof Error ? err2.message : String(err2), hint: "\u8BF7\u786E\u8BA4 GSA \u670D\u52A1\u53EF\u7528\uFF08\u672C\u5730 localhost:8000 \u6216\u5BBF\u4E3B\u914D\u7F6E\u7684 gsaUrl\uFF09\uFF0C\u5E76\u5DF2\u6709\u5F53\u524D AML\u3002" }; } } function parseSelector(selector) { const tagMatch = /^\s*([a-zA-Z][a-zA-Z0-9-]*)/.exec(selector); const tag = tagMatch?.[1] || ""; const typeMatch = /type\s*=\s*['"]([^'"]+)['"]/.exec(selector); return { tag, type: typeMatch?.[1] }; } function selectorActive(aml, selector) { const { tag, type } = parseSelector(selector); if (!tag) return false; if (type) { const re2 = new RegExp(`<${tag}\\b[^>]*\\btype=["']${type}["']`, "i"); return re2.test(aml); } return new RegExp(`<${tag}\\b`, "i").test(aml); } async function buildRulesComplianceReport(ctx, params, precompiled) { try { const defaults = mergeSkillDefaultSources(ctx.skills); const rulesText = params.rules || defaults.rules; if (!rulesText) { return { error: "\u6CA1\u6709\u53EF\u7528\u7684 rules.yml\uFF08\u5F53\u524D skill \u672A\u63D0\u4F9B\u9ED8\u8BA4\u6821\u9A8C\u89C4\u5219\uFF0C\u4E5F\u672A\u4F20 rules \u53C2\u6570\uFF09\u3002", hint: "design-arch \u9ED8\u8BA4\u89C4\u5219\uFF1ASTRUCT-GRID-ALIGNED\uFF08\u67F1\u5BF9\u9F50\u8F74\u7F51\uFF09\u3001ENVELOPE-WINDOW-SPAN\uFF08\u7A97\u5BBD\u5F02\u5E38\uFF09\u3002" }; } const issues = precompiled?.issues ?? (await compileForAnalysis(ctx, params)).issues; let rules = []; try { const data = load(rulesText); rules = Array.isArray(data?.rules) ? data.rules : []; } catch { return { error: "rules.yml \u89E3\u6790\u5931\u8D25\uFF1A\u4E0D\u662F\u5408\u6CD5 YAML\u3002" }; } if (rules.length === 0) { return { error: "rules.yml \u4E2D\u6CA1\u6709 rules \u5B9A\u4E49\u3002", hint: "\u683C\u5F0F\uFF1Arules: [{id, description, selector, condition, action, message, priority}]" }; } const amlText = precompiled?.amlText ?? params.aml ?? (await resolveAnalysisSources(ctx, params)).aml ?? ""; const violatedIds = new Set(issues.filter((i4) => i4.rule_id).map((i4) => i4.rule_id)); const ruleResults = rules.map((rule) => { const id = rule.id || ""; const active2 = selectorActive(amlText, rule.selector || ""); const violated2 = active2 && (id ? violatedIds.has(id) : false); const violation = issues.find((i4) => i4.rule_id === id); return { id: id || "(\u672A\u547D\u540D)", description: rule.description || "", action: (rule.action || rule.severity || "error").toLowerCase(), priority: rule.priority ?? 100, status: !active2 ? "skipped" : violated2 ? "violated" : "passed", reason: !active2 ? "AML \u4E2D\u65E0\u8BE5 selector \u5339\u914D\u7684\u5B9E\u4F53" : void 0, message: violation?.message || (violated2 ? rule.message : void 0), suggested_fix: violation?.suggested_fix, targets: violation ? violation.target_id ? [violation.target_id] : violation.affected_entities || [] : void 0 }; }); const passed = ruleResults.filter((r4) => r4.status === "passed").length; const violated = ruleResults.filter((r4) => r4.status === "violated").length; const skipped = ruleResults.filter((r4) => r4.status === "skipped").length; const active = passed + violated; const score = active > 0 ? Math.round(passed / active * 100) : void 0; return { score, active_count: active, passed_count: passed, violated_count: violated, skipped_count: skipped, rules: ruleResults, summary: score !== void 0 ? `\u89C4\u5219\u5339\u914D\u5EA6 ${score}/100\uFF08${passed}/${active} \u6761\u901A\u8FC7\uFF0C${violated} \u6761\u8FDD\u53CD\uFF0C${skipped} \u6761\u65E0\u5339\u914D\u5B9E\u4F53\u8DF3\u8FC7\uFF09` : `\u65E0\u5339\u914D\u5B9E\u4F53\u7684\u89C4\u5219\u53EF\u8BC4\u4F30\uFF08${skipped} \u6761\u5168\u90E8\u8DF3\u8FC7\uFF09`, hint: "violated \u89C4\u5219\u6309 message/suggested_fix \u7528 edit_source \u5B9A\u5411\u4FEE\u590D\u540E\u91CD\u65B0\u7F16\u8BD1\uFF1B\u89C4\u5219\u7531 GSA \u7F16\u8BD1\u7AEF\u8BC4\u4F30\uFF0Cscore \u53EA\u53CD\u6620\u5F53\u524D\u7F16\u8BD1\u7ED3\u679C\u3002" }; } catch (err2) { return { error: err2 instanceof Error ? err2.message : String(err2), hint: "\u8BF7\u786E\u8BA4 GSA \u670D\u52A1\u53EF\u7528\u5E76\u5DF2\u6709\u5F53\u524D AML\u3002" }; } } // src/tools/validate.model.ts var validateModelContextSchema = external_exports2.custom(); var GEOMETRY_CHECKS = ["overlap", "aperture", "lighting", "navigation", "circulation", "boundary"]; var isGeometryCheck = (v2) => GEOMETRY_CHECKS.includes(v2); function createValidateModel() { return tool({ description: '\u6821\u9A8C\u5F53\u524D\u5EFA\u7B51\u6A21\u578B\u2014\u2014**\u4E09\u7C7B\u89C6\u56FE\u4E00\u6B21\u51FA**\uFF0C\u6570\u636E\u6E90\u5747\u4E3A GSA\uFF1A\u2460 \u51E0\u4F55/\u8BED\u4E49\uFF08\u623F\u95F4\u91CD\u53E0\u3001\u7A97\u8D8A\u754C/\u4E0D\u843D\u5728\u5899\u4E0A\u3001\u65E0\u7A97\u623F\u95F4\u3001\u53EF\u8FBE\u6027\u3001\u6D41\u7EBF\uFF09\uFF1B\u2461 \u7F16\u8BD1 issue \u5206\u7C7B\uFF08fatal/error/warning/info \u8BA1\u6570\u3001\u6309 code \u5206\u7EC4\u7ED9\u4FEE\u590D\u5EFA\u8BAE\u3001quality_gate \u4E0E lint \u8BC4\u5206\u2014\u2014**info \u7EA7\u63D0\u793A\u53EA\u5728\u8FD9\u91CC\u53EF\u89C1**\uFF0Capply_design \u7ED3\u679C\u4E0D\u900F\u51FA\uFF09\uFF1B\u2462 rules.yml \u89C4\u5219\u5408\u89C4\uFF08\u6BCF\u6761\u89C4\u5219 passed/violated/skipped + \u5408\u89C4\u5F97\u5206\uFF09\u3002\u4E09\u7C7B\u5171\u7528\u540C\u4E00\u6B21\u7F16\u8BD1\uFF0C\u8981\u51E0\u7C7B\u5C31\u4E00\u6B21\u8981\u9F50\uFF0C\u4E0D\u8981\u5206\u5F00\u8FDE\u8C03\u3002apply_design \u7F16\u8BD1\u524D\u9884\u68C0\u6216\u7528\u6237\u95EE"\u6A21\u578B\u6709\u6CA1\u6709\u95EE\u9898/\u5408\u4E0D\u5408\u89C4"\u65F6\u4F7F\u7528\u3002', inputSchema: external_exports2.object({ checks: external_exports2.array(external_exports2.enum(["overlap", "aperture", "lighting", "navigation", "circulation", "boundary", "issues", "rules"])).optional().describe("\u6821\u9A8C\u7EF4\u5EA6\uFF08\u7F3A\u7701 = \u516D\u9879\u51E0\u4F55\u68C0\u67E5 + issues\uFF09\u3002\u524D\u516D\u9879\u662F\u51E0\u4F55/\u8BED\u4E49\u5B50\u96C6\uFF1Bissues = \u7F16\u8BD1 issue \u5206\u7C7B + quality_gate + lint\uFF1Brules = rules.yml \u5408\u89C4\u8BC4\u5206\u3002\u540E\u4E24\u9879\u4E0E\u51E0\u4F55\u68C0\u67E5\u5171\u7528\u4E00\u6B21\u7F16\u8BD1"), aml: external_exports2.string().optional().describe("\u8981\u6821\u9A8C\u7684 AML\uFF08\u7F3A\u7701\u53D6\u5BBF\u4E3B\u5F53\u524D AML\uFF1B\u8FDC\u7A0B\u5F62\u6001\u7ECF push_project \u843D\u5230\u5DE5\u4F5C\u533A\uFF09"), rules: external_exports2.string().optional().describe("rules.yml \u5168\u6587\uFF08\u4EC5 checks \u542B rules \u65F6\u7528\uFF1B\u7F3A\u7701\u53D6\u5F53\u524D skill \u7684\u9ED8\u8BA4\u6821\u9A8C\u89C4\u5219\uFF09"), level: external_exports2.enum(["massing", "structure", "full"]).optional().describe("\u7F16\u8BD1\u9636\u6BB5\uFF08\u7F3A\u7701\u81EA\u52A8\u89E3\u6790\uFF1A\u6D41\u7A0B\u72B6\u6001 vars.stage > designStep \u63A8\u5BFC\uFF09\uFF1Amassing/structure \u8FDE\u901A\u6027\u6309\u5171\u4EAB\u8FB9\u9608\u503C\u5224\u5B9A\uFF0Cfull \u6309\u95E8\u5224\u5B9A\u3002\u9636\u6BB5\u4E0D\u5339\u914D\u4F1A\u4EA7\u751F\u5927\u91CF\u53EF\u8FBE\u6027\u8BEF\u62A5"), min_passage_width: external_exports2.number().positive().optional().describe("massing/structure \u9636\u6BB5\u8FDE\u901A\u6027\u5224\u5B9A\u7684\u6700\u5C0F\u5171\u4EAB\u8FB9\u5BBD\u5EA6\uFF08\u7C73\uFF09\uFF0C\u9ED8\u8BA4 0.9\uFF1B\u4E24\u7A7A\u95F4\u5171\u4EAB\u8FB9 \u2265 \u8BE5\u503C\u5373\u89C6\u4E3A\u53EF\u901A\u884C"), gsaUrl: external_exports2.string().optional().describe("GSA \u670D\u52A1\u5730\u5740\uFF08\u9ED8\u8BA4 http://localhost:8000\uFF09") }), contextSchema: validateModelContextSchema, execute: (async (params, { context }) => { if (!context.getCurrentAml && !context.getCurrentSources) { return { status: "unavailable", message: "\u5BBF\u4E3B\u672A\u6CE8\u5165 AML \u901A\u9053\uFF08getCurrentAml / getCurrentSources\uFF09\uFF0C\u65E0\u6CD5\u6821\u9A8C\u6A21\u578B\u3002" }; } const requested = params.checks; const wantsGeometry = !requested || requested.some((c2) => isGeometryCheck(c2)); const geometryChecks = requested ? requested.filter(isGeometryCheck) : void 0; const wantsIssues = !requested || requested.includes("issues"); const wantsRules = !!requested?.includes("rules"); const compileLevel = resolveCompileStage(context.sessionParts, params.level, context.designStep); try { let aml = params.aml || ""; if (!aml && context.getCurrentAml) { try { aml = await context.getCurrentAml() || ""; } catch { } } if (!aml && context.getCurrentSources) { try { aml = (await context.getCurrentSources())?.aml || ""; } catch { } } if (!aml) { return { status: "no_data", message: "\u5F53\u524D\u6CA1\u6709 AML \u6570\u636E\u3002\u8BF7\u5148\u751F\u6210\u6216\u52A0\u8F7D\u65B9\u6848\u3002" }; } let geometry; if (wantsGeometry) { geometry = await validateModel(aml, { gsaUrl: params.gsaUrl, checks: geometryChecks, minPassageWidth: params.min_passage_width, compileLevel }); context.toolContext?.lastResults?.set("validate-model", geometry); } let compiled; if (wantsIssues || wantsRules) { compiled = await compileForAnalysis(context, { aml, rules: params.rules, compile_level: params.level ?? compileLevel, gsaUrl: params.gsaUrl }); } const compileReport = wantsIssues ? await buildGsaIssueReport(context, {}, compiled) : void 0; const rulesReport = wantsRules ? await buildRulesComplianceReport(context, { aml, rules: params.rules }, compiled ? { issues: compiled.issues, amlText: compiled.amlText } : void 0) : void 0; const severity = compileReport?.by_severity; const blockingIssues = severity ? (severity.fatal ?? 0) + (severity.error ?? 0) : 0; const valid = (geometry ? geometry.valid !== false : true) && blockingIssues === 0; const summaryLines = [ geometry ? `\u51E0\u4F55\u6821\u9A8C\uFF1A${geometry.valid ? "\u901A\u8FC7" : "\u6709\u95EE\u9898"}\uFF08${geometry.issues.length} \u6761\uFF09` : "", compileReport && !compileReport.error ? String(compileReport.summary) : "", rulesReport && !rulesReport.error ? String(rulesReport.summary) : "" ].filter(Boolean); return { status: "success", valid, overview: summaryLines.join("\uFF1B"), // 向后兼容:valid / summary / issues 保持原有几何语义(summary 是对象,不是字符串) ...geometry ? { summary: geometry.summary || { total: geometry.issues.length }, geometry: { valid: geometry.valid, summary: geometry.summary || { total: geometry.issues.length }, issues: geometry.issues }, issues: geometry.issues } : {}, ...compileReport ? { compile: compileReport } : {}, ...rulesReport ? { rules: rulesReport } : {}, hint: "fatal/error \u4E0E\u51E0\u4F55\u95EE\u9898\u9700\u4FEE\u590D\u540E\u91CD\u65B0\u7F16\u8BD1\uFF1Binfo \u4E3A\u63D0\u793A\u6027\u4FE1\u606F\uFF08\u81EA\u52A8 void \u586B\u5145\u3001\u515C\u5E95\u5B9A\u4F4D\u7B49\uFF09\u3002\u6309 compile.code_groups \u6216 rules.rules \u7684 suggested_fix \u7528 AML \u5DE5\u5177\u5B9A\u5411\u4FEE\u590D\u3002" }; } catch (err2) { return { status: "error", message: `\u6A21\u578B\u6821\u9A8C\u5931\u8D25: ${err2?.message ?? String(err2)}` }; } }) }); } // node_modules/@ringoarch/ant-climate/dist/index.js function Mn(l13) { let e5 = l13.split(/\r?\n/); if (e5.length < 8) throw new Error("EPW file is too short/invalid."); let n5 = e5[0].split(","); if (n5[0].toUpperCase() !== "LOCATION") throw new Error("Invalid EPW format: Missing LOCATION header."); let i4 = { location: n5[1], state: n5[2], country: n5[3], dataSource: n5[4], wmo: n5[5], latitude: parseFloat(n5[6]), longitude: parseFloat(n5[7]), timeZone: parseFloat(n5[8]), elevation: parseFloat(n5[9]) }, s2 = 8, r4 = [], a3 = [], c2 = 2005; for (let h2 = s2; h2 < e5.length; h2++) { let u2 = e5[h2].trim(); if (!u2) continue; let d2 = u2.split(","); if (d2.length < 20) continue; let f2 = true, m3 = parseInt(d2[4]); (isNaN(m3) || m3 < 0 || m3 > 60) && (f2 = false); let p2 = f2 ? 0 : -1, _2 = parseInt(d2[0]), g2 = parseInt(d2[1]), v2 = parseInt(d2[2]), M = parseInt(d2[3]), S2 = f2 ? parseInt(d2[4]) : 0, y2 = { year: _2, month: g2, day: v2, hour: M, minute: S2, dryBulbTemperature: parseFloat(d2[6 + p2]), dewPointTemperature: parseFloat(d2[7 + p2]), relativeHumidity: parseFloat(d2[8 + p2]), atmosphericPressure: parseFloat(d2[9 + p2]), extraterrestrialHorizRad: parseFloat(d2[10 + p2]), extraterrestrialDirectNormalRad: parseFloat(d2[11 + p2]), horizInfraredRadSky: parseFloat(d2[12 + p2]), globalHorizontalRad: parseFloat(d2[13 + p2]), directNormalRad: parseFloat(d2[14 + p2]), diffuseHorizontalRad: parseFloat(d2[15 + p2]), globalHorizIlluminance: parseFloat(d2[16 + p2]), directNormalIlluminance: parseFloat(d2[17 + p2]), diffuseHorizIlluminance: parseFloat(d2[18 + p2]), zenithLuminance: parseFloat(d2[19 + p2]), windDirection: parseFloat(d2[20 + p2]), windSpeed: parseFloat(d2[21 + p2]), totalSkyCover: parseFloat(d2[22 + p2]), opaqueSkyCover: parseFloat(d2[23 + p2]), visibility: parseFloat(d2[24 + p2]), ceilingHeight: parseFloat(d2[25 + p2]), presentWeatherObservation: parseFloat(d2[26 + p2]), presentWeatherCodes: parseFloat(d2[27 + p2]), precipitableWater: parseFloat(d2[28 + p2]), aerosolOpticalDepth: parseFloat(d2[29 + p2]), snowDepth: parseFloat(d2[30 + p2]), daysSinceLastSnow: parseFloat(d2[31 + p2]) }; r4.push(y2); let A2 = new Date(Date.UTC(c2, g2 - 1, v2, M, S2)); a3.push(A2); } return { header: i4, rows: r4, getColumn: (h2) => r4.map((u2) => u2[h2]), dates: a3 }; } var Nt; (function(l13) { l13.NORTH = "NORTH", l13.SOUTH = "SOUTH", l13.EAST = "EAST", l13.WEST = "WEST", l13.ROOF = "ROOF"; })(Nt || (Nt = {})); var Ee = Math.PI; var Ut = 180 / Ee; var Fe = Ee / 180; var tn = 1; var nn = 3; var Xe = 0; var qe = 1; var Ye = 2; var Ze = 3; var Je = 4; var $e = 5; var Ke = 6; var Qe = 7; var sn = 0; var rn = 1; var an = 2; var yt = 1; var Mt = 2; var St = 3; var bt = 4; var Tt = 5; var Et = 6; var At = 7; var on = 300; var ln = 301; var wt = 302; var cn = 306; var je = 1e3; var ge = 1001; var et = 1002; var hn = 1006; var un = 1008; var dn = 1009; var fn = 1023; var Pe = 2300; var tt = 2301; var Oe = 2302; var Ot = 2303; var Bt = 2400; var zt = 2401; var Vt = 2402; var Ct = ""; var X = "srgb"; var nt = "srgb-linear"; var it = "linear"; var Ie = "srgb"; var _e = 2e3; var kt = 2001; function Dn(l13) { return ArrayBuffer.isView(l13) && !(l13 instanceof DataView); } function st(l13) { return document.createElementNS("http://www.w3.org/1999/xhtml", l13); } var Gt = {}; var De = null; function pn(l13) { let e5 = l13[0]; if (typeof e5 == "string" && e5.startsWith("TSL:")) { let t4 = l13[1]; t4 && t4.isStackTrace ? l13[0] += " " + t4.getLocation() : l13[1] = 'Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'; } return l13; } function z(...l13) { l13 = pn(l13); let e5 = "THREE." + l13.shift(); if (De) De("warn", e5, ...l13); else { let t4 = l13[0]; t4 && t4.isStackTrace ? console.warn(t4.getError(e5)) : console.warn(e5, ...l13); } } function L(...l13) { l13 = pn(l13); let e5 = "THREE." + l13.shift(); if (De) De("error", e5, ...l13); else { let t4 = l13[0]; t4 && t4.isStackTrace ? console.error(t4.getError(e5)) : console.error(e5, ...l13); } } function rt(...l13) { let e5 = l13.join(" "); e5 in Gt || (Gt[e5] = true, z(...l13)); } var Ln = { [Xe]: qe, [Ye]: Ke, [Je]: Qe, [Ze]: $e, [qe]: Xe, [Ke]: Ye, [Qe]: Je, [$e]: Ze }; var xe = class { addEventListener(e5, t4) { this._listeners === void 0 && (this._listeners = {}); let n5 = this._listeners; n5[e5] === void 0 && (n5[e5] = []), n5[e5].indexOf(t4) === -1 && n5[e5].push(t4); } hasEventListener(e5, t4) { let n5 = this._listeners; return n5 === void 0 ? false : n5[e5] !== void 0 && n5[e5].indexOf(t4) !== -1; } removeEventListener(e5, t4) { let n5 = this._listeners; if (n5 === void 0) return; let i4 = n5[e5]; if (i4 !== void 0) { let s2 = i4.indexOf(t4); s2 !== -1 && i4.splice(s2, 1); } } dispatchEvent(e5) { let t4 = this._listeners; if (t4 === void 0) return; let n5 = t4[e5.type]; if (n5 !== void 0) { e5.target = this; let i4 = n5.slice(0); for (let s2 = 0, r4 = i4.length; s2 < r4; s2++) i4[s2].call(this, e5); e5.target = null; } } }; var O = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"]; var ma = Math.PI / 180; var Nn = 180 / Math.PI; function Rt() { let l13 = Math.random() * 4294967295 | 0, e5 = Math.random() * 4294967295 | 0, t4 = Math.random() * 4294967295 | 0, n5 = Math.random() * 4294967295 | 0; return (O[l13 & 255] + O[l13 >> 8 & 255] + O[l13 >> 16 & 255] + O[l13 >> 24 & 255] + "-" + O[e5 & 255] + O[e5 >> 8 & 255] + "-" + O[e5 >> 16 & 15 | 64] + O[e5 >> 24 & 255] + "-" + O[t4 & 63 | 128] + O[t4 >> 8 & 255] + "-" + O[t4 >> 16 & 255] + O[t4 >> 24 & 255] + O[n5 & 255] + O[n5 >> 8 & 255] + O[n5 >> 16 & 255] + O[n5 >> 24 & 255]).toLowerCase(); } function E(l13, e5, t4) { return Math.max(e5, Math.min(t4, l13)); } function Un(l13, e5) { return (l13 % e5 + e5) % e5; } function Be(l13, e5, t4) { return (1 - t4) * l13 + t4 * e5; } var Z = class l { static { l.prototype.isVector2 = true; } constructor(e5 = 0, t4 = 0) { this.x = e5, this.y = t4; } get width() { return this.x; } set width(e5) { this.x = e5; } get height() { return this.y; } set height(e5) { this.y = e5; } set(e5, t4) { return this.x = e5, this.y = t4, this; } setScalar(e5) { return this.x = e5, this.y = e5, this; } setX(e5) { return this.x = e5, this; } setY(e5) { return this.y = e5, this; } setComponent(e5, t4) { switch (e5) { case 0: this.x = t4; break; case 1: this.y = t4; break; default: throw new Error("index is out of range: " + e5); } return this; } getComponent(e5) { switch (e5) { case 0: return this.x; case 1: return this.y; default: throw new Error("index is out of range: " + e5); } } clone() { return new this.constructor(this.x, this.y); } copy(e5) { return this.x = e5.x, this.y = e5.y, this; } add(e5) { return this.x += e5.x, this.y += e5.y, this; } addScalar(e5) { return this.x += e5, this.y += e5, this; } addVectors(e5, t4) { return this.x = e5.x + t4.x, this.y = e5.y + t4.y, this; } addScaledVector(e5, t4) { return this.x += e5.x * t4, this.y += e5.y * t4, this; } sub(e5) { return this.x -= e5.x, this.y -= e5.y, this; } subScalar(e5) { return this.x -= e5, this.y -= e5, this; } subVectors(e5, t4) { return this.x = e5.x - t4.x, this.y = e5.y - t4.y, this; } multiply(e5) { return this.x *= e5.x, this.y *= e5.y, this; } multiplyScalar(e5) { return this.x *= e5, this.y *= e5, this; } divide(e5) { return this.x /= e5.x, this.y /= e5.y, this; } divideScalar(e5) { return this.multiplyScalar(1 / e5); } applyMatrix3(e5) { let t4 = this.x, n5 = this.y, i4 = e5.elements; return this.x = i4[0] * t4 + i4[3] * n5 + i4[6], this.y = i4[1] * t4 + i4[4] * n5 + i4[7], this; } min(e5) { return this.x = Math.min(this.x, e5.x), this.y = Math.min(this.y, e5.y), this; } max(e5) { return this.x = Math.max(this.x, e5.x), this.y = Math.max(this.y, e5.y), this; } clamp(e5, t4) { return this.x = E(this.x, e5.x, t4.x), this.y = E(this.y, e5.y, t4.y), this; } clampScalar(e5, t4) { return this.x = E(this.x, e5, t4), this.y = E(this.y, e5, t4), this; } clampLength(e5, t4) { let n5 = this.length(); return this.divideScalar(n5 || 1).multiplyScalar(E(n5, e5, t4)); } floor() { return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this; } ceil() { return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this; } round() { return this.x = Math.round(this.x), this.y = Math.round(this.y), this; } roundToZero() { return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this; } negate() { return this.x = -this.x, this.y = -this.y, this; } dot(e5) { return this.x * e5.x + this.y * e5.y; } cross(e5) { return this.x * e5.y - this.y * e5.x; } lengthSq() { return this.x * this.x + this.y * this.y; } length() { return Math.sqrt(this.x * this.x + this.y * this.y); } manhattanLength() { return Math.abs(this.x) + Math.abs(this.y); } normalize() { return this.divideScalar(this.length() || 1); } angle() { return Math.atan2(-this.y, -this.x) + Math.PI; } angleTo(e5) { let t4 = Math.sqrt(this.lengthSq() * e5.lengthSq()); if (t4 === 0) return Math.PI / 2; let n5 = this.dot(e5) / t4; return Math.acos(E(n5, -1, 1)); } distanceTo(e5) { return Math.sqrt(this.distanceToSquared(e5)); } distanceToSquared(e5) { let t4 = this.x - e5.x, n5 = this.y - e5.y; return t4 * t4 + n5 * n5; } manhattanDistanceTo(e5) { return Math.abs(this.x - e5.x) + Math.abs(this.y - e5.y); } setLength(e5) { return this.normalize().multiplyScalar(e5); } lerp(e5, t4) { return this.x += (e5.x - this.x) * t4, this.y += (e5.y - this.y) * t4, this; } lerpVectors(e5, t4, n5) { return this.x = e5.x + (t4.x - e5.x) * n5, this.y = e5.y + (t4.y - e5.y) * n5, this; } equals(e5) { return e5.x === this.x && e5.y === this.y; } fromArray(e5, t4 = 0) { return this.x = e5[t4], this.y = e5[t4 + 1], this; } toArray(e5 = [], t4 = 0) { return e5[t4] = this.x, e5[t4 + 1] = this.y, e5; } fromBufferAttribute(e5, t4) { return this.x = e5.getX(t4), this.y = e5.getY(t4), this; } rotateAround(e5, t4) { let n5 = Math.cos(t4), i4 = Math.sin(t4), s2 = this.x - e5.x, r4 = this.y - e5.y; return this.x = s2 * n5 - r4 * i4 + e5.x, this.y = s2 * i4 + r4 * n5 + e5.y, this; } random() { return this.x = Math.random(), this.y = Math.random(), this; } *[Symbol.iterator]() { yield this.x, yield this.y; } }; var te = class { constructor(e5 = 0, t4 = 0, n5 = 0, i4 = 1) { this.isQuaternion = true, this._x = e5, this._y = t4, this._z = n5, this._w = i4; } static slerpFlat(e5, t4, n5, i4, s2, r4, a3) { let c2 = n5[i4 + 0], o3 = n5[i4 + 1], h2 = n5[i4 + 2], u2 = n5[i4 + 3], d2 = s2[r4 + 0], f2 = s2[r4 + 1], m3 = s2[r4 + 2], p2 = s2[r4 + 3]; if (u2 !== p2 || c2 !== d2 || o3 !== f2 || h2 !== m3) { let _2 = c2 * d2 + o3 * f2 + h2 * m3 + u2 * p2; _2 < 0 && (d2 = -d2, f2 = -f2, m3 = -m3, p2 = -p2, _2 = -_2); let g2 = 1 - a3; if (_2 < 0.9995) { let v2 = Math.acos(_2), M = Math.sin(v2); g2 = Math.sin(g2 * v2) / M, a3 = Math.sin(a3 * v2) / M, c2 = c2 * g2 + d2 * a3, o3 = o3 * g2 + f2 * a3, h2 = h2 * g2 + m3 * a3, u2 = u2 * g2 + p2 * a3; } else { c2 = c2 * g2 + d2 * a3, o3 = o3 * g2 + f2 * a3, h2 = h2 * g2 + m3 * a3, u2 = u2 * g2 + p2 * a3; let v2 = 1 / Math.sqrt(c2 * c2 + o3 * o3 + h2 * h2 + u2 * u2); c2 *= v2, o3 *= v2, h2 *= v2, u2 *= v2; } } e5[t4] = c2, e5[t4 + 1] = o3, e5[t4 + 2] = h2, e5[t4 + 3] = u2; } static multiplyQuaternionsFlat(e5, t4, n5, i4, s2, r4) { let a3 = n5[i4], c2 = n5[i4 + 1], o3 = n5[i4 + 2], h2 = n5[i4 + 3], u2 = s2[r4], d2 = s2[r4 + 1], f2 = s2[r4 + 2], m3 = s2[r4 + 3]; return e5[t4] = a3 * m3 + h2 * u2 + c2 * f2 - o3 * d2, e5[t4 + 1] = c2 * m3 + h2 * d2 + o3 * u2 - a3 * f2, e5[t4 + 2] = o3 * m3 + h2 * f2 + a3 * d2 - c2 * u2, e5[t4 + 3] = h2 * m3 - a3 * u2 - c2 * d2 - o3 * f2, e5; } get x() { return this._x; } set x(e5) { this._x = e5, this._onChangeCallback(); } get y() { return this._y; } set y(e5) { this._y = e5, this._onChangeCallback(); } get z() { return this._z; } set z(e5) { this._z = e5, this._onChangeCallback(); } get w() { return this._w; } set w(e5) { this._w = e5, this._onChangeCallback(); } set(e5, t4, n5, i4) { return this._x = e5, this._y = t4, this._z = n5, this._w = i4, this._onChangeCallback(), this; } clone() { return new this.constructor(this._x, this._y, this._z, this._w); } copy(e5) { return this._x = e5.x, this._y = e5.y, this._z = e5.z, this._w = e5.w, this._onChangeCallback(), this; } setFromEuler(e5, t4 = true) { let n5 = e5._x, i4 = e5._y, s2 = e5._z, r4 = e5._order, a3 = Math.cos, c2 = Math.sin, o3 = a3(n5 / 2), h2 = a3(i4 / 2), u2 = a3(s2 / 2), d2 = c2(n5 / 2), f2 = c2(i4 / 2), m3 = c2(s2 / 2); switch (r4) { case "XYZ": this._x = d2 * h2 * u2 + o3 * f2 * m3, this._y = o3 * f2 * u2 - d2 * h2 * m3, this._z = o3 * h2 * m3 + d2 * f2 * u2, this._w = o3 * h2 * u2 - d2 * f2 * m3; break; case "YXZ": this._x = d2 * h2 * u2 + o3 * f2 * m3, this._y = o3 * f2 * u2 - d2 * h2 * m3, this._z = o3 * h2 * m3 - d2 * f2 * u2, this._w = o3 * h2 * u2 + d2 * f2 * m3; break; case "ZXY": this._x = d2 * h2 * u2 - o3 * f2 * m3, this._y = o3 * f2 * u2 + d2 * h2 * m3, this._z = o3 * h2 * m3 + d2 * f2 * u2, this._w = o3 * h2 * u2 - d2 * f2 * m3; break; case "ZYX": this._x = d2 * h2 * u2 - o3 * f2 * m3, this._y = o3 * f2 * u2 + d2 * h2 * m3, this._z = o3 * h2 * m3 - d2 * f2 * u2, this._w = o3 * h2 * u2 + d2 * f2 * m3; break; case "YZX": this._x = d2 * h2 * u2 + o3 * f2 * m3, this._y = o3 * f2 * u2 + d2 * h2 * m3, this._z = o3 * h2 * m3 - d2 * f2 * u2, this._w = o3 * h2 * u2 - d2 * f2 * m3; break; case "XZY": this._x = d2 * h2 * u2 - o3 * f2 * m3, this._y = o3 * f2 * u2 - d2 * h2 * m3, this._z = o3 * h2 * m3 + d2 * f2 * u2, this._w = o3 * h2 * u2 + d2 * f2 * m3; break; default: z("Quaternion: .setFromEuler() encountered an unknown order: " + r4); } return t4 === true && this._onChangeCallback(), this; } setFromAxisAngle(e5, t4) { let n5 = t4 / 2, i4 = Math.sin(n5); return this._x = e5.x * i4, this._y = e5.y * i4, this._z = e5.z * i4, this._w = Math.cos(n5), this._onChangeCallback(), this; } setFromRotationMatrix(e5) { let t4 = e5.elements, n5 = t4[0], i4 = t4[4], s2 = t4[8], r4 = t4[1], a3 = t4[5], c2 = t4[9], o3 = t4[2], h2 = t4[6], u2 = t4[10], d2 = n5 + a3 + u2; if (d2 > 0) { let f2 = 0.5 / Math.sqrt(d2 + 1); this._w = 0.25 / f2, this._x = (h2 - c2) * f2, this._y = (s2 - o3) * f2, this._z = (r4 - i4) * f2; } else if (n5 > a3 && n5 > u2) { let f2 = 2 * Math.sqrt(1 + n5 - a3 - u2); this._w = (h2 - c2) / f2, this._x = 0.25 * f2, this._y = (i4 + r4) / f2, this._z = (s2 + o3) / f2; } else if (a3 > u2) { let f2 = 2 * Math.sqrt(1 + a3 - n5 - u2); this._w = (s2 - o3) / f2, this._x = (i4 + r4) / f2, this._y = 0.25 * f2, this._z = (c2 + h2) / f2; } else { let f2 = 2 * Math.sqrt(1 + u2 - n5 - a3); this._w = (r4 - i4) / f2, this._x = (s2 + o3) / f2, this._y = (c2 + h2) / f2, this._z = 0.25 * f2; } return this._onChangeCallback(), this; } setFromUnitVectors(e5, t4) { let n5 = e5.dot(t4) + 1; return n5 < 1e-8 ? (n5 = 0, Math.abs(e5.x) > Math.abs(e5.z) ? (this._x = -e5.y, this._y = e5.x, this._z = 0, this._w = n5) : (this._x = 0, this._y = -e5.z, this._z = e5.y, this._w = n5)) : (this._x = e5.y * t4.z - e5.z * t4.y, this._y = e5.z * t4.x - e5.x * t4.z, this._z = e5.x * t4.y - e5.y * t4.x, this._w = n5), this.normalize(); } angleTo(e5) { return 2 * Math.acos(Math.abs(E(this.dot(e5), -1, 1))); } rotateTowards(e5, t4) { let n5 = this.angleTo(e5); if (n5 === 0) return this; let i4 = Math.min(1, t4 / n5); return this.slerp(e5, i4), this; } identity() { return this.set(0, 0, 0, 1); } invert() { return this.conjugate(); } conjugate() { return this._x *= -1, this._y *= -1, this._z *= -1, this._onChangeCallback(), this; } dot(e5) { return this._x * e5._x + this._y * e5._y + this._z * e5._z + this._w * e5._w; } lengthSq() { return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; } length() { return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); } normalize() { let e5 = this.length(); return e5 === 0 ? (this._x = 0, this._y = 0, this._z = 0, this._w = 1) : (e5 = 1 / e5, this._x = this._x * e5, this._y = this._y * e5, this._z = this._z * e5, this._w = this._w * e5), this._onChangeCallback(), this; } multiply(e5) { return this.multiplyQuaternions(this, e5); } premultiply(e5) { return this.multiplyQuaternions(e5, this); } multiplyQuaternions(e5, t4) { let n5 = e5._x, i4 = e5._y, s2 = e5._z, r4 = e5._w, a3 = t4._x, c2 = t4._y, o3 = t4._z, h2 = t4._w; return this._x = n5 * h2 + r4 * a3 + i4 * o3 - s2 * c2, this._y = i4 * h2 + r4 * c2 + s2 * a3 - n5 * o3, this._z = s2 * h2 + r4 * o3 + n5 * c2 - i4 * a3, this._w = r4 * h2 - n5 * a3 - i4 * c2 - s2 * o3, this._onChangeCallback(), this; } slerp(e5, t4) { let n5 = e5._x, i4 = e5._y, s2 = e5._z, r4 = e5._w, a3 = this.dot(e5); a3 < 0 && (n5 = -n5, i4 = -i4, s2 = -s2, r4 = -r4, a3 = -a3); let c2 = 1 - t4; if (a3 < 0.9995) { let o3 = Math.acos(a3), h2 = Math.sin(o3); c2 = Math.sin(c2 * o3) / h2, t4 = Math.sin(t4 * o3) / h2, this._x = this._x * c2 + n5 * t4, this._y = this._y * c2 + i4 * t4, this._z = this._z * c2 + s2 * t4, this._w = this._w * c2 + r4 * t4, this._onChangeCallback(); } else this._x = this._x * c2 + n5 * t4, this._y = this._y * c2 + i4 * t4, this._z = this._z * c2 + s2 * t4, this._w = this._w * c2 + r4 * t4, this.normalize(); return this; } slerpQuaternions(e5, t4, n5) { return this.copy(e5).slerp(t4, n5); } random() { let e5 = 2 * Math.PI * Math.random(), t4 = 2 * Math.PI * Math.random(), n5 = Math.random(), i4 = Math.sqrt(1 - n5), s2 = Math.sqrt(n5); return this.set(i4 * Math.sin(e5), i4 * Math.cos(e5), s2 * Math.sin(t4), s2 * Math.cos(t4)); } equals(e5) { return e5._x === this._x && e5._y === this._y && e5._z === this._z && e5._w === this._w; } fromArray(e5, t4 = 0) { return this._x = e5[t4], this._y = e5[t4 + 1], this._z = e5[t4 + 2], this._w = e5[t4 + 3], this._onChangeCallback(), this; } toArray(e5 = [], t4 = 0) { return e5[t4] = this._x, e5[t4 + 1] = this._y, e5[t4 + 2] = this._z, e5[t4 + 3] = this._w, e5; } fromBufferAttribute(e5, t4) { return this._x = e5.getX(t4), this._y = e5.getY(t4), this._z = e5.getZ(t4), this._w = e5.getW(t4), this._onChangeCallback(), this; } toJSON() { return this.toArray(); } _onChange(e5) { return this._onChangeCallback = e5, this; } _onChangeCallback() { } *[Symbol.iterator]() { yield this._x, yield this._y, yield this._z, yield this._w; } }; var w = class l2 { static { l2.prototype.isVector3 = true; } constructor(e5 = 0, t4 = 0, n5 = 0) { this.x = e5, this.y = t4, this.z = n5; } set(e5, t4, n5) { return n5 === void 0 && (n5 = this.z), this.x = e5, this.y = t4, this.z = n5, this; } setScalar(e5) { return this.x = e5, this.y = e5, this.z = e5, this; } setX(e5) { return this.x = e5, this; } setY(e5) { return this.y = e5, this; } setZ(e5) { return this.z = e5, this; } setComponent(e5, t4) { switch (e5) { case 0: this.x = t4; break; case 1: this.y = t4; break; case 2: this.z = t4; break; default: throw new Error("index is out of range: " + e5); } return this; } getComponent(e5) { switch (e5) { case 0: return this.x; case 1: return this.y; case 2: return this.z; default: throw new Error("index is out of range: " + e5); } } clone() { return new this.constructor(this.x, this.y, this.z); } copy(e5) { return this.x = e5.x, this.y = e5.y, this.z = e5.z, this; } add(e5) { return this.x += e5.x, this.y += e5.y, this.z += e5.z, this; } addScalar(e5) { return this.x += e5, this.y += e5, this.z += e5, this; } addVectors(e5, t4) { return this.x = e5.x + t4.x, this.y = e5.y + t4.y, this.z = e5.z + t4.z, this; } addScaledVector(e5, t4) { return this.x += e5.x * t4, this.y += e5.y * t4, this.z += e5.z * t4, this; } sub(e5) { return this.x -= e5.x, this.y -= e5.y, this.z -= e5.z, this; } subScalar(e5) { return this.x -= e5, this.y -= e5, this.z -= e5, this; } subVectors(e5, t4) { return this.x = e5.x - t4.x, this.y = e5.y - t4.y, this.z = e5.z - t4.z, this; } multiply(e5) { return this.x *= e5.x, this.y *= e5.y, this.z *= e5.z, this; } multiplyScalar(e5) { return this.x *= e5, this.y *= e5, this.z *= e5, this; } multiplyVectors(e5, t4) { return this.x = e5.x * t4.x, this.y = e5.y * t4.y, this.z = e5.z * t4.z, this; } applyEuler(e5) { return this.applyQuaternion(Ht.setFromEuler(e5)); } applyAxisAngle(e5, t4) { return this.applyQuaternion(Ht.setFromAxisAngle(e5, t4)); } applyMatrix3(e5) { let t4 = this.x, n5 = this.y, i4 = this.z, s2 = e5.elements; return this.x = s2[0] * t4 + s2[3] * n5 + s2[6] * i4, this.y = s2[1] * t4 + s2[4] * n5 + s2[7] * i4, this.z = s2[2] * t4 + s2[5] * n5 + s2[8] * i4, this; } applyNormalMatrix(e5) { return this.applyMatrix3(e5).normalize(); } applyMatrix4(e5) { let t4 = this.x, n5 = this.y, i4 = this.z, s2 = e5.elements, r4 = 1 / (s2[3] * t4 + s2[7] * n5 + s2[11] * i4 + s2[15]); return this.x = (s2[0] * t4 + s2[4] * n5 + s2[8] * i4 + s2[12]) * r4, this.y = (s2[1] * t4 + s2[5] * n5 + s2[9] * i4 + s2[13]) * r4, this.z = (s2[2] * t4 + s2[6] * n5 + s2[10] * i4 + s2[14]) * r4, this; } applyQuaternion(e5) { let t4 = this.x, n5 = this.y, i4 = this.z, s2 = e5.x, r4 = e5.y, a3 = e5.z, c2 = e5.w, o3 = 2 * (r4 * i4 - a3 * n5), h2 = 2 * (a3 * t4 - s2 * i4), u2 = 2 * (s2 * n5 - r4 * t4); return this.x = t4 + c2 * o3 + r4 * u2 - a3 * h2, this.y = n5 + c2 * h2 + a3 * o3 - s2 * u2, this.z = i4 + c2 * u2 + s2 * h2 - r4 * o3, this; } project(e5) { return this.applyMatrix4(e5.matrixWorldInverse).applyMatrix4(e5.projectionMatrix); } unproject(e5) { return this.applyMatrix4(e5.projectionMatrixInverse).applyMatrix4(e5.matrixWorld); } transformDirection(e5) { let t4 = this.x, n5 = this.y, i4 = this.z, s2 = e5.elements; return this.x = s2[0] * t4 + s2[4] * n5 + s2[8] * i4, this.y = s2[1] * t4 + s2[5] * n5 + s2[9] * i4, this.z = s2[2] * t4 + s2[6] * n5 + s2[10] * i4, this.normalize(); } divide(e5) { return this.x /= e5.x, this.y /= e5.y, this.z /= e5.z, this; } divideScalar(e5) { return this.multiplyScalar(1 / e5); } min(e5) { return this.x = Math.min(this.x, e5.x), this.y = Math.min(this.y, e5.y), this.z = Math.min(this.z, e5.z), this; } max(e5) { return this.x = Math.max(this.x, e5.x), this.y = Math.max(this.y, e5.y), this.z = Math.max(this.z, e5.z), this; } clamp(e5, t4) { return this.x = E(this.x, e5.x, t4.x), this.y = E(this.y, e5.y, t4.y), this.z = E(this.z, e5.z, t4.z), this; } clampScalar(e5, t4) { return this.x = E(this.x, e5, t4), this.y = E(this.y, e5, t4), this.z = E(this.z, e5, t4), this; } clampLength(e5, t4) { let n5 = this.length(); return this.divideScalar(n5 || 1).multiplyScalar(E(n5, e5, t4)); } floor() { return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this; } ceil() { return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this; } round() { return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this; } roundToZero() { return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this; } negate() { return this.x = -this.x, this.y = -this.y, this.z = -this.z, this; } dot(e5) { return this.x * e5.x + this.y * e5.y + this.z * e5.z; } lengthSq() { return this.x * this.x + this.y * this.y + this.z * this.z; } length() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } manhattanLength() { return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); } normalize() { return this.divideScalar(this.length() || 1); } setLength(e5) { return this.normalize().multiplyScalar(e5); } lerp(e5, t4) { return this.x += (e5.x - this.x) * t4, this.y += (e5.y - this.y) * t4, this.z += (e5.z - this.z) * t4, this; } lerpVectors(e5, t4, n5) { return this.x = e5.x + (t4.x - e5.x) * n5, this.y = e5.y + (t4.y - e5.y) * n5, this.z = e5.z + (t4.z - e5.z) * n5, this; } cross(e5) { return this.crossVectors(this, e5); } crossVectors(e5, t4) { let n5 = e5.x, i4 = e5.y, s2 = e5.z, r4 = t4.x, a3 = t4.y, c2 = t4.z; return this.x = i4 * c2 - s2 * a3, this.y = s2 * r4 - n5 * c2, this.z = n5 * a3 - i4 * r4, this; } projectOnVector(e5) { let t4 = e5.lengthSq(); if (t4 === 0) return this.set(0, 0, 0); let n5 = e5.dot(this) / t4; return this.copy(e5).multiplyScalar(n5); } projectOnPlane(e5) { return ze.copy(this).projectOnVector(e5), this.sub(ze); } reflect(e5) { return this.sub(ze.copy(e5).multiplyScalar(2 * this.dot(e5))); } angleTo(e5) { let t4 = Math.sqrt(this.lengthSq() * e5.lengthSq()); if (t4 === 0) return Math.PI / 2; let n5 = this.dot(e5) / t4; return Math.acos(E(n5, -1, 1)); } distanceTo(e5) { return Math.sqrt(this.distanceToSquared(e5)); } distanceToSquared(e5) { let t4 = this.x - e5.x, n5 = this.y - e5.y, i4 = this.z - e5.z; return t4 * t4 + n5 * n5 + i4 * i4; } manhattanDistanceTo(e5) { return Math.abs(this.x - e5.x) + Math.abs(this.y - e5.y) + Math.abs(this.z - e5.z); } setFromSpherical(e5) { return this.setFromSphericalCoords(e5.radius, e5.phi, e5.theta); } setFromSphericalCoords(e5, t4, n5) { let i4 = Math.sin(t4) * e5; return this.x = i4 * Math.sin(n5), this.y = Math.cos(t4) * e5, this.z = i4 * Math.cos(n5), this; } setFromCylindrical(e5) { return this.setFromCylindricalCoords(e5.radius, e5.theta, e5.y); } setFromCylindricalCoords(e5, t4, n5) { return this.x = e5 * Math.sin(t4), this.y = n5, this.z = e5 * Math.cos(t4), this; } setFromMatrixPosition(e5) { let t4 = e5.elements; return this.x = t4[12], this.y = t4[13], this.z = t4[14], this; } setFromMatrixScale(e5) { let t4 = this.setFromMatrixColumn(e5, 0).length(), n5 = this.setFromMatrixColumn(e5, 1).length(), i4 = this.setFromMatrixColumn(e5, 2).length(); return this.x = t4, this.y = n5, this.z = i4, this; } setFromMatrixColumn(e5, t4) { return this.fromArray(e5.elements, t4 * 4); } setFromMatrix3Column(e5, t4) { return this.fromArray(e5.elements, t4 * 3); } setFromEuler(e5) { return this.x = e5._x, this.y = e5._y, this.z = e5._z, this; } setFromColor(e5) { return this.x = e5.r, this.y = e5.g, this.z = e5.b, this; } equals(e5) { return e5.x === this.x && e5.y === this.y && e5.z === this.z; } fromArray(e5, t4 = 0) { return this.x = e5[t4], this.y = e5[t4 + 1], this.z = e5[t4 + 2], this; } toArray(e5 = [], t4 = 0) { return e5[t4] = this.x, e5[t4 + 1] = this.y, e5[t4 + 2] = this.z, e5; } fromBufferAttribute(e5, t4) { return this.x = e5.getX(t4), this.y = e5.getY(t4), this.z = e5.getZ(t4), this; } random() { return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this; } randomDirection() { let e5 = Math.random() * Math.PI * 2, t4 = Math.random() * 2 - 1, n5 = Math.sqrt(1 - t4 * t4); return this.x = n5 * Math.cos(e5), this.y = t4, this.z = n5 * Math.sin(e5), this; } *[Symbol.iterator]() { yield this.x, yield this.y, yield this.z; } }; var ze = new w(); var Ht = new te(); var b = class l3 { static { l3.prototype.isMatrix3 = true; } constructor(e5, t4, n5, i4, s2, r4, a3, c2, o3) { this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1], e5 !== void 0 && this.set(e5, t4, n5, i4, s2, r4, a3, c2, o3); } set(e5, t4, n5, i4, s2, r4, a3, c2, o3) { let h2 = this.elements; return h2[0] = e5, h2[1] = i4, h2[2] = a3, h2[3] = t4, h2[4] = s2, h2[5] = c2, h2[6] = n5, h2[7] = r4, h2[8] = o3, this; } identity() { return this.set(1, 0, 0, 0, 1, 0, 0, 0, 1), this; } copy(e5) { let t4 = this.elements, n5 = e5.elements; return t4[0] = n5[0], t4[1] = n5[1], t4[2] = n5[2], t4[3] = n5[3], t4[4] = n5[4], t4[5] = n5[5], t4[6] = n5[6], t4[7] = n5[7], t4[8] = n5[8], this; } extractBasis(e5, t4, n5) { return e5.setFromMatrix3Column(this, 0), t4.setFromMatrix3Column(this, 1), n5.setFromMatrix3Column(this, 2), this; } setFromMatrix4(e5) { let t4 = e5.elements; return this.set(t4[0], t4[4], t4[8], t4[1], t4[5], t4[9], t4[2], t4[6], t4[10]), this; } multiply(e5) { return this.multiplyMatrices(this, e5); } premultiply(e5) { return this.multiplyMatrices(e5, this); } multiplyMatrices(e5, t4) { let n5 = e5.elements, i4 = t4.elements, s2 = this.elements, r4 = n5[0], a3 = n5[3], c2 = n5[6], o3 = n5[1], h2 = n5[4], u2 = n5[7], d2 = n5[2], f2 = n5[5], m3 = n5[8], p2 = i4[0], _2 = i4[3], g2 = i4[6], v2 = i4[1], M = i4[4], S2 = i4[7], y2 = i4[2], A2 = i4[5], C2 = i4[8]; return s2[0] = r4 * p2 + a3 * v2 + c2 * y2, s2[3] = r4 * _2 + a3 * M + c2 * A2, s2[6] = r4 * g2 + a3 * S2 + c2 * C2, s2[1] = o3 * p2 + h2 * v2 + u2 * y2, s2[4] = o3 * _2 + h2 * M + u2 * A2, s2[7] = o3 * g2 + h2 * S2 + u2 * C2, s2[2] = d2 * p2 + f2 * v2 + m3 * y2, s2[5] = d2 * _2 + f2 * M + m3 * A2, s2[8] = d2 * g2 + f2 * S2 + m3 * C2, this; } multiplyScalar(e5) { let t4 = this.elements; return t4[0] *= e5, t4[3] *= e5, t4[6] *= e5, t4[1] *= e5, t4[4] *= e5, t4[7] *= e5, t4[2] *= e5, t4[5] *= e5, t4[8] *= e5, this; } determinant() { let e5 = this.elements, t4 = e5[0], n5 = e5[1], i4 = e5[2], s2 = e5[3], r4 = e5[4], a3 = e5[5], c2 = e5[6], o3 = e5[7], h2 = e5[8]; return t4 * r4 * h2 - t4 * a3 * o3 - n5 * s2 * h2 + n5 * a3 * c2 + i4 * s2 * o3 - i4 * r4 * c2; } invert() { let e5 = this.elements, t4 = e5[0], n5 = e5[1], i4 = e5[2], s2 = e5[3], r4 = e5[4], a3 = e5[5], c2 = e5[6], o3 = e5[7], h2 = e5[8], u2 = h2 * r4 - a3 * o3, d2 = a3 * c2 - h2 * s2, f2 = o3 * s2 - r4 * c2, m3 = t4 * u2 + n5 * d2 + i4 * f2; if (m3 === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); let p2 = 1 / m3; return e5[0] = u2 * p2, e5[1] = (i4 * o3 - h2 * n5) * p2, e5[2] = (a3 * n5 - i4 * r4) * p2, e5[3] = d2 * p2, e5[4] = (h2 * t4 - i4 * c2) * p2, e5[5] = (i4 * s2 - a3 * t4) * p2, e5[6] = f2 * p2, e5[7] = (n5 * c2 - o3 * t4) * p2, e5[8] = (r4 * t4 - n5 * s2) * p2, this; } transpose() { let e5, t4 = this.elements; return e5 = t4[1], t4[1] = t4[3], t4[3] = e5, e5 = t4[2], t4[2] = t4[6], t4[6] = e5, e5 = t4[5], t4[5] = t4[7], t4[7] = e5, this; } getNormalMatrix(e5) { return this.setFromMatrix4(e5).invert().transpose(); } transposeIntoArray(e5) { let t4 = this.elements; return e5[0] = t4[0], e5[1] = t4[3], e5[2] = t4[6], e5[3] = t4[1], e5[4] = t4[4], e5[5] = t4[7], e5[6] = t4[2], e5[7] = t4[5], e5[8] = t4[8], this; } setUvTransform(e5, t4, n5, i4, s2, r4, a3) { let c2 = Math.cos(s2), o3 = Math.sin(s2); return this.set(n5 * c2, n5 * o3, -n5 * (c2 * r4 + o3 * a3) + r4 + e5, -i4 * o3, i4 * c2, -i4 * (-o3 * r4 + c2 * a3) + a3 + t4, 0, 0, 1), this; } scale(e5, t4) { return this.premultiply(Ve.makeScale(e5, t4)), this; } rotate(e5) { return this.premultiply(Ve.makeRotation(-e5)), this; } translate(e5, t4) { return this.premultiply(Ve.makeTranslation(e5, t4)), this; } makeTranslation(e5, t4) { return e5.isVector2 ? this.set(1, 0, e5.x, 0, 1, e5.y, 0, 0, 1) : this.set(1, 0, e5, 0, 1, t4, 0, 0, 1), this; } makeRotation(e5) { let t4 = Math.cos(e5), n5 = Math.sin(e5); return this.set(t4, -n5, 0, n5, t4, 0, 0, 0, 1), this; } makeScale(e5, t4) { return this.set(e5, 0, 0, 0, t4, 0, 0, 0, 1), this; } equals(e5) { let t4 = this.elements, n5 = e5.elements; for (let i4 = 0; i4 < 9; i4++) if (t4[i4] !== n5[i4]) return false; return true; } fromArray(e5, t4 = 0) { for (let n5 = 0; n5 < 9; n5++) this.elements[n5] = e5[n5 + t4]; return this; } toArray(e5 = [], t4 = 0) { let n5 = this.elements; return e5[t4] = n5[0], e5[t4 + 1] = n5[1], e5[t4 + 2] = n5[2], e5[t4 + 3] = n5[3], e5[t4 + 4] = n5[4], e5[t4 + 5] = n5[5], e5[t4 + 6] = n5[6], e5[t4 + 7] = n5[7], e5[t4 + 8] = n5[8], e5; } clone() { return new this.constructor().fromArray(this.elements); } }; var Ve = new b(); var Wt = new b().set(0.4123908, 0.3575843, 0.1804808, 0.212639, 0.7151687, 0.0721923, 0.0193308, 0.1191948, 0.9505322); var Xt = new b().set(3.2409699, -1.5373832, -0.4986108, -0.9692436, 1.8759675, 0.0415551, 0.0556301, -0.203977, 1.0569715); function Fn() { let l13 = { enabled: true, workingColorSpace: nt, spaces: {}, convert: function(i4, s2, r4) { return this.enabled === false || s2 === r4 || !s2 || !r4 || (this.spaces[s2].transfer === Ie && (i4.r = K(i4.r), i4.g = K(i4.g), i4.b = K(i4.b)), this.spaces[s2].primaries !== this.spaces[r4].primaries && (i4.applyMatrix3(this.spaces[s2].toXYZ), i4.applyMatrix3(this.spaces[r4].fromXYZ)), this.spaces[r4].transfer === Ie && (i4.r = de(i4.r), i4.g = de(i4.g), i4.b = de(i4.b))), i4; }, workingToColorSpace: function(i4, s2) { return this.convert(i4, this.workingColorSpace, s2); }, colorSpaceToWorking: function(i4, s2) { return this.convert(i4, s2, this.workingColorSpace); }, getPrimaries: function(i4) { return this.spaces[i4].primaries; }, getTransfer: function(i4) { return i4 === Ct ? it : this.spaces[i4].transfer; }, getToneMappingMode: function(i4) { return this.spaces[i4].outputColorSpaceConfig.toneMappingMode || "standard"; }, getLuminanceCoefficients: function(i4, s2 = this.workingColorSpace) { return i4.fromArray(this.spaces[s2].luminanceCoefficients); }, define: function(i4) { Object.assign(this.spaces, i4); }, _getMatrix: function(i4, s2, r4) { return i4.copy(this.spaces[s2].toXYZ).multiply(this.spaces[r4].fromXYZ); }, _getDrawingBufferColorSpace: function(i4) { return this.spaces[i4].outputColorSpaceConfig.drawingBufferColorSpace; }, _getUnpackColorSpace: function(i4 = this.workingColorSpace) { return this.spaces[i4].workingColorSpaceConfig.unpackColorSpace; }, fromWorkingColorSpace: function(i4, s2) { return rt("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."), l13.workingToColorSpace(i4, s2); }, toWorkingColorSpace: function(i4, s2) { return rt("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."), l13.colorSpaceToWorking(i4, s2); } }, e5 = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06], t4 = [0.2126, 0.7152, 0.0722], n5 = [0.3127, 0.329]; return l13.define({ [nt]: { primaries: e5, whitePoint: n5, transfer: it, toXYZ: Wt, fromXYZ: Xt, luminanceCoefficients: t4, workingColorSpaceConfig: { unpackColorSpace: X }, outputColorSpaceConfig: { drawingBufferColorSpace: X } }, [X]: { primaries: e5, whitePoint: n5, transfer: Ie, toXYZ: Wt, fromXYZ: Xt, luminanceCoefficients: t4, outputColorSpaceConfig: { drawingBufferColorSpace: X } } }), l13; } var W = Fn(); function K(l13) { return l13 < 0.04045 ? l13 * 0.0773993808 : Math.pow(l13 * 0.9478672986 + 0.0521327014, 2.4); } function de(l13) { return l13 < 31308e-7 ? l13 * 12.92 : 1.055 * Math.pow(l13, 0.41666) - 0.055; } var le; var at = class { static getDataURL(e5, t4 = "image/png") { if (/^data:/i.test(e5.src) || typeof HTMLCanvasElement > "u") return e5.src; let n5; if (e5 instanceof HTMLCanvasElement) n5 = e5; else { le === void 0 && (le = st("canvas")), le.width = e5.width, le.height = e5.height; let i4 = le.getContext("2d"); e5 instanceof ImageData ? i4.putImageData(e5, 0, 0) : i4.drawImage(e5, 0, 0, e5.width, e5.height), n5 = le; } return n5.toDataURL(t4); } static sRGBToLinear(e5) { if (typeof HTMLImageElement < "u" && e5 instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && e5 instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && e5 instanceof ImageBitmap) { let t4 = st("canvas"); t4.width = e5.width, t4.height = e5.height; let n5 = t4.getContext("2d"); n5.drawImage(e5, 0, 0, e5.width, e5.height); let i4 = n5.getImageData(0, 0, e5.width, e5.height), s2 = i4.data; for (let r4 = 0; r4 < s2.length; r4++) s2[r4] = K(s2[r4] / 255) * 255; return n5.putImageData(i4, 0, 0), t4; } else if (e5.data) { let t4 = e5.data.slice(0); for (let n5 = 0; n5 < t4.length; n5++) t4 instanceof Uint8Array || t4 instanceof Uint8ClampedArray ? t4[n5] = Math.floor(K(t4[n5] / 255) * 255) : t4[n5] = K(t4[n5]); return { data: t4, width: e5.width, height: e5.height }; } else return z("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."), e5; } }; var On = 0; var ot = class { constructor(e5 = null) { this.isSource = true, Object.defineProperty(this, "id", { value: On++ }), this.uuid = Rt(), this.data = e5, this.dataReady = true, this.version = 0; } getSize(e5) { let t4 = this.data; return typeof HTMLVideoElement < "u" && t4 instanceof HTMLVideoElement ? e5.set(t4.videoWidth, t4.videoHeight, 0) : typeof VideoFrame < "u" && t4 instanceof VideoFrame ? e5.set(t4.displayWidth, t4.displayHeight, 0) : t4 !== null ? e5.set(t4.width, t4.height, t4.depth || 0) : e5.set(0, 0, 0), e5; } set needsUpdate(e5) { e5 === true && this.version++; } toJSON(e5) { let t4 = e5 === void 0 || typeof e5 == "string"; if (!t4 && e5.images[this.uuid] !== void 0) return e5.images[this.uuid]; let n5 = { uuid: this.uuid, url: "" }, i4 = this.data; if (i4 !== null) { let s2; if (Array.isArray(i4)) { s2 = []; for (let r4 = 0, a3 = i4.length; r4 < a3; r4++) i4[r4].isDataTexture ? s2.push(ke(i4[r4].image)) : s2.push(ke(i4[r4])); } else s2 = ke(i4); n5.url = s2; } return t4 || (e5.images[this.uuid] = n5), n5; } }; function ke(l13) { return typeof HTMLImageElement < "u" && l13 instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && l13 instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && l13 instanceof ImageBitmap ? at.getDataURL(l13) : l13.data ? { data: Array.from(l13.data), width: l13.width, height: l13.height, type: l13.data.constructor.name } : (z("Texture: Unable to serialize Texture."), {}); } var Bn = 0; var Ge = new w(); var fe = class l4 extends xe { constructor(e5 = l4.DEFAULT_IMAGE, t4 = l4.DEFAULT_MAPPING, n5 = ge, i4 = ge, s2 = hn, r4 = un, a3 = fn, c2 = dn, o3 = l4.DEFAULT_ANISOTROPY, h2 = Ct) { super(), this.isTexture = true, Object.defineProperty(this, "id", { value: Bn++ }), this.uuid = Rt(), this.name = "", this.source = new ot(e5), this.mipmaps = [], this.mapping = t4, this.channel = 0, this.wrapS = n5, this.wrapT = i4, this.magFilter = s2, this.minFilter = r4, this.anisotropy = o3, this.format = a3, this.internalFormat = null, this.type = c2, this.offset = new Z(0, 0), this.repeat = new Z(1, 1), this.center = new Z(0, 0), this.rotation = 0, this.matrixAutoUpdate = true, this.matrix = new b(), this.generateMipmaps = true, this.premultiplyAlpha = false, this.flipY = true, this.unpackAlignment = 4, this.colorSpace = h2, this.userData = {}, this.updateRanges = [], this.version = 0, this.onUpdate = null, this.renderTarget = null, this.isRenderTargetTexture = false, this.isArrayTexture = !!(e5 && e5.depth && e5.depth > 1), this.pmremVersion = 0, this.normalized = false; } get width() { return this.source.getSize(Ge).x; } get height() { return this.source.getSize(Ge).y; } get depth() { return this.source.getSize(Ge).z; } get image() { return this.source.data; } set image(e5) { this.source.data = e5; } updateMatrix() { this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); } addUpdateRange(e5, t4) { this.updateRanges.push({ start: e5, count: t4 }); } clearUpdateRanges() { this.updateRanges.length = 0; } clone() { return new this.constructor().copy(this); } copy(e5) { return this.name = e5.name, this.source = e5.source, this.mipmaps = e5.mipmaps.slice(0), this.mapping = e5.mapping, this.channel = e5.channel, this.wrapS = e5.wrapS, this.wrapT = e5.wrapT, this.magFilter = e5.magFilter, this.minFilter = e5.minFilter, this.anisotropy = e5.anisotropy, this.format = e5.format, this.internalFormat = e5.internalFormat, this.type = e5.type, this.normalized = e5.normalized, this.offset.copy(e5.offset), this.repeat.copy(e5.repeat), this.center.copy(e5.center), this.rotation = e5.rotation, this.matrixAutoUpdate = e5.matrixAutoUpdate, this.matrix.copy(e5.matrix), this.generateMipmaps = e5.generateMipmaps, this.premultiplyAlpha = e5.premultiplyAlpha, this.flipY = e5.flipY, this.unpackAlignment = e5.unpackAlignment, this.colorSpace = e5.colorSpace, this.renderTarget = e5.renderTarget, this.isRenderTargetTexture = e5.isRenderTargetTexture, this.isArrayTexture = e5.isArrayTexture, this.userData = JSON.parse(JSON.stringify(e5.userData)), this.needsUpdate = true, this; } setValues(e5) { for (let t4 in e5) { let n5 = e5[t4]; if (n5 === void 0) { z(`Texture.setValues(): parameter '${t4}' has value of undefined.`); continue; } let i4 = this[t4]; if (i4 === void 0) { z(`Texture.setValues(): property '${t4}' does not exist.`); continue; } i4 && n5 && i4.isVector2 && n5.isVector2 || i4 && n5 && i4.isVector3 && n5.isVector3 || i4 && n5 && i4.isMatrix3 && n5.isMatrix3 ? i4.copy(n5) : this[t4] = n5; } } toJSON(e5) { let t4 = e5 === void 0 || typeof e5 == "string"; if (!t4 && e5.textures[this.uuid] !== void 0) return e5.textures[this.uuid]; let n5 = { metadata: { version: 4.7, type: "Texture", generator: "Texture.toJSON" }, uuid: this.uuid, name: this.name, image: this.source.toJSON(e5).uuid, mapping: this.mapping, channel: this.channel, repeat: [this.repeat.x, this.repeat.y], offset: [this.offset.x, this.offset.y], center: [this.center.x, this.center.y], rotation: this.rotation, wrap: [this.wrapS, this.wrapT], format: this.format, internalFormat: this.internalFormat, type: this.type, normalized: this.normalized, colorSpace: this.colorSpace, minFilter: this.minFilter, magFilter: this.magFilter, anisotropy: this.anisotropy, flipY: this.flipY, generateMipmaps: this.generateMipmaps, premultiplyAlpha: this.premultiplyAlpha, unpackAlignment: this.unpackAlignment }; return Object.keys(this.userData).length > 0 && (n5.userData = this.userData), t4 || (e5.textures[this.uuid] = n5), n5; } dispose() { this.dispatchEvent({ type: "dispose" }); } transformUv(e5) { if (this.mapping !== on) return e5; if (e5.applyMatrix3(this.matrix), e5.x < 0 || e5.x > 1) switch (this.wrapS) { case je: e5.x = e5.x - Math.floor(e5.x); break; case ge: e5.x = e5.x < 0 ? 0 : 1; break; case et: Math.abs(Math.floor(e5.x) % 2) === 1 ? e5.x = Math.ceil(e5.x) - e5.x : e5.x = e5.x - Math.floor(e5.x); break; } if (e5.y < 0 || e5.y > 1) switch (this.wrapT) { case je: e5.y = e5.y - Math.floor(e5.y); break; case ge: e5.y = e5.y < 0 ? 0 : 1; break; case et: Math.abs(Math.floor(e5.y) % 2) === 1 ? e5.y = Math.ceil(e5.y) - e5.y : e5.y = e5.y - Math.floor(e5.y); break; } return this.flipY && (e5.y = 1 - e5.y), e5; } set needsUpdate(e5) { e5 === true && (this.version++, this.source.needsUpdate = true); } set needsPMREMUpdate(e5) { e5 === true && this.pmremVersion++; } }; fe.DEFAULT_IMAGE = null; fe.DEFAULT_MAPPING = on; fe.DEFAULT_ANISOTROPY = 1; var lt = class l5 { static { l5.prototype.isVector4 = true; } constructor(e5 = 0, t4 = 0, n5 = 0, i4 = 1) { this.x = e5, this.y = t4, this.z = n5, this.w = i4; } get width() { return this.z; } set width(e5) { this.z = e5; } get height() { return this.w; } set height(e5) { this.w = e5; } set(e5, t4, n5, i4) { return this.x = e5, this.y = t4, this.z = n5, this.w = i4, this; } setScalar(e5) { return this.x = e5, this.y = e5, this.z = e5, this.w = e5, this; } setX(e5) { return this.x = e5, this; } setY(e5) { return this.y = e5, this; } setZ(e5) { return this.z = e5, this; } setW(e5) { return this.w = e5, this; } setComponent(e5, t4) { switch (e5) { case 0: this.x = t4; break; case 1: this.y = t4; break; case 2: this.z = t4; break; case 3: this.w = t4; break; default: throw new Error("index is out of range: " + e5); } return this; } getComponent(e5) { switch (e5) { case 0: return this.x; case 1: return this.y; case 2: return this.z; case 3: return this.w; default: throw new Error("index is out of range: " + e5); } } clone() { return new this.constructor(this.x, this.y, this.z, this.w); } copy(e5) { return this.x = e5.x, this.y = e5.y, this.z = e5.z, this.w = e5.w !== void 0 ? e5.w : 1, this; } add(e5) { return this.x += e5.x, this.y += e5.y, this.z += e5.z, this.w += e5.w, this; } addScalar(e5) { return this.x += e5, this.y += e5, this.z += e5, this.w += e5, this; } addVectors(e5, t4) { return this.x = e5.x + t4.x, this.y = e5.y + t4.y, this.z = e5.z + t4.z, this.w = e5.w + t4.w, this; } addScaledVector(e5, t4) { return this.x += e5.x * t4, this.y += e5.y * t4, this.z += e5.z * t4, this.w += e5.w * t4, this; } sub(e5) { return this.x -= e5.x, this.y -= e5.y, this.z -= e5.z, this.w -= e5.w, this; } subScalar(e5) { return this.x -= e5, this.y -= e5, this.z -= e5, this.w -= e5, this; } subVectors(e5, t4) { return this.x = e5.x - t4.x, this.y = e5.y - t4.y, this.z = e5.z - t4.z, this.w = e5.w - t4.w, this; } multiply(e5) { return this.x *= e5.x, this.y *= e5.y, this.z *= e5.z, this.w *= e5.w, this; } multiplyScalar(e5) { return this.x *= e5, this.y *= e5, this.z *= e5, this.w *= e5, this; } applyMatrix4(e5) { let t4 = this.x, n5 = this.y, i4 = this.z, s2 = this.w, r4 = e5.elements; return this.x = r4[0] * t4 + r4[4] * n5 + r4[8] * i4 + r4[12] * s2, this.y = r4[1] * t4 + r4[5] * n5 + r4[9] * i4 + r4[13] * s2, this.z = r4[2] * t4 + r4[6] * n5 + r4[10] * i4 + r4[14] * s2, this.w = r4[3] * t4 + r4[7] * n5 + r4[11] * i4 + r4[15] * s2, this; } divide(e5) { return this.x /= e5.x, this.y /= e5.y, this.z /= e5.z, this.w /= e5.w, this; } divideScalar(e5) { return this.multiplyScalar(1 / e5); } setAxisAngleFromQuaternion(e5) { this.w = 2 * Math.acos(e5.w); let t4 = Math.sqrt(1 - e5.w * e5.w); return t4 < 1e-4 ? (this.x = 1, this.y = 0, this.z = 0) : (this.x = e5.x / t4, this.y = e5.y / t4, this.z = e5.z / t4), this; } setAxisAngleFromRotationMatrix(e5) { let t4, n5, i4, s2, c2 = e5.elements, o3 = c2[0], h2 = c2[4], u2 = c2[8], d2 = c2[1], f2 = c2[5], m3 = c2[9], p2 = c2[2], _2 = c2[6], g2 = c2[10]; if (Math.abs(h2 - d2) < 0.01 && Math.abs(u2 - p2) < 0.01 && Math.abs(m3 - _2) < 0.01) { if (Math.abs(h2 + d2) < 0.1 && Math.abs(u2 + p2) < 0.1 && Math.abs(m3 + _2) < 0.1 && Math.abs(o3 + f2 + g2 - 3) < 0.1) return this.set(1, 0, 0, 0), this; t4 = Math.PI; let M = (o3 + 1) / 2, S2 = (f2 + 1) / 2, y2 = (g2 + 1) / 2, A2 = (h2 + d2) / 4, C2 = (u2 + p2) / 4, R2 = (m3 + _2) / 4; return M > S2 && M > y2 ? M < 0.01 ? (n5 = 0, i4 = 0.707106781, s2 = 0.707106781) : (n5 = Math.sqrt(M), i4 = A2 / n5, s2 = C2 / n5) : S2 > y2 ? S2 < 0.01 ? (n5 = 0.707106781, i4 = 0, s2 = 0.707106781) : (i4 = Math.sqrt(S2), n5 = A2 / i4, s2 = R2 / i4) : y2 < 0.01 ? (n5 = 0.707106781, i4 = 0.707106781, s2 = 0) : (s2 = Math.sqrt(y2), n5 = C2 / s2, i4 = R2 / s2), this.set(n5, i4, s2, t4), this; } let v2 = Math.sqrt((_2 - m3) * (_2 - m3) + (u2 - p2) * (u2 - p2) + (d2 - h2) * (d2 - h2)); return Math.abs(v2) < 1e-3 && (v2 = 1), this.x = (_2 - m3) / v2, this.y = (u2 - p2) / v2, this.z = (d2 - h2) / v2, this.w = Math.acos((o3 + f2 + g2 - 1) / 2), this; } setFromMatrixPosition(e5) { let t4 = e5.elements; return this.x = t4[12], this.y = t4[13], this.z = t4[14], this.w = t4[15], this; } min(e5) { return this.x = Math.min(this.x, e5.x), this.y = Math.min(this.y, e5.y), this.z = Math.min(this.z, e5.z), this.w = Math.min(this.w, e5.w), this; } max(e5) { return this.x = Math.max(this.x, e5.x), this.y = Math.max(this.y, e5.y), this.z = Math.max(this.z, e5.z), this.w = Math.max(this.w, e5.w), this; } clamp(e5, t4) { return this.x = E(this.x, e5.x, t4.x), this.y = E(this.y, e5.y, t4.y), this.z = E(this.z, e5.z, t4.z), this.w = E(this.w, e5.w, t4.w), this; } clampScalar(e5, t4) { return this.x = E(this.x, e5, t4), this.y = E(this.y, e5, t4), this.z = E(this.z, e5, t4), this.w = E(this.w, e5, t4), this; } clampLength(e5, t4) { let n5 = this.length(); return this.divideScalar(n5 || 1).multiplyScalar(E(n5, e5, t4)); } floor() { return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this.w = Math.floor(this.w), this; } ceil() { return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this.w = Math.ceil(this.w), this; } round() { return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this.w = Math.round(this.w), this; } roundToZero() { return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this.w = Math.trunc(this.w), this; } negate() { return this.x = -this.x, this.y = -this.y, this.z = -this.z, this.w = -this.w, this; } dot(e5) { return this.x * e5.x + this.y * e5.y + this.z * e5.z + this.w * e5.w; } lengthSq() { return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; } length() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); } manhattanLength() { return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); } normalize() { return this.divideScalar(this.length() || 1); } setLength(e5) { return this.normalize().multiplyScalar(e5); } lerp(e5, t4) { return this.x += (e5.x - this.x) * t4, this.y += (e5.y - this.y) * t4, this.z += (e5.z - this.z) * t4, this.w += (e5.w - this.w) * t4, this; } lerpVectors(e5, t4, n5) { return this.x = e5.x + (t4.x - e5.x) * n5, this.y = e5.y + (t4.y - e5.y) * n5, this.z = e5.z + (t4.z - e5.z) * n5, this.w = e5.w + (t4.w - e5.w) * n5, this; } equals(e5) { return e5.x === this.x && e5.y === this.y && e5.z === this.z && e5.w === this.w; } fromArray(e5, t4 = 0) { return this.x = e5[t4], this.y = e5[t4 + 1], this.z = e5[t4 + 2], this.w = e5[t4 + 3], this; } toArray(e5 = [], t4 = 0) { return e5[t4] = this.x, e5[t4 + 1] = this.y, e5[t4 + 2] = this.z, e5[t4 + 3] = this.w, e5; } fromBufferAttribute(e5, t4) { return this.x = e5.getX(t4), this.y = e5.getY(t4), this.z = e5.getZ(t4), this.w = e5.getW(t4), this; } random() { return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this.w = Math.random(), this; } *[Symbol.iterator]() { yield this.x, yield this.y, yield this.z, yield this.w; } }; var Q = class l6 { static { l6.prototype.isMatrix4 = true; } constructor(e5, t4, n5, i4, s2, r4, a3, c2, o3, h2, u2, d2, f2, m3, p2, _2) { this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], e5 !== void 0 && this.set(e5, t4, n5, i4, s2, r4, a3, c2, o3, h2, u2, d2, f2, m3, p2, _2); } set(e5, t4, n5, i4, s2, r4, a3, c2, o3, h2, u2, d2, f2, m3, p2, _2) { let g2 = this.elements; return g2[0] = e5, g2[4] = t4, g2[8] = n5, g2[12] = i4, g2[1] = s2, g2[5] = r4, g2[9] = a3, g2[13] = c2, g2[2] = o3, g2[6] = h2, g2[10] = u2, g2[14] = d2, g2[3] = f2, g2[7] = m3, g2[11] = p2, g2[15] = _2, this; } identity() { return this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), this; } clone() { return new l6().fromArray(this.elements); } copy(e5) { let t4 = this.elements, n5 = e5.elements; return t4[0] = n5[0], t4[1] = n5[1], t4[2] = n5[2], t4[3] = n5[3], t4[4] = n5[4], t4[5] = n5[5], t4[6] = n5[6], t4[7] = n5[7], t4[8] = n5[8], t4[9] = n5[9], t4[10] = n5[10], t4[11] = n5[11], t4[12] = n5[12], t4[13] = n5[13], t4[14] = n5[14], t4[15] = n5[15], this; } copyPosition(e5) { let t4 = this.elements, n5 = e5.elements; return t4[12] = n5[12], t4[13] = n5[13], t4[14] = n5[14], this; } setFromMatrix3(e5) { let t4 = e5.elements; return this.set(t4[0], t4[3], t4[6], 0, t4[1], t4[4], t4[7], 0, t4[2], t4[5], t4[8], 0, 0, 0, 0, 1), this; } extractBasis(e5, t4, n5) { return this.determinant() === 0 ? (e5.set(1, 0, 0), t4.set(0, 1, 0), n5.set(0, 0, 1), this) : (e5.setFromMatrixColumn(this, 0), t4.setFromMatrixColumn(this, 1), n5.setFromMatrixColumn(this, 2), this); } makeBasis(e5, t4, n5) { return this.set(e5.x, t4.x, n5.x, 0, e5.y, t4.y, n5.y, 0, e5.z, t4.z, n5.z, 0, 0, 0, 0, 1), this; } extractRotation(e5) { if (e5.determinant() === 0) return this.identity(); let t4 = this.elements, n5 = e5.elements, i4 = 1 / ce.setFromMatrixColumn(e5, 0).length(), s2 = 1 / ce.setFromMatrixColumn(e5, 1).length(), r4 = 1 / ce.setFromMatrixColumn(e5, 2).length(); return t4[0] = n5[0] * i4, t4[1] = n5[1] * i4, t4[2] = n5[2] * i4, t4[3] = 0, t4[4] = n5[4] * s2, t4[5] = n5[5] * s2, t4[6] = n5[6] * s2, t4[7] = 0, t4[8] = n5[8] * r4, t4[9] = n5[9] * r4, t4[10] = n5[10] * r4, t4[11] = 0, t4[12] = 0, t4[13] = 0, t4[14] = 0, t4[15] = 1, this; } makeRotationFromEuler(e5) { let t4 = this.elements, n5 = e5.x, i4 = e5.y, s2 = e5.z, r4 = Math.cos(n5), a3 = Math.sin(n5), c2 = Math.cos(i4), o3 = Math.sin(i4), h2 = Math.cos(s2), u2 = Math.sin(s2); if (e5.order === "XYZ") { let d2 = r4 * h2, f2 = r4 * u2, m3 = a3 * h2, p2 = a3 * u2; t4[0] = c2 * h2, t4[4] = -c2 * u2, t4[8] = o3, t4[1] = f2 + m3 * o3, t4[5] = d2 - p2 * o3, t4[9] = -a3 * c2, t4[2] = p2 - d2 * o3, t4[6] = m3 + f2 * o3, t4[10] = r4 * c2; } else if (e5.order === "YXZ") { let d2 = c2 * h2, f2 = c2 * u2, m3 = o3 * h2, p2 = o3 * u2; t4[0] = d2 + p2 * a3, t4[4] = m3 * a3 - f2, t4[8] = r4 * o3, t4[1] = r4 * u2, t4[5] = r4 * h2, t4[9] = -a3, t4[2] = f2 * a3 - m3, t4[6] = p2 + d2 * a3, t4[10] = r4 * c2; } else if (e5.order === "ZXY") { let d2 = c2 * h2, f2 = c2 * u2, m3 = o3 * h2, p2 = o3 * u2; t4[0] = d2 - p2 * a3, t4[4] = -r4 * u2, t4[8] = m3 + f2 * a3, t4[1] = f2 + m3 * a3, t4[5] = r4 * h2, t4[9] = p2 - d2 * a3, t4[2] = -r4 * o3, t4[6] = a3, t4[10] = r4 * c2; } else if (e5.order === "ZYX") { let d2 = r4 * h2, f2 = r4 * u2, m3 = a3 * h2, p2 = a3 * u2; t4[0] = c2 * h2, t4[4] = m3 * o3 - f2, t4[8] = d2 * o3 + p2, t4[1] = c2 * u2, t4[5] = p2 * o3 + d2, t4[9] = f2 * o3 - m3, t4[2] = -o3, t4[6] = a3 * c2, t4[10] = r4 * c2; } else if (e5.order === "YZX") { let d2 = r4 * c2, f2 = r4 * o3, m3 = a3 * c2, p2 = a3 * o3; t4[0] = c2 * h2, t4[4] = p2 - d2 * u2, t4[8] = m3 * u2 + f2, t4[1] = u2, t4[5] = r4 * h2, t4[9] = -a3 * h2, t4[2] = -o3 * h2, t4[6] = f2 * u2 + m3, t4[10] = d2 - p2 * u2; } else if (e5.order === "XZY") { let d2 = r4 * c2, f2 = r4 * o3, m3 = a3 * c2, p2 = a3 * o3; t4[0] = c2 * h2, t4[4] = -u2, t4[8] = o3 * h2, t4[1] = d2 * u2 + p2, t4[5] = r4 * h2, t4[9] = f2 * u2 - m3, t4[2] = m3 * u2 - f2, t4[6] = a3 * h2, t4[10] = p2 * u2 + d2; } return t4[3] = 0, t4[7] = 0, t4[11] = 0, t4[12] = 0, t4[13] = 0, t4[14] = 0, t4[15] = 1, this; } makeRotationFromQuaternion(e5) { return this.compose(zn, e5, Vn); } lookAt(e5, t4, n5) { let i4 = this.elements; return H.subVectors(e5, t4), H.lengthSq() === 0 && (H.z = 1), H.normalize(), j.crossVectors(n5, H), j.lengthSq() === 0 && (Math.abs(n5.z) === 1 ? H.x += 1e-4 : H.z += 1e-4, H.normalize(), j.crossVectors(n5, H)), j.normalize(), Ae.crossVectors(H, j), i4[0] = j.x, i4[4] = Ae.x, i4[8] = H.x, i4[1] = j.y, i4[5] = Ae.y, i4[9] = H.y, i4[2] = j.z, i4[6] = Ae.z, i4[10] = H.z, this; } multiply(e5) { return this.multiplyMatrices(this, e5); } premultiply(e5) { return this.multiplyMatrices(e5, this); } multiplyMatrices(e5, t4) { let n5 = e5.elements, i4 = t4.elements, s2 = this.elements, r4 = n5[0], a3 = n5[4], c2 = n5[8], o3 = n5[12], h2 = n5[1], u2 = n5[5], d2 = n5[9], f2 = n5[13], m3 = n5[2], p2 = n5[6], _2 = n5[10], g2 = n5[14], v2 = n5[3], M = n5[7], S2 = n5[11], y2 = n5[15], A2 = i4[0], C2 = i4[4], R2 = i4[8], U = i4[12], k = i4[1], D = i4[5], F2 = i4[9], G = i4[13], J = i4[2], P = i4[6], ne = i4[10], ie = i4[14], Me = i4[3], Se = i4[7], be = i4[11], Te = i4[15]; return s2[0] = r4 * A2 + a3 * k + c2 * J + o3 * Me, s2[4] = r4 * C2 + a3 * D + c2 * P + o3 * Se, s2[8] = r4 * R2 + a3 * F2 + c2 * ne + o3 * be, s2[12] = r4 * U + a3 * G + c2 * ie + o3 * Te, s2[1] = h2 * A2 + u2 * k + d2 * J + f2 * Me, s2[5] = h2 * C2 + u2 * D + d2 * P + f2 * Se, s2[9] = h2 * R2 + u2 * F2 + d2 * ne + f2 * be, s2[13] = h2 * U + u2 * G + d2 * ie + f2 * Te, s2[2] = m3 * A2 + p2 * k + _2 * J + g2 * Me, s2[6] = m3 * C2 + p2 * D + _2 * P + g2 * Se, s2[10] = m3 * R2 + p2 * F2 + _2 * ne + g2 * be, s2[14] = m3 * U + p2 * G + _2 * ie + g2 * Te, s2[3] = v2 * A2 + M * k + S2 * J + y2 * Me, s2[7] = v2 * C2 + M * D + S2 * P + y2 * Se, s2[11] = v2 * R2 + M * F2 + S2 * ne + y2 * be, s2[15] = v2 * U + M * G + S2 * ie + y2 * Te, this; } multiplyScalar(e5) { let t4 = this.elements; return t4[0] *= e5, t4[4] *= e5, t4[8] *= e5, t4[12] *= e5, t4[1] *= e5, t4[5] *= e5, t4[9] *= e5, t4[13] *= e5, t4[2] *= e5, t4[6] *= e5, t4[10] *= e5, t4[14] *= e5, t4[3] *= e5, t4[7] *= e5, t4[11] *= e5, t4[15] *= e5, this; } determinant() { let e5 = this.elements, t4 = e5[0], n5 = e5[4], i4 = e5[8], s2 = e5[12], r4 = e5[1], a3 = e5[5], c2 = e5[9], o3 = e5[13], h2 = e5[2], u2 = e5[6], d2 = e5[10], f2 = e5[14], m3 = e5[3], p2 = e5[7], _2 = e5[11], g2 = e5[15], v2 = c2 * f2 - o3 * d2, M = a3 * f2 - o3 * u2, S2 = a3 * d2 - c2 * u2, y2 = r4 * f2 - o3 * h2, A2 = r4 * d2 - c2 * h2, C2 = r4 * u2 - a3 * h2; return t4 * (p2 * v2 - _2 * M + g2 * S2) - n5 * (m3 * v2 - _2 * y2 + g2 * A2) + i4 * (m3 * M - p2 * y2 + g2 * C2) - s2 * (m3 * S2 - p2 * A2 + _2 * C2); } transpose() { let e5 = this.elements, t4; return t4 = e5[1], e5[1] = e5[4], e5[4] = t4, t4 = e5[2], e5[2] = e5[8], e5[8] = t4, t4 = e5[6], e5[6] = e5[9], e5[9] = t4, t4 = e5[3], e5[3] = e5[12], e5[12] = t4, t4 = e5[7], e5[7] = e5[13], e5[13] = t4, t4 = e5[11], e5[11] = e5[14], e5[14] = t4, this; } setPosition(e5, t4, n5) { let i4 = this.elements; return e5.isVector3 ? (i4[12] = e5.x, i4[13] = e5.y, i4[14] = e5.z) : (i4[12] = e5, i4[13] = t4, i4[14] = n5), this; } invert() { let e5 = this.elements, t4 = e5[0], n5 = e5[1], i4 = e5[2], s2 = e5[3], r4 = e5[4], a3 = e5[5], c2 = e5[6], o3 = e5[7], h2 = e5[8], u2 = e5[9], d2 = e5[10], f2 = e5[11], m3 = e5[12], p2 = e5[13], _2 = e5[14], g2 = e5[15], v2 = t4 * a3 - n5 * r4, M = t4 * c2 - i4 * r4, S2 = t4 * o3 - s2 * r4, y2 = n5 * c2 - i4 * a3, A2 = n5 * o3 - s2 * a3, C2 = i4 * o3 - s2 * c2, R2 = h2 * p2 - u2 * m3, U = h2 * _2 - d2 * m3, k = h2 * g2 - f2 * m3, D = u2 * _2 - d2 * p2, F2 = u2 * g2 - f2 * p2, G = d2 * g2 - f2 * _2, J = v2 * G - M * F2 + S2 * D + y2 * k - A2 * U + C2 * R2; if (J === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); let P = 1 / J; return e5[0] = (a3 * G - c2 * F2 + o3 * D) * P, e5[1] = (i4 * F2 - n5 * G - s2 * D) * P, e5[2] = (p2 * C2 - _2 * A2 + g2 * y2) * P, e5[3] = (d2 * A2 - u2 * C2 - f2 * y2) * P, e5[4] = (c2 * k - r4 * G - o3 * U) * P, e5[5] = (t4 * G - i4 * k + s2 * U) * P, e5[6] = (_2 * S2 - m3 * C2 - g2 * M) * P, e5[7] = (h2 * C2 - d2 * S2 + f2 * M) * P, e5[8] = (r4 * F2 - a3 * k + o3 * R2) * P, e5[9] = (n5 * k - t4 * F2 - s2 * R2) * P, e5[10] = (m3 * A2 - p2 * S2 + g2 * v2) * P, e5[11] = (u2 * S2 - h2 * A2 - f2 * v2) * P, e5[12] = (a3 * U - r4 * D - c2 * R2) * P, e5[13] = (t4 * D - n5 * U + i4 * R2) * P, e5[14] = (p2 * M - m3 * y2 - _2 * v2) * P, e5[15] = (h2 * y2 - u2 * M + d2 * v2) * P, this; } scale(e5) { let t4 = this.elements, n5 = e5.x, i4 = e5.y, s2 = e5.z; return t4[0] *= n5, t4[4] *= i4, t4[8] *= s2, t4[1] *= n5, t4[5] *= i4, t4[9] *= s2, t4[2] *= n5, t4[6] *= i4, t4[10] *= s2, t4[3] *= n5, t4[7] *= i4, t4[11] *= s2, this; } getMaxScaleOnAxis() { let e5 = this.elements, t4 = e5[0] * e5[0] + e5[1] * e5[1] + e5[2] * e5[2], n5 = e5[4] * e5[4] + e5[5] * e5[5] + e5[6] * e5[6], i4 = e5[8] * e5[8] + e5[9] * e5[9] + e5[10] * e5[10]; return Math.sqrt(Math.max(t4, n5, i4)); } makeTranslation(e5, t4, n5) { return e5.isVector3 ? this.set(1, 0, 0, e5.x, 0, 1, 0, e5.y, 0, 0, 1, e5.z, 0, 0, 0, 1) : this.set(1, 0, 0, e5, 0, 1, 0, t4, 0, 0, 1, n5, 0, 0, 0, 1), this; } makeRotationX(e5) { let t4 = Math.cos(e5), n5 = Math.sin(e5); return this.set(1, 0, 0, 0, 0, t4, -n5, 0, 0, n5, t4, 0, 0, 0, 0, 1), this; } makeRotationY(e5) { let t4 = Math.cos(e5), n5 = Math.sin(e5); return this.set(t4, 0, n5, 0, 0, 1, 0, 0, -n5, 0, t4, 0, 0, 0, 0, 1), this; } makeRotationZ(e5) { let t4 = Math.cos(e5), n5 = Math.sin(e5); return this.set(t4, -n5, 0, 0, n5, t4, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), this; } makeRotationAxis(e5, t4) { let n5 = Math.cos(t4), i4 = Math.sin(t4), s2 = 1 - n5, r4 = e5.x, a3 = e5.y, c2 = e5.z, o3 = s2 * r4, h2 = s2 * a3; return this.set(o3 * r4 + n5, o3 * a3 - i4 * c2, o3 * c2 + i4 * a3, 0, o3 * a3 + i4 * c2, h2 * a3 + n5, h2 * c2 - i4 * r4, 0, o3 * c2 - i4 * a3, h2 * c2 + i4 * r4, s2 * c2 * c2 + n5, 0, 0, 0, 0, 1), this; } makeScale(e5, t4, n5) { return this.set(e5, 0, 0, 0, 0, t4, 0, 0, 0, 0, n5, 0, 0, 0, 0, 1), this; } makeShear(e5, t4, n5, i4, s2, r4) { return this.set(1, n5, s2, 0, e5, 1, r4, 0, t4, i4, 1, 0, 0, 0, 0, 1), this; } compose(e5, t4, n5) { let i4 = this.elements, s2 = t4._x, r4 = t4._y, a3 = t4._z, c2 = t4._w, o3 = s2 + s2, h2 = r4 + r4, u2 = a3 + a3, d2 = s2 * o3, f2 = s2 * h2, m3 = s2 * u2, p2 = r4 * h2, _2 = r4 * u2, g2 = a3 * u2, v2 = c2 * o3, M = c2 * h2, S2 = c2 * u2, y2 = n5.x, A2 = n5.y, C2 = n5.z; return i4[0] = (1 - (p2 + g2)) * y2, i4[1] = (f2 + S2) * y2, i4[2] = (m3 - M) * y2, i4[3] = 0, i4[4] = (f2 - S2) * A2, i4[5] = (1 - (d2 + g2)) * A2, i4[6] = (_2 + v2) * A2, i4[7] = 0, i4[8] = (m3 + M) * C2, i4[9] = (_2 - v2) * C2, i4[10] = (1 - (d2 + p2)) * C2, i4[11] = 0, i4[12] = e5.x, i4[13] = e5.y, i4[14] = e5.z, i4[15] = 1, this; } decompose(e5, t4, n5) { let i4 = this.elements; e5.x = i4[12], e5.y = i4[13], e5.z = i4[14]; let s2 = this.determinant(); if (s2 === 0) return n5.set(1, 1, 1), t4.identity(), this; let r4 = ce.set(i4[0], i4[1], i4[2]).length(), a3 = ce.set(i4[4], i4[5], i4[6]).length(), c2 = ce.set(i4[8], i4[9], i4[10]).length(); s2 < 0 && (r4 = -r4), Y.copy(this); let o3 = 1 / r4, h2 = 1 / a3, u2 = 1 / c2; return Y.elements[0] *= o3, Y.elements[1] *= o3, Y.elements[2] *= o3, Y.elements[4] *= h2, Y.elements[5] *= h2, Y.elements[6] *= h2, Y.elements[8] *= u2, Y.elements[9] *= u2, Y.elements[10] *= u2, t4.setFromRotationMatrix(Y), n5.x = r4, n5.y = a3, n5.z = c2, this; } makePerspective(e5, t4, n5, i4, s2, r4, a3 = _e, c2 = false) { let o3 = this.elements, h2 = 2 * s2 / (t4 - e5), u2 = 2 * s2 / (n5 - i4), d2 = (t4 + e5) / (t4 - e5), f2 = (n5 + i4) / (n5 - i4), m3, p2; if (c2) m3 = s2 / (r4 - s2), p2 = r4 * s2 / (r4 - s2); else if (a3 === _e) m3 = -(r4 + s2) / (r4 - s2), p2 = -2 * r4 * s2 / (r4 - s2); else if (a3 === kt) m3 = -r4 / (r4 - s2), p2 = -r4 * s2 / (r4 - s2); else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + a3); return o3[0] = h2, o3[4] = 0, o3[8] = d2, o3[12] = 0, o3[1] = 0, o3[5] = u2, o3[9] = f2, o3[13] = 0, o3[2] = 0, o3[6] = 0, o3[10] = m3, o3[14] = p2, o3[3] = 0, o3[7] = 0, o3[11] = -1, o3[15] = 0, this; } makeOrthographic(e5, t4, n5, i4, s2, r4, a3 = _e, c2 = false) { let o3 = this.elements, h2 = 2 / (t4 - e5), u2 = 2 / (n5 - i4), d2 = -(t4 + e5) / (t4 - e5), f2 = -(n5 + i4) / (n5 - i4), m3, p2; if (c2) m3 = 1 / (r4 - s2), p2 = r4 / (r4 - s2); else if (a3 === _e) m3 = -2 / (r4 - s2), p2 = -(r4 + s2) / (r4 - s2); else if (a3 === kt) m3 = -1 / (r4 - s2), p2 = -s2 / (r4 - s2); else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + a3); return o3[0] = h2, o3[4] = 0, o3[8] = 0, o3[12] = d2, o3[1] = 0, o3[5] = u2, o3[9] = 0, o3[13] = f2, o3[2] = 0, o3[6] = 0, o3[10] = m3, o3[14] = p2, o3[3] = 0, o3[7] = 0, o3[11] = 0, o3[15] = 1, this; } equals(e5) { let t4 = this.elements, n5 = e5.elements; for (let i4 = 0; i4 < 16; i4++) if (t4[i4] !== n5[i4]) return false; return true; } fromArray(e5, t4 = 0) { for (let n5 = 0; n5 < 16; n5++) this.elements[n5] = e5[n5 + t4]; return this; } toArray(e5 = [], t4 = 0) { let n5 = this.elements; return e5[t4] = n5[0], e5[t4 + 1] = n5[1], e5[t4 + 2] = n5[2], e5[t4 + 3] = n5[3], e5[t4 + 4] = n5[4], e5[t4 + 5] = n5[5], e5[t4 + 6] = n5[6], e5[t4 + 7] = n5[7], e5[t4 + 8] = n5[8], e5[t4 + 9] = n5[9], e5[t4 + 10] = n5[10], e5[t4 + 11] = n5[11], e5[t4 + 12] = n5[12], e5[t4 + 13] = n5[13], e5[t4 + 14] = n5[14], e5[t4 + 15] = n5[15], e5; } }; var ce = new w(); var Y = new Q(); var zn = new w(0, 0, 0); var Vn = new w(1, 1, 1); var j = new w(); var Ae = new w(); var H = new w(); var qt = new Q(); var Yt = new te(); var Le = class l7 { constructor(e5 = 0, t4 = 0, n5 = 0, i4 = l7.DEFAULT_ORDER) { this.isEuler = true, this._x = e5, this._y = t4, this._z = n5, this._order = i4; } get x() { return this._x; } set x(e5) { this._x = e5, this._onChangeCallback(); } get y() { return this._y; } set y(e5) { this._y = e5, this._onChangeCallback(); } get z() { return this._z; } set z(e5) { this._z = e5, this._onChangeCallback(); } get order() { return this._order; } set order(e5) { this._order = e5, this._onChangeCallback(); } set(e5, t4, n5, i4 = this._order) { return this._x = e5, this._y = t4, this._z = n5, this._order = i4, this._onChangeCallback(), this; } clone() { return new this.constructor(this._x, this._y, this._z, this._order); } copy(e5) { return this._x = e5._x, this._y = e5._y, this._z = e5._z, this._order = e5._order, this._onChangeCallback(), this; } setFromRotationMatrix(e5, t4 = this._order, n5 = true) { let i4 = e5.elements, s2 = i4[0], r4 = i4[4], a3 = i4[8], c2 = i4[1], o3 = i4[5], h2 = i4[9], u2 = i4[2], d2 = i4[6], f2 = i4[10]; switch (t4) { case "XYZ": this._y = Math.asin(E(a3, -1, 1)), Math.abs(a3) < 0.9999999 ? (this._x = Math.atan2(-h2, f2), this._z = Math.atan2(-r4, s2)) : (this._x = Math.atan2(d2, o3), this._z = 0); break; case "YXZ": this._x = Math.asin(-E(h2, -1, 1)), Math.abs(h2) < 0.9999999 ? (this._y = Math.atan2(a3, f2), this._z = Math.atan2(c2, o3)) : (this._y = Math.atan2(-u2, s2), this._z = 0); break; case "ZXY": this._x = Math.asin(E(d2, -1, 1)), Math.abs(d2) < 0.9999999 ? (this._y = Math.atan2(-u2, f2), this._z = Math.atan2(-r4, o3)) : (this._y = 0, this._z = Math.atan2(c2, s2)); break; case "ZYX": this._y = Math.asin(-E(u2, -1, 1)), Math.abs(u2) < 0.9999999 ? (this._x = Math.atan2(d2, f2), this._z = Math.atan2(c2, s2)) : (this._x = 0, this._z = Math.atan2(-r4, o3)); break; case "YZX": this._z = Math.asin(E(c2, -1, 1)), Math.abs(c2) < 0.9999999 ? (this._x = Math.atan2(-h2, o3), this._y = Math.atan2(-u2, s2)) : (this._x = 0, this._y = Math.atan2(a3, f2)); break; case "XZY": this._z = Math.asin(-E(r4, -1, 1)), Math.abs(r4) < 0.9999999 ? (this._x = Math.atan2(d2, o3), this._y = Math.atan2(a3, s2)) : (this._x = Math.atan2(-h2, f2), this._y = 0); break; default: z("Euler: .setFromRotationMatrix() encountered an unknown order: " + t4); } return this._order = t4, n5 === true && this._onChangeCallback(), this; } setFromQuaternion(e5, t4, n5) { return qt.makeRotationFromQuaternion(e5), this.setFromRotationMatrix(qt, t4, n5); } setFromVector3(e5, t4 = this._order) { return this.set(e5.x, e5.y, e5.z, t4); } reorder(e5) { return Yt.setFromEuler(this), this.setFromQuaternion(Yt, e5); } equals(e5) { return e5._x === this._x && e5._y === this._y && e5._z === this._z && e5._order === this._order; } fromArray(e5) { return this._x = e5[0], this._y = e5[1], this._z = e5[2], e5[3] !== void 0 && (this._order = e5[3]), this._onChangeCallback(), this; } toArray(e5 = [], t4 = 0) { return e5[t4] = this._x, e5[t4 + 1] = this._y, e5[t4 + 2] = this._z, e5[t4 + 3] = this._order, e5; } _onChange(e5) { return this._onChangeCallback = e5, this; } _onChangeCallback() { } *[Symbol.iterator]() { yield this._x, yield this._y, yield this._z, yield this._order; } }; Le.DEFAULT_ORDER = "XYZ"; var Ne = class { constructor() { this.mask = 1; } set(e5) { this.mask = (1 << e5 | 0) >>> 0; } enable(e5) { this.mask |= 1 << e5 | 0; } enableAll() { this.mask = -1; } toggle(e5) { this.mask ^= 1 << e5 | 0; } disable(e5) { this.mask &= ~(1 << e5 | 0); } disableAll() { this.mask = 0; } test(e5) { return (this.mask & e5.mask) !== 0; } isEnabled(e5) { return (this.mask & (1 << e5 | 0)) !== 0; } }; var kn = 0; var Zt = new w(); var he = new te(); var $ = new Q(); var we = new w(); var me = new w(); var Gn = new w(); var Hn = new te(); var Jt = new w(1, 0, 0); var $t = new w(0, 1, 0); var Kt = new w(0, 0, 1); var Qt = { type: "added" }; var Wn = { type: "removed" }; var ue = { type: "childadded", child: null }; var He = { type: "childremoved", child: null }; var ve = class l8 extends xe { constructor() { super(), this.isObject3D = true, Object.defineProperty(this, "id", { value: kn++ }), this.uuid = Rt(), this.name = "", this.type = "Object3D", this.parent = null, this.children = [], this.up = l8.DEFAULT_UP.clone(); let e5 = new w(), t4 = new Le(), n5 = new te(), i4 = new w(1, 1, 1); function s2() { n5.setFromEuler(t4, false); } function r4() { t4.setFromQuaternion(n5, void 0, false); } t4._onChange(s2), n5._onChange(r4), Object.defineProperties(this, { position: { configurable: true, enumerable: true, value: e5 }, rotation: { configurable: true, enumerable: true, value: t4 }, quaternion: { configurable: true, enumerable: true, value: n5 }, scale: { configurable: true, enumerable: true, value: i4 }, modelViewMatrix: { value: new Q() }, normalMatrix: { value: new b() } }), this.matrix = new Q(), this.matrixWorld = new Q(), this.matrixAutoUpdate = l8.DEFAULT_MATRIX_AUTO_UPDATE, this.matrixWorldAutoUpdate = l8.DEFAULT_MATRIX_WORLD_AUTO_UPDATE, this.matrixWorldNeedsUpdate = false, this.layers = new Ne(), this.visible = true, this.castShadow = false, this.receiveShadow = false, this.frustumCulled = true, this.renderOrder = 0, this.animations = [], this.customDepthMaterial = void 0, this.customDistanceMaterial = void 0, this.static = false, this.userData = {}, this.pivot = null; } onBeforeShadow() { } onAfterShadow() { } onBeforeRender() { } onAfterRender() { } applyMatrix4(e5) { this.matrixAutoUpdate && this.updateMatrix(), this.matrix.premultiply(e5), this.matrix.decompose(this.position, this.quaternion, this.scale); } applyQuaternion(e5) { return this.quaternion.premultiply(e5), this; } setRotationFromAxisAngle(e5, t4) { this.quaternion.setFromAxisAngle(e5, t4); } setRotationFromEuler(e5) { this.quaternion.setFromEuler(e5, true); } setRotationFromMatrix(e5) { this.quaternion.setFromRotationMatrix(e5); } setRotationFromQuaternion(e5) { this.quaternion.copy(e5); } rotateOnAxis(e5, t4) { return he.setFromAxisAngle(e5, t4), this.quaternion.multiply(he), this; } rotateOnWorldAxis(e5, t4) { return he.setFromAxisAngle(e5, t4), this.quaternion.premultiply(he), this; } rotateX(e5) { return this.rotateOnAxis(Jt, e5); } rotateY(e5) { return this.rotateOnAxis($t, e5); } rotateZ(e5) { return this.rotateOnAxis(Kt, e5); } translateOnAxis(e5, t4) { return Zt.copy(e5).applyQuaternion(this.quaternion), this.position.add(Zt.multiplyScalar(t4)), this; } translateX(e5) { return this.translateOnAxis(Jt, e5); } translateY(e5) { return this.translateOnAxis($t, e5); } translateZ(e5) { return this.translateOnAxis(Kt, e5); } localToWorld(e5) { return this.updateWorldMatrix(true, false), e5.applyMatrix4(this.matrixWorld); } worldToLocal(e5) { return this.updateWorldMatrix(true, false), e5.applyMatrix4($.copy(this.matrixWorld).invert()); } lookAt(e5, t4, n5) { e5.isVector3 ? we.copy(e5) : we.set(e5, t4, n5); let i4 = this.parent; this.updateWorldMatrix(true, false), me.setFromMatrixPosition(this.matrixWorld), this.isCamera || this.isLight ? $.lookAt(me, we, this.up) : $.lookAt(we, me, this.up), this.quaternion.setFromRotationMatrix($), i4 && ($.extractRotation(i4.matrixWorld), he.setFromRotationMatrix($), this.quaternion.premultiply(he.invert())); } add(e5) { if (arguments.length > 1) { for (let t4 = 0; t4 < arguments.length; t4++) this.add(arguments[t4]); return this; } return e5 === this ? (L("Object3D.add: object can't be added as a child of itself.", e5), this) : (e5 && e5.isObject3D ? (e5.removeFromParent(), e5.parent = this, this.children.push(e5), e5.dispatchEvent(Qt), ue.child = e5, this.dispatchEvent(ue), ue.child = null) : L("Object3D.add: object not an instance of THREE.Object3D.", e5), this); } remove(e5) { if (arguments.length > 1) { for (let n5 = 0; n5 < arguments.length; n5++) this.remove(arguments[n5]); return this; } let t4 = this.children.indexOf(e5); return t4 !== -1 && (e5.parent = null, this.children.splice(t4, 1), e5.dispatchEvent(Wn), He.child = e5, this.dispatchEvent(He), He.child = null), this; } removeFromParent() { let e5 = this.parent; return e5 !== null && e5.remove(this), this; } clear() { return this.remove(...this.children); } attach(e5) { return this.updateWorldMatrix(true, false), $.copy(this.matrixWorld).invert(), e5.parent !== null && (e5.parent.updateWorldMatrix(true, false), $.multiply(e5.parent.matrixWorld)), e5.applyMatrix4($), e5.removeFromParent(), e5.parent = this, this.children.push(e5), e5.updateWorldMatrix(false, true), e5.dispatchEvent(Qt), ue.child = e5, this.dispatchEvent(ue), ue.child = null, this; } getObjectById(e5) { return this.getObjectByProperty("id", e5); } getObjectByName(e5) { return this.getObjectByProperty("name", e5); } getObjectByProperty(e5, t4) { if (this[e5] === t4) return this; for (let n5 = 0, i4 = this.children.length; n5 < i4; n5++) { let r4 = this.children[n5].getObjectByProperty(e5, t4); if (r4 !== void 0) return r4; } } getObjectsByProperty(e5, t4, n5 = []) { this[e5] === t4 && n5.push(this); let i4 = this.children; for (let s2 = 0, r4 = i4.length; s2 < r4; s2++) i4[s2].getObjectsByProperty(e5, t4, n5); return n5; } getWorldPosition(e5) { return this.updateWorldMatrix(true, false), e5.setFromMatrixPosition(this.matrixWorld); } getWorldQuaternion(e5) { return this.updateWorldMatrix(true, false), this.matrixWorld.decompose(me, e5, Gn), e5; } getWorldScale(e5) { return this.updateWorldMatrix(true, false), this.matrixWorld.decompose(me, Hn, e5), e5; } getWorldDirection(e5) { this.updateWorldMatrix(true, false); let t4 = this.matrixWorld.elements; return e5.set(t4[8], t4[9], t4[10]).normalize(); } raycast() { } traverse(e5) { e5(this); let t4 = this.children; for (let n5 = 0, i4 = t4.length; n5 < i4; n5++) t4[n5].traverse(e5); } traverseVisible(e5) { if (this.visible === false) return; e5(this); let t4 = this.children; for (let n5 = 0, i4 = t4.length; n5 < i4; n5++) t4[n5].traverseVisible(e5); } traverseAncestors(e5) { let t4 = this.parent; t4 !== null && (e5(t4), t4.traverseAncestors(e5)); } updateMatrix() { this.matrix.compose(this.position, this.quaternion, this.scale); let e5 = this.pivot; if (e5 !== null) { let t4 = e5.x, n5 = e5.y, i4 = e5.z, s2 = this.matrix.elements; s2[12] += t4 - s2[0] * t4 - s2[4] * n5 - s2[8] * i4, s2[13] += n5 - s2[1] * t4 - s2[5] * n5 - s2[9] * i4, s2[14] += i4 - s2[2] * t4 - s2[6] * n5 - s2[10] * i4; } this.matrixWorldNeedsUpdate = true; } updateMatrixWorld(e5) { this.matrixAutoUpdate && this.updateMatrix(), (this.matrixWorldNeedsUpdate || e5) && (this.matrixWorldAutoUpdate === true && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), this.matrixWorldNeedsUpdate = false, e5 = true); let t4 = this.children; for (let n5 = 0, i4 = t4.length; n5 < i4; n5++) t4[n5].updateMatrixWorld(e5); } updateWorldMatrix(e5, t4) { let n5 = this.parent; if (e5 === true && n5 !== null && n5.updateWorldMatrix(true, false), this.matrixAutoUpdate && this.updateMatrix(), this.matrixWorldAutoUpdate === true && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), t4 === true) { let i4 = this.children; for (let s2 = 0, r4 = i4.length; s2 < r4; s2++) i4[s2].updateWorldMatrix(false, true); } } toJSON(e5) { let t4 = e5 === void 0 || typeof e5 == "string", n5 = {}; t4 && (e5 = { geometries: {}, materials: {}, textures: {}, images: {}, shapes: {}, skeletons: {}, animations: {}, nodes: {} }, n5.metadata = { version: 4.7, type: "Object", generator: "Object3D.toJSON" }); let i4 = {}; i4.uuid = this.uuid, i4.type = this.type, this.name !== "" && (i4.name = this.name), this.castShadow === true && (i4.castShadow = true), this.receiveShadow === true && (i4.receiveShadow = true), this.visible === false && (i4.visible = false), this.frustumCulled === false && (i4.frustumCulled = false), this.renderOrder !== 0 && (i4.renderOrder = this.renderOrder), this.static !== false && (i4.static = this.static), Object.keys(this.userData).length > 0 && (i4.userData = this.userData), i4.layers = this.layers.mask, i4.matrix = this.matrix.toArray(), i4.up = this.up.toArray(), this.pivot !== null && (i4.pivot = this.pivot.toArray()), this.matrixAutoUpdate === false && (i4.matrixAutoUpdate = false), this.morphTargetDictionary !== void 0 && (i4.morphTargetDictionary = Object.assign({}, this.morphTargetDictionary)), this.morphTargetInfluences !== void 0 && (i4.morphTargetInfluences = this.morphTargetInfluences.slice()), this.isInstancedMesh && (i4.type = "InstancedMesh", i4.count = this.count, i4.instanceMatrix = this.instanceMatrix.toJSON(), this.instanceColor !== null && (i4.instanceColor = this.instanceColor.toJSON())), this.isBatchedMesh && (i4.type = "BatchedMesh", i4.perObjectFrustumCulled = this.perObjectFrustumCulled, i4.sortObjects = this.sortObjects, i4.drawRanges = this._drawRanges, i4.reservedRanges = this._reservedRanges, i4.geometryInfo = this._geometryInfo.map((a3) => ({ ...a3, boundingBox: a3.boundingBox ? a3.boundingBox.toJSON() : void 0, boundingSphere: a3.boundingSphere ? a3.boundingSphere.toJSON() : void 0 })), i4.instanceInfo = this._instanceInfo.map((a3) => ({ ...a3 })), i4.availableInstanceIds = this._availableInstanceIds.slice(), i4.availableGeometryIds = this._availableGeometryIds.slice(), i4.nextIndexStart = this._nextIndexStart, i4.nextVertexStart = this._nextVertexStart, i4.geometryCount = this._geometryCount, i4.maxInstanceCount = this._maxInstanceCount, i4.maxVertexCount = this._maxVertexCount, i4.maxIndexCount = this._maxIndexCount, i4.geometryInitialized = this._geometryInitialized, i4.matricesTexture = this._matricesTexture.toJSON(e5), i4.indirectTexture = this._indirectTexture.toJSON(e5), this._colorsTexture !== null && (i4.colorsTexture = this._colorsTexture.toJSON(e5)), this.boundingSphere !== null && (i4.boundingSphere = this.boundingSphere.toJSON()), this.boundingBox !== null && (i4.boundingBox = this.boundingBox.toJSON())); function s2(a3, c2) { return a3[c2.uuid] === void 0 && (a3[c2.uuid] = c2.toJSON(e5)), c2.uuid; } if (this.isScene) this.background && (this.background.isColor ? i4.background = this.background.toJSON() : this.background.isTexture && (i4.background = this.background.toJSON(e5).uuid)), this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true && (i4.environment = this.environment.toJSON(e5).uuid); else if (this.isMesh || this.isLine || this.isPoints) { i4.geometry = s2(e5.geometries, this.geometry); let a3 = this.geometry.parameters; if (a3 !== void 0 && a3.shapes !== void 0) { let c2 = a3.shapes; if (Array.isArray(c2)) for (let o3 = 0, h2 = c2.length; o3 < h2; o3++) { let u2 = c2[o3]; s2(e5.shapes, u2); } else s2(e5.shapes, c2); } } if (this.isSkinnedMesh && (i4.bindMode = this.bindMode, i4.bindMatrix = this.bindMatrix.toArray(), this.skeleton !== void 0 && (s2(e5.skeletons, this.skeleton), i4.skeleton = this.skeleton.uuid)), this.material !== void 0) if (Array.isArray(this.material)) { let a3 = []; for (let c2 = 0, o3 = this.material.length; c2 < o3; c2++) a3.push(s2(e5.materials, this.material[c2])); i4.material = a3; } else i4.material = s2(e5.materials, this.material); if (this.children.length > 0) { i4.children = []; for (let a3 = 0; a3 < this.children.length; a3++) i4.children.push(this.children[a3].toJSON(e5).object); } if (this.animations.length > 0) { i4.animations = []; for (let a3 = 0; a3 < this.animations.length; a3++) { let c2 = this.animations[a3]; i4.animations.push(s2(e5.animations, c2)); } } if (t4) { let a3 = r4(e5.geometries), c2 = r4(e5.materials), o3 = r4(e5.textures), h2 = r4(e5.images), u2 = r4(e5.shapes), d2 = r4(e5.skeletons), f2 = r4(e5.animations), m3 = r4(e5.nodes); a3.length > 0 && (n5.geometries = a3), c2.length > 0 && (n5.materials = c2), o3.length > 0 && (n5.textures = o3), h2.length > 0 && (n5.images = h2), u2.length > 0 && (n5.shapes = u2), d2.length > 0 && (n5.skeletons = d2), f2.length > 0 && (n5.animations = f2), m3.length > 0 && (n5.nodes = m3); } return n5.object = i4, n5; function r4(a3) { let c2 = []; for (let o3 in a3) { let h2 = a3[o3]; delete h2.metadata, c2.push(h2); } return c2; } } clone(e5) { return new this.constructor().copy(this, e5); } copy(e5, t4 = true) { if (this.name = e5.name, this.up.copy(e5.up), this.position.copy(e5.position), this.rotation.order = e5.rotation.order, this.quaternion.copy(e5.quaternion), this.scale.copy(e5.scale), this.pivot = e5.pivot !== null ? e5.pivot.clone() : null, this.matrix.copy(e5.matrix), this.matrixWorld.copy(e5.matrixWorld), this.matrixAutoUpdate = e5.matrixAutoUpdate, this.matrixWorldAutoUpdate = e5.matrixWorldAutoUpdate, this.matrixWorldNeedsUpdate = e5.matrixWorldNeedsUpdate, this.layers.mask = e5.layers.mask, this.visible = e5.visible, this.castShadow = e5.castShadow, this.receiveShadow = e5.receiveShadow, this.frustumCulled = e5.frustumCulled, this.renderOrder = e5.renderOrder, this.static = e5.static, this.animations = e5.animations.slice(), this.userData = JSON.parse(JSON.stringify(e5.userData)), t4 === true) for (let n5 = 0; n5 < e5.children.length; n5++) { let i4 = e5.children[n5]; this.add(i4.clone()); } return this; } }; ve.DEFAULT_UP = new w(0, 1, 0); ve.DEFAULT_MATRIX_AUTO_UPDATE = true; ve.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; var mn = { aliceblue: 15792383, antiquewhite: 16444375, aqua: 65535, aquamarine: 8388564, azure: 15794175, beige: 16119260, bisque: 16770244, black: 0, blanchedalmond: 16772045, blue: 255, blueviolet: 9055202, brown: 10824234, burlywood: 14596231, cadetblue: 6266528, chartreuse: 8388352, chocolate: 13789470, coral: 16744272, cornflowerblue: 6591981, cornsilk: 16775388, crimson: 14423100, cyan: 65535, darkblue: 139, darkcyan: 35723, darkgoldenrod: 12092939, darkgray: 11119017, darkgreen: 25600, darkgrey: 11119017, darkkhaki: 12433259, darkmagenta: 9109643, darkolivegreen: 5597999, darkorange: 16747520, darkorchid: 10040012, darkred: 9109504, darksalmon: 15308410, darkseagreen: 9419919, darkslateblue: 4734347, darkslategray: 3100495, darkslategrey: 3100495, darkturquoise: 52945, darkviolet: 9699539, deeppink: 16716947, deepskyblue: 49151, dimgray: 6908265, dimgrey: 6908265, dodgerblue: 2003199, firebrick: 11674146, floralwhite: 16775920, forestgreen: 2263842, fuchsia: 16711935, gainsboro: 14474460, ghostwhite: 16316671, gold: 16766720, goldenrod: 14329120, gray: 8421504, green: 32768, greenyellow: 11403055, grey: 8421504, honeydew: 15794160, hotpink: 16738740, indianred: 13458524, indigo: 4915330, ivory: 16777200, khaki: 15787660, lavender: 15132410, lavenderblush: 16773365, lawngreen: 8190976, lemonchiffon: 16775885, lightblue: 11393254, lightcoral: 15761536, lightcyan: 14745599, lightgoldenrodyellow: 16448210, lightgray: 13882323, lightgreen: 9498256, lightgrey: 13882323, lightpink: 16758465, lightsalmon: 16752762, lightseagreen: 2142890, lightskyblue: 8900346, lightslategray: 7833753, lightslategrey: 7833753, lightsteelblue: 11584734, lightyellow: 16777184, lime: 65280, limegreen: 3329330, linen: 16445670, magenta: 16711935, maroon: 8388608, mediumaquamarine: 6737322, mediumblue: 205, mediumorchid: 12211667, mediumpurple: 9662683, mediumseagreen: 3978097, mediumslateblue: 8087790, mediumspringgreen: 64154, mediumturquoise: 4772300, mediumvioletred: 13047173, midnightblue: 1644912, mintcream: 16121850, mistyrose: 16770273, moccasin: 16770229, navajowhite: 16768685, navy: 128, oldlace: 16643558, olive: 8421376, olivedrab: 7048739, orange: 16753920, orangered: 16729344, orchid: 14315734, palegoldenrod: 15657130, palegreen: 10025880, paleturquoise: 11529966, palevioletred: 14381203, papayawhip: 16773077, peachpuff: 16767673, peru: 13468991, pink: 16761035, plum: 14524637, powderblue: 11591910, purple: 8388736, rebeccapurple: 6697881, red: 16711680, rosybrown: 12357519, royalblue: 4286945, saddlebrown: 9127187, salmon: 16416882, sandybrown: 16032864, seagreen: 3050327, seashell: 16774638, sienna: 10506797, silver: 12632256, skyblue: 8900331, slateblue: 6970061, slategray: 7372944, slategrey: 7372944, snow: 16775930, springgreen: 65407, steelblue: 4620980, tan: 13808780, teal: 32896, thistle: 14204888, tomato: 16737095, turquoise: 4251856, violet: 15631086, wheat: 16113331, white: 16777215, whitesmoke: 16119285, yellow: 16776960, yellowgreen: 10145074 }; var ee = { h: 0, s: 0, l: 0 }; var Ce = { h: 0, s: 0, l: 0 }; function We(l13, e5, t4) { return t4 < 0 && (t4 += 1), t4 > 1 && (t4 -= 1), t4 < 1 / 6 ? l13 + (e5 - l13) * 6 * t4 : t4 < 1 / 2 ? e5 : t4 < 2 / 3 ? l13 + (e5 - l13) * 6 * (2 / 3 - t4) : l13; } var N = class { constructor(e5, t4, n5) { return this.isColor = true, this.r = 1, this.g = 1, this.b = 1, this.set(e5, t4, n5); } set(e5, t4, n5) { if (t4 === void 0 && n5 === void 0) { let i4 = e5; i4 && i4.isColor ? this.copy(i4) : typeof i4 == "number" ? this.setHex(i4) : typeof i4 == "string" && this.setStyle(i4); } else this.setRGB(e5, t4, n5); return this; } setScalar(e5) { return this.r = e5, this.g = e5, this.b = e5, this; } setHex(e5, t4 = X) { return e5 = Math.floor(e5), this.r = (e5 >> 16 & 255) / 255, this.g = (e5 >> 8 & 255) / 255, this.b = (e5 & 255) / 255, W.colorSpaceToWorking(this, t4), this; } setRGB(e5, t4, n5, i4 = W.workingColorSpace) { return this.r = e5, this.g = t4, this.b = n5, W.colorSpaceToWorking(this, i4), this; } setHSL(e5, t4, n5, i4 = W.workingColorSpace) { if (e5 = Un(e5, 1), t4 = E(t4, 0, 1), n5 = E(n5, 0, 1), t4 === 0) this.r = this.g = this.b = n5; else { let s2 = n5 <= 0.5 ? n5 * (1 + t4) : n5 + t4 - n5 * t4, r4 = 2 * n5 - s2; this.r = We(r4, s2, e5 + 1 / 3), this.g = We(r4, s2, e5), this.b = We(r4, s2, e5 - 1 / 3); } return W.colorSpaceToWorking(this, i4), this; } setStyle(e5, t4 = X) { function n5(s2) { s2 !== void 0 && parseFloat(s2) < 1 && z("Color: Alpha component of " + e5 + " will be ignored."); } let i4; if (i4 = /^(\w+)\(([^\)]*)\)/.exec(e5)) { let s2, r4 = i4[1], a3 = i4[2]; switch (r4) { case "rgb": case "rgba": if (s2 = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a3)) return n5(s2[4]), this.setRGB(Math.min(255, parseInt(s2[1], 10)) / 255, Math.min(255, parseInt(s2[2], 10)) / 255, Math.min(255, parseInt(s2[3], 10)) / 255, t4); if (s2 = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a3)) return n5(s2[4]), this.setRGB(Math.min(100, parseInt(s2[1], 10)) / 100, Math.min(100, parseInt(s2[2], 10)) / 100, Math.min(100, parseInt(s2[3], 10)) / 100, t4); break; case "hsl": case "hsla": if (s2 = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a3)) return n5(s2[4]), this.setHSL(parseFloat(s2[1]) / 360, parseFloat(s2[2]) / 100, parseFloat(s2[3]) / 100, t4); break; default: z("Color: Unknown color model " + e5); } } else if (i4 = /^\#([A-Fa-f\d]+)$/.exec(e5)) { let s2 = i4[1], r4 = s2.length; if (r4 === 3) return this.setRGB(parseInt(s2.charAt(0), 16) / 15, parseInt(s2.charAt(1), 16) / 15, parseInt(s2.charAt(2), 16) / 15, t4); if (r4 === 6) return this.setHex(parseInt(s2, 16), t4); z("Color: Invalid hex color " + e5); } else if (e5 && e5.length > 0) return this.setColorName(e5, t4); return this; } setColorName(e5, t4 = X) { let n5 = mn[e5.toLowerCase()]; return n5 !== void 0 ? this.setHex(n5, t4) : z("Color: Unknown color " + e5), this; } clone() { return new this.constructor(this.r, this.g, this.b); } copy(e5) { return this.r = e5.r, this.g = e5.g, this.b = e5.b, this; } copySRGBToLinear(e5) { return this.r = K(e5.r), this.g = K(e5.g), this.b = K(e5.b), this; } copyLinearToSRGB(e5) { return this.r = de(e5.r), this.g = de(e5.g), this.b = de(e5.b), this; } convertSRGBToLinear() { return this.copySRGBToLinear(this), this; } convertLinearToSRGB() { return this.copyLinearToSRGB(this), this; } getHex(e5 = X) { return W.workingToColorSpace(B.copy(this), e5), Math.round(E(B.r * 255, 0, 255)) * 65536 + Math.round(E(B.g * 255, 0, 255)) * 256 + Math.round(E(B.b * 255, 0, 255)); } getHexString(e5 = X) { return ("000000" + this.getHex(e5).toString(16)).slice(-6); } getHSL(e5, t4 = W.workingColorSpace) { W.workingToColorSpace(B.copy(this), t4); let n5 = B.r, i4 = B.g, s2 = B.b, r4 = Math.max(n5, i4, s2), a3 = Math.min(n5, i4, s2), c2, o3, h2 = (a3 + r4) / 2; if (a3 === r4) c2 = 0, o3 = 0; else { let u2 = r4 - a3; switch (o3 = h2 <= 0.5 ? u2 / (r4 + a3) : u2 / (2 - r4 - a3), r4) { case n5: c2 = (i4 - s2) / u2 + (i4 < s2 ? 6 : 0); break; case i4: c2 = (s2 - n5) / u2 + 2; break; case s2: c2 = (n5 - i4) / u2 + 4; break; } c2 /= 6; } return e5.h = c2, e5.s = o3, e5.l = h2, e5; } getRGB(e5, t4 = W.workingColorSpace) { return W.workingToColorSpace(B.copy(this), t4), e5.r = B.r, e5.g = B.g, e5.b = B.b, e5; } getStyle(e5 = X) { W.workingToColorSpace(B.copy(this), e5); let t4 = B.r, n5 = B.g, i4 = B.b; return e5 !== X ? `color(${e5} ${t4.toFixed(3)} ${n5.toFixed(3)} ${i4.toFixed(3)})` : `rgb(${Math.round(t4 * 255)},${Math.round(n5 * 255)},${Math.round(i4 * 255)})`; } offsetHSL(e5, t4, n5) { return this.getHSL(ee), this.setHSL(ee.h + e5, ee.s + t4, ee.l + n5); } add(e5) { return this.r += e5.r, this.g += e5.g, this.b += e5.b, this; } addColors(e5, t4) { return this.r = e5.r + t4.r, this.g = e5.g + t4.g, this.b = e5.b + t4.b, this; } addScalar(e5) { return this.r += e5, this.g += e5, this.b += e5, this; } sub(e5) { return this.r = Math.max(0, this.r - e5.r), this.g = Math.max(0, this.g - e5.g), this.b = Math.max(0, this.b - e5.b), this; } multiply(e5) { return this.r *= e5.r, this.g *= e5.g, this.b *= e5.b, this; } multiplyScalar(e5) { return this.r *= e5, this.g *= e5, this.b *= e5, this; } lerp(e5, t4) { return this.r += (e5.r - this.r) * t4, this.g += (e5.g - this.g) * t4, this.b += (e5.b - this.b) * t4, this; } lerpColors(e5, t4, n5) { return this.r = e5.r + (t4.r - e5.r) * n5, this.g = e5.g + (t4.g - e5.g) * n5, this.b = e5.b + (t4.b - e5.b) * n5, this; } lerpHSL(e5, t4) { this.getHSL(ee), e5.getHSL(Ce); let n5 = Be(ee.h, Ce.h, t4), i4 = Be(ee.s, Ce.s, t4), s2 = Be(ee.l, Ce.l, t4); return this.setHSL(n5, i4, s2), this; } setFromVector3(e5) { return this.r = e5.x, this.g = e5.y, this.b = e5.z, this; } applyMatrix3(e5) { let t4 = this.r, n5 = this.g, i4 = this.b, s2 = e5.elements; return this.r = s2[0] * t4 + s2[3] * n5 + s2[6] * i4, this.g = s2[1] * t4 + s2[4] * n5 + s2[7] * i4, this.b = s2[2] * t4 + s2[5] * n5 + s2[8] * i4, this; } equals(e5) { return e5.r === this.r && e5.g === this.g && e5.b === this.b; } fromArray(e5, t4 = 0) { return this.r = e5[t4], this.g = e5[t4 + 1], this.b = e5[t4 + 2], this; } toArray(e5 = [], t4 = 0) { return e5[t4] = this.r, e5[t4 + 1] = this.g, e5[t4 + 2] = this.b, e5; } fromBufferAttribute(e5, t4) { return this.r = e5.getX(t4), this.g = e5.getY(t4), this.b = e5.getZ(t4), this; } toJSON() { return this.getHex(); } *[Symbol.iterator]() { yield this.r, yield this.g, yield this.b; } }; var B = new N(); N.NAMES = mn; function gn(l13) { let e5 = {}; for (let t4 in l13) { e5[t4] = {}; for (let n5 in l13[t4]) { let i4 = l13[t4][n5]; if (jt(i4)) i4.isRenderTargetTexture ? (z("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."), e5[t4][n5] = null) : e5[t4][n5] = i4.clone(); else if (Array.isArray(i4)) if (jt(i4[0])) { let s2 = []; for (let r4 = 0, a3 = i4.length; r4 < a3; r4++) s2[r4] = i4[r4].clone(); e5[t4][n5] = s2; } else e5[t4][n5] = i4.slice(); else e5[t4][n5] = i4; } } return e5; } function V(l13) { let e5 = {}; for (let t4 = 0; t4 < l13.length; t4++) { let n5 = gn(l13[t4]); for (let i4 in n5) e5[i4] = n5[i4]; } return e5; } function jt(l13) { return l13 && (l13.isColor || l13.isMatrix3 || l13.isMatrix4 || l13.isVector2 || l13.isVector3 || l13.isVector4 || l13.isTexture || l13.isQuaternion); } function Re(l13, e5) { return !l13 || l13.constructor === e5 ? l13 : typeof e5.BYTES_PER_ELEMENT == "number" ? new e5(l13) : Array.prototype.slice.call(l13); } var se = class { constructor(e5, t4, n5, i4) { this.parameterPositions = e5, this._cachedIndex = 0, this.resultBuffer = i4 !== void 0 ? i4 : new t4.constructor(n5), this.sampleValues = t4, this.valueSize = n5, this.settings = null, this.DefaultSettings_ = {}; } evaluate(e5) { let t4 = this.parameterPositions, n5 = this._cachedIndex, i4 = t4[n5], s2 = t4[n5 - 1]; n: { e: { let r4; t: { i: if (!(e5 < i4)) { for (let a3 = n5 + 2; ; ) { if (i4 === void 0) { if (e5 < s2) break i; return n5 = t4.length, this._cachedIndex = n5, this.copySampleValue_(n5 - 1); } if (n5 === a3) break; if (s2 = i4, i4 = t4[++n5], e5 < i4) break e; } r4 = t4.length; break t; } if (!(e5 >= s2)) { let a3 = t4[1]; e5 < a3 && (n5 = 2, s2 = a3); for (let c2 = n5 - 2; ; ) { if (s2 === void 0) return this._cachedIndex = 0, this.copySampleValue_(0); if (n5 === c2) break; if (i4 = s2, s2 = t4[--n5 - 1], e5 >= s2) break e; } r4 = n5, n5 = 0; break t; } break n; } for (; n5 < r4; ) { let a3 = n5 + r4 >>> 1; e5 < t4[a3] ? r4 = a3 : n5 = a3 + 1; } if (i4 = t4[n5], s2 = t4[n5 - 1], s2 === void 0) return this._cachedIndex = 0, this.copySampleValue_(0); if (i4 === void 0) return n5 = t4.length, this._cachedIndex = n5, this.copySampleValue_(n5 - 1); } this._cachedIndex = n5, this.intervalChanged_(n5, s2, i4); } return this.interpolate_(n5, s2, e5, i4); } getSettings_() { return this.settings || this.DefaultSettings_; } copySampleValue_(e5) { let t4 = this.resultBuffer, n5 = this.sampleValues, i4 = this.valueSize, s2 = e5 * i4; for (let r4 = 0; r4 !== i4; ++r4) t4[r4] = n5[s2 + r4]; return t4; } interpolate_() { throw new Error("call to abstract method"); } intervalChanged_() { } }; var ct = class extends se { constructor(e5, t4, n5, i4) { super(e5, t4, n5, i4), this._weightPrev = -0, this._offsetPrev = -0, this._weightNext = -0, this._offsetNext = -0, this.DefaultSettings_ = { endingStart: Bt, endingEnd: Bt }; } intervalChanged_(e5, t4, n5) { let i4 = this.parameterPositions, s2 = e5 - 2, r4 = e5 + 1, a3 = i4[s2], c2 = i4[r4]; if (a3 === void 0) switch (this.getSettings_().endingStart) { case zt: s2 = e5, a3 = 2 * t4 - n5; break; case Vt: s2 = i4.length - 2, a3 = t4 + i4[s2] - i4[s2 + 1]; break; default: s2 = e5, a3 = n5; } if (c2 === void 0) switch (this.getSettings_().endingEnd) { case zt: r4 = e5, c2 = 2 * n5 - t4; break; case Vt: r4 = 1, c2 = n5 + i4[1] - i4[0]; break; default: r4 = e5 - 1, c2 = t4; } let o3 = (n5 - t4) * 0.5, h2 = this.valueSize; this._weightPrev = o3 / (t4 - a3), this._weightNext = o3 / (c2 - n5), this._offsetPrev = s2 * h2, this._offsetNext = r4 * h2; } interpolate_(e5, t4, n5, i4) { let s2 = this.resultBuffer, r4 = this.sampleValues, a3 = this.valueSize, c2 = e5 * a3, o3 = c2 - a3, h2 = this._offsetPrev, u2 = this._offsetNext, d2 = this._weightPrev, f2 = this._weightNext, m3 = (n5 - t4) / (i4 - t4), p2 = m3 * m3, _2 = p2 * m3, g2 = -d2 * _2 + 2 * d2 * p2 - d2 * m3, v2 = (1 + d2) * _2 + (-1.5 - 2 * d2) * p2 + (-0.5 + d2) * m3 + 1, M = (-1 - f2) * _2 + (1.5 + f2) * p2 + 0.5 * m3, S2 = f2 * _2 - f2 * p2; for (let y2 = 0; y2 !== a3; ++y2) s2[y2] = g2 * r4[h2 + y2] + v2 * r4[o3 + y2] + M * r4[c2 + y2] + S2 * r4[u2 + y2]; return s2; } }; var ht = class extends se { constructor(e5, t4, n5, i4) { super(e5, t4, n5, i4); } interpolate_(e5, t4, n5, i4) { let s2 = this.resultBuffer, r4 = this.sampleValues, a3 = this.valueSize, c2 = e5 * a3, o3 = c2 - a3, h2 = (n5 - t4) / (i4 - t4), u2 = 1 - h2; for (let d2 = 0; d2 !== a3; ++d2) s2[d2] = r4[o3 + d2] * u2 + r4[c2 + d2] * h2; return s2; } }; var ut = class extends se { constructor(e5, t4, n5, i4) { super(e5, t4, n5, i4); } interpolate_(e5) { return this.copySampleValue_(e5 - 1); } }; var dt = class extends se { interpolate_(e5, t4, n5, i4) { let s2 = this.resultBuffer, r4 = this.sampleValues, a3 = this.valueSize, c2 = e5 * a3, o3 = c2 - a3, h2 = this.settings || this.DefaultSettings_, u2 = h2.inTangents, d2 = h2.outTangents; if (!u2 || !d2) { let p2 = (n5 - t4) / (i4 - t4), _2 = 1 - p2; for (let g2 = 0; g2 !== a3; ++g2) s2[g2] = r4[o3 + g2] * _2 + r4[c2 + g2] * p2; return s2; } let f2 = a3 * 2, m3 = e5 - 1; for (let p2 = 0; p2 !== a3; ++p2) { let _2 = r4[o3 + p2], g2 = r4[c2 + p2], v2 = m3 * f2 + p2 * 2, M = d2[v2], S2 = d2[v2 + 1], y2 = e5 * f2 + p2 * 2, A2 = u2[y2], C2 = u2[y2 + 1], R2 = (n5 - t4) / (i4 - t4), U, k, D, F2, G; for (let J = 0; J < 8; J++) { U = R2 * R2, k = U * R2, D = 1 - R2, F2 = D * D, G = F2 * D; let ne = G * t4 + 3 * F2 * R2 * M + 3 * D * U * A2 + k * i4 - n5; if (Math.abs(ne) < 1e-10) break; let ie = 3 * F2 * (M - t4) + 6 * D * R2 * (A2 - M) + 3 * U * (i4 - A2); if (Math.abs(ie) < 1e-10) break; R2 = R2 - ne / ie, R2 = Math.max(0, Math.min(1, R2)); } s2[p2] = G * _2 + 3 * F2 * R2 * S2 + 3 * D * U * C2 + k * g2; } return s2; } }; var q = class { constructor(e5, t4, n5, i4) { if (e5 === void 0) throw new Error("THREE.KeyframeTrack: track name is undefined"); if (t4 === void 0 || t4.length === 0) throw new Error("THREE.KeyframeTrack: no keyframes in track named " + e5); this.name = e5, this.times = Re(t4, this.TimeBufferType), this.values = Re(n5, this.ValueBufferType), this.setInterpolation(i4 || this.DefaultInterpolation); } static toJSON(e5) { let t4 = e5.constructor, n5; if (t4.toJSON !== this.toJSON) n5 = t4.toJSON(e5); else { n5 = { name: e5.name, times: Re(e5.times, Array), values: Re(e5.values, Array) }; let i4 = e5.getInterpolation(); i4 !== e5.DefaultInterpolation && (n5.interpolation = i4); } return n5.type = e5.ValueTypeName, n5; } InterpolantFactoryMethodDiscrete(e5) { return new ut(this.times, this.values, this.getValueSize(), e5); } InterpolantFactoryMethodLinear(e5) { return new ht(this.times, this.values, this.getValueSize(), e5); } InterpolantFactoryMethodSmooth(e5) { return new ct(this.times, this.values, this.getValueSize(), e5); } InterpolantFactoryMethodBezier(e5) { let t4 = new dt(this.times, this.values, this.getValueSize(), e5); return this.settings && (t4.settings = this.settings), t4; } setInterpolation(e5) { let t4; switch (e5) { case Pe: t4 = this.InterpolantFactoryMethodDiscrete; break; case tt: t4 = this.InterpolantFactoryMethodLinear; break; case Oe: t4 = this.InterpolantFactoryMethodSmooth; break; case Ot: t4 = this.InterpolantFactoryMethodBezier; break; } if (t4 === void 0) { let n5 = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; if (this.createInterpolant === void 0) if (e5 !== this.DefaultInterpolation) this.setInterpolation(this.DefaultInterpolation); else throw new Error(n5); return z("KeyframeTrack:", n5), this; } return this.createInterpolant = t4, this; } getInterpolation() { switch (this.createInterpolant) { case this.InterpolantFactoryMethodDiscrete: return Pe; case this.InterpolantFactoryMethodLinear: return tt; case this.InterpolantFactoryMethodSmooth: return Oe; case this.InterpolantFactoryMethodBezier: return Ot; } } getValueSize() { return this.values.length / this.times.length; } shift(e5) { if (e5 !== 0) { let t4 = this.times; for (let n5 = 0, i4 = t4.length; n5 !== i4; ++n5) t4[n5] += e5; } return this; } scale(e5) { if (e5 !== 1) { let t4 = this.times; for (let n5 = 0, i4 = t4.length; n5 !== i4; ++n5) t4[n5] *= e5; } return this; } trim(e5, t4) { let n5 = this.times, i4 = n5.length, s2 = 0, r4 = i4 - 1; for (; s2 !== i4 && n5[s2] < e5; ) ++s2; for (; r4 !== -1 && n5[r4] > t4; ) --r4; if (++r4, s2 !== 0 || r4 !== i4) { s2 >= r4 && (r4 = Math.max(r4, 1), s2 = r4 - 1); let a3 = this.getValueSize(); this.times = n5.slice(s2, r4), this.values = this.values.slice(s2 * a3, r4 * a3); } return this; } validate() { let e5 = true, t4 = this.getValueSize(); t4 - Math.floor(t4) !== 0 && (L("KeyframeTrack: Invalid value size in track.", this), e5 = false); let n5 = this.times, i4 = this.values, s2 = n5.length; s2 === 0 && (L("KeyframeTrack: Track is empty.", this), e5 = false); let r4 = null; for (let a3 = 0; a3 !== s2; a3++) { let c2 = n5[a3]; if (typeof c2 == "number" && isNaN(c2)) { L("KeyframeTrack: Time is not a valid number.", this, a3, c2), e5 = false; break; } if (r4 !== null && r4 > c2) { L("KeyframeTrack: Out of order keys.", this, a3, c2, r4), e5 = false; break; } r4 = c2; } if (i4 !== void 0 && Dn(i4)) for (let a3 = 0, c2 = i4.length; a3 !== c2; ++a3) { let o3 = i4[a3]; if (isNaN(o3)) { L("KeyframeTrack: Value is not a valid number.", this, a3, o3), e5 = false; break; } } return e5; } optimize() { let e5 = this.times.slice(), t4 = this.values.slice(), n5 = this.getValueSize(), i4 = this.getInterpolation() === Oe, s2 = e5.length - 1, r4 = 1; for (let a3 = 1; a3 < s2; ++a3) { let c2 = false, o3 = e5[a3], h2 = e5[a3 + 1]; if (o3 !== h2 && (a3 !== 1 || o3 !== e5[0])) if (i4) c2 = true; else { let u2 = a3 * n5, d2 = u2 - n5, f2 = u2 + n5; for (let m3 = 0; m3 !== n5; ++m3) { let p2 = t4[u2 + m3]; if (p2 !== t4[d2 + m3] || p2 !== t4[f2 + m3]) { c2 = true; break; } } } if (c2) { if (a3 !== r4) { e5[r4] = e5[a3]; let u2 = a3 * n5, d2 = r4 * n5; for (let f2 = 0; f2 !== n5; ++f2) t4[d2 + f2] = t4[u2 + f2]; } ++r4; } } if (s2 > 0) { e5[r4] = e5[s2]; for (let a3 = s2 * n5, c2 = r4 * n5, o3 = 0; o3 !== n5; ++o3) t4[c2 + o3] = t4[a3 + o3]; ++r4; } return r4 !== e5.length ? (this.times = e5.slice(0, r4), this.values = t4.slice(0, r4 * n5)) : (this.times = e5, this.values = t4), this; } clone() { let e5 = this.times.slice(), t4 = this.values.slice(), n5 = this.constructor, i4 = new n5(this.name, e5, t4); return i4.createInterpolant = this.createInterpolant, i4; } }; q.prototype.ValueTypeName = ""; q.prototype.TimeBufferType = Float32Array; q.prototype.ValueBufferType = Float32Array; q.prototype.DefaultInterpolation = tt; var re = class extends q { constructor(e5, t4, n5) { super(e5, t4, n5); } }; re.prototype.ValueTypeName = "bool"; re.prototype.ValueBufferType = Array; re.prototype.DefaultInterpolation = Pe; re.prototype.InterpolantFactoryMethodLinear = void 0; re.prototype.InterpolantFactoryMethodSmooth = void 0; var ft = class extends q { constructor(e5, t4, n5, i4) { super(e5, t4, n5, i4); } }; ft.prototype.ValueTypeName = "color"; var pt = class extends q { constructor(e5, t4, n5, i4) { super(e5, t4, n5, i4); } }; pt.prototype.ValueTypeName = "number"; var mt = class extends se { constructor(e5, t4, n5, i4) { super(e5, t4, n5, i4); } interpolate_(e5, t4, n5, i4) { let s2 = this.resultBuffer, r4 = this.sampleValues, a3 = this.valueSize, c2 = (n5 - t4) / (i4 - t4), o3 = e5 * a3; for (let h2 = o3 + a3; o3 !== h2; o3 += 4) te.slerpFlat(s2, 0, r4, o3 - a3, r4, o3, c2); return s2; } }; var Ue = class extends q { constructor(e5, t4, n5, i4) { super(e5, t4, n5, i4); } InterpolantFactoryMethodLinear(e5) { return new mt(this.times, this.values, this.getValueSize(), e5); } }; Ue.prototype.ValueTypeName = "quaternion"; Ue.prototype.InterpolantFactoryMethodSmooth = void 0; var ae = class extends q { constructor(e5, t4, n5) { super(e5, t4, n5); } }; ae.prototype.ValueTypeName = "string"; ae.prototype.ValueBufferType = Array; ae.prototype.DefaultInterpolation = Pe; ae.prototype.InterpolantFactoryMethodLinear = void 0; ae.prototype.InterpolantFactoryMethodSmooth = void 0; var gt = class extends q { constructor(e5, t4, n5, i4) { super(e5, t4, n5, i4); } }; gt.prototype.ValueTypeName = "vector"; var _t = class { constructor(e5, t4, n5) { let i4 = this, s2 = false, r4 = 0, a3 = 0, c2, o3 = []; this.onStart = void 0, this.onLoad = e5, this.onProgress = t4, this.onError = n5, this._abortController = null, this.itemStart = function(h2) { a3++, s2 === false && i4.onStart !== void 0 && i4.onStart(h2, r4, a3), s2 = true; }, this.itemEnd = function(h2) { r4++, i4.onProgress !== void 0 && i4.onProgress(h2, r4, a3), r4 === a3 && (s2 = false, i4.onLoad !== void 0 && i4.onLoad()); }, this.itemError = function(h2) { i4.onError !== void 0 && i4.onError(h2); }, this.resolveURL = function(h2) { return c2 ? c2(h2) : h2; }, this.setURLModifier = function(h2) { return c2 = h2, this; }, this.addHandler = function(h2, u2) { return o3.push(h2, u2), this; }, this.removeHandler = function(h2) { let u2 = o3.indexOf(h2); return u2 !== -1 && o3.splice(u2, 2), this; }, this.getHandler = function(h2) { for (let u2 = 0, d2 = o3.length; u2 < d2; u2 += 2) { let f2 = o3[u2], m3 = o3[u2 + 1]; if (f2.global && (f2.lastIndex = 0), f2.test(h2)) return m3; } return null; }, this.abort = function() { return this.abortController.abort(), this._abortController = null, this; }; } get abortController() { return this._abortController || (this._abortController = new AbortController()), this._abortController; } }; var Xn = new _t(); var xt = class { constructor(e5) { this.manager = e5 !== void 0 ? e5 : Xn, this.crossOrigin = "anonymous", this.withCredentials = false, this.path = "", this.resourcePath = "", this.requestHeader = {}, typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); } load() { } loadAsync(e5, t4) { let n5 = this; return new Promise(function(i4, s2) { n5.load(e5, i4, t4, s2); }); } parse() { } setCrossOrigin(e5) { return this.crossOrigin = e5, this; } setWithCredentials(e5) { return this.withCredentials = e5, this; } setPath(e5) { return this.path = e5, this; } setResourcePath(e5) { return this.resourcePath = e5, this; } setRequestHeader(e5) { return this.requestHeader = e5, this; } abort() { return this; } }; xt.DEFAULT_MATERIAL_NAME = "__DEFAULT"; var It = "\\[\\]\\.:\\/"; var qn = new RegExp("[" + It + "]", "g"); var Pt = "[^" + It + "]"; var Yn = "[^" + It.replace("\\.", "") + "]"; var Zn = /((?:WC+[\/:])*)/.source.replace("WC", Pt); var Jn = /(WCOD+)?/.source.replace("WCOD", Yn); var $n = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", Pt); var Kn = /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", Pt); var Qn = new RegExp("^" + Zn + Jn + $n + Kn + "$"); var jn = ["material", "materials", "bones", "map"]; var vt = class { constructor(e5, t4, n5) { let i4 = n5 || I.parseTrackName(t4); this._targetGroup = e5, this._bindings = e5.subscribe_(t4, i4); } getValue(e5, t4) { this.bind(); let n5 = this._targetGroup.nCachedObjects_, i4 = this._bindings[n5]; i4 !== void 0 && i4.getValue(e5, t4); } setValue(e5, t4) { let n5 = this._bindings; for (let i4 = this._targetGroup.nCachedObjects_, s2 = n5.length; i4 !== s2; ++i4) n5[i4].setValue(e5, t4); } bind() { let e5 = this._bindings; for (let t4 = this._targetGroup.nCachedObjects_, n5 = e5.length; t4 !== n5; ++t4) e5[t4].bind(); } unbind() { let e5 = this._bindings; for (let t4 = this._targetGroup.nCachedObjects_, n5 = e5.length; t4 !== n5; ++t4) e5[t4].unbind(); } }; var I = class l9 { constructor(e5, t4, n5) { this.path = t4, this.parsedPath = n5 || l9.parseTrackName(t4), this.node = l9.findNode(e5, this.parsedPath.nodeName), this.rootNode = e5, this.getValue = this._getValue_unbound, this.setValue = this._setValue_unbound; } static create(e5, t4, n5) { return e5 && e5.isAnimationObjectGroup ? new l9.Composite(e5, t4, n5) : new l9(e5, t4, n5); } static sanitizeNodeName(e5) { return e5.replace(/\s/g, "_").replace(qn, ""); } static parseTrackName(e5) { let t4 = Qn.exec(e5); if (t4 === null) throw new Error("PropertyBinding: Cannot parse trackName: " + e5); let n5 = { nodeName: t4[2], objectName: t4[3], objectIndex: t4[4], propertyName: t4[5], propertyIndex: t4[6] }, i4 = n5.nodeName && n5.nodeName.lastIndexOf("."); if (i4 !== void 0 && i4 !== -1) { let s2 = n5.nodeName.substring(i4 + 1); jn.indexOf(s2) !== -1 && (n5.nodeName = n5.nodeName.substring(0, i4), n5.objectName = s2); } if (n5.propertyName === null || n5.propertyName.length === 0) throw new Error("PropertyBinding: can not parse propertyName from trackName: " + e5); return n5; } static findNode(e5, t4) { if (t4 === void 0 || t4 === "" || t4 === "." || t4 === -1 || t4 === e5.name || t4 === e5.uuid) return e5; if (e5.skeleton) { let n5 = e5.skeleton.getBoneByName(t4); if (n5 !== void 0) return n5; } if (e5.children) { let n5 = function(s2) { for (let r4 = 0; r4 < s2.length; r4++) { let a3 = s2[r4]; if (a3.name === t4 || a3.uuid === t4) return a3; let c2 = n5(a3.children); if (c2) return c2; } return null; }, i4 = n5(e5.children); if (i4) return i4; } return null; } _getValue_unavailable() { } _setValue_unavailable() { } _getValue_direct(e5, t4) { e5[t4] = this.targetObject[this.propertyName]; } _getValue_array(e5, t4) { let n5 = this.resolvedProperty; for (let i4 = 0, s2 = n5.length; i4 !== s2; ++i4) e5[t4++] = n5[i4]; } _getValue_arrayElement(e5, t4) { e5[t4] = this.resolvedProperty[this.propertyIndex]; } _getValue_toArray(e5, t4) { this.resolvedProperty.toArray(e5, t4); } _setValue_direct(e5, t4) { this.targetObject[this.propertyName] = e5[t4]; } _setValue_direct_setNeedsUpdate(e5, t4) { this.targetObject[this.propertyName] = e5[t4], this.targetObject.needsUpdate = true; } _setValue_direct_setMatrixWorldNeedsUpdate(e5, t4) { this.targetObject[this.propertyName] = e5[t4], this.targetObject.matrixWorldNeedsUpdate = true; } _setValue_array(e5, t4) { let n5 = this.resolvedProperty; for (let i4 = 0, s2 = n5.length; i4 !== s2; ++i4) n5[i4] = e5[t4++]; } _setValue_array_setNeedsUpdate(e5, t4) { let n5 = this.resolvedProperty; for (let i4 = 0, s2 = n5.length; i4 !== s2; ++i4) n5[i4] = e5[t4++]; this.targetObject.needsUpdate = true; } _setValue_array_setMatrixWorldNeedsUpdate(e5, t4) { let n5 = this.resolvedProperty; for (let i4 = 0, s2 = n5.length; i4 !== s2; ++i4) n5[i4] = e5[t4++]; this.targetObject.matrixWorldNeedsUpdate = true; } _setValue_arrayElement(e5, t4) { this.resolvedProperty[this.propertyIndex] = e5[t4]; } _setValue_arrayElement_setNeedsUpdate(e5, t4) { this.resolvedProperty[this.propertyIndex] = e5[t4], this.targetObject.needsUpdate = true; } _setValue_arrayElement_setMatrixWorldNeedsUpdate(e5, t4) { this.resolvedProperty[this.propertyIndex] = e5[t4], this.targetObject.matrixWorldNeedsUpdate = true; } _setValue_fromArray(e5, t4) { this.resolvedProperty.fromArray(e5, t4); } _setValue_fromArray_setNeedsUpdate(e5, t4) { this.resolvedProperty.fromArray(e5, t4), this.targetObject.needsUpdate = true; } _setValue_fromArray_setMatrixWorldNeedsUpdate(e5, t4) { this.resolvedProperty.fromArray(e5, t4), this.targetObject.matrixWorldNeedsUpdate = true; } _getValue_unbound(e5, t4) { this.bind(), this.getValue(e5, t4); } _setValue_unbound(e5, t4) { this.bind(), this.setValue(e5, t4); } bind() { let e5 = this.node, t4 = this.parsedPath, n5 = t4.objectName, i4 = t4.propertyName, s2 = t4.propertyIndex; if (e5 || (e5 = l9.findNode(this.rootNode, t4.nodeName), this.node = e5), this.getValue = this._getValue_unavailable, this.setValue = this._setValue_unavailable, !e5) { z("PropertyBinding: No target node found for track: " + this.path + "."); return; } if (n5) { let o3 = t4.objectIndex; switch (n5) { case "materials": if (!e5.material) { L("PropertyBinding: Can not bind to material as node does not have a material.", this); return; } if (!e5.material.materials) { L("PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this); return; } e5 = e5.material.materials; break; case "bones": if (!e5.skeleton) { L("PropertyBinding: Can not bind to bones as node does not have a skeleton.", this); return; } e5 = e5.skeleton.bones; for (let h2 = 0; h2 < e5.length; h2++) if (e5[h2].name === o3) { o3 = h2; break; } break; case "map": if ("map" in e5) { e5 = e5.map; break; } if (!e5.material) { L("PropertyBinding: Can not bind to material as node does not have a material.", this); return; } if (!e5.material.map) { L("PropertyBinding: Can not bind to material.map as node.material does not have a map.", this); return; } e5 = e5.material.map; break; default: if (e5[n5] === void 0) { L("PropertyBinding: Can not bind to objectName of node undefined.", this); return; } e5 = e5[n5]; } if (o3 !== void 0) { if (e5[o3] === void 0) { L("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, e5); return; } e5 = e5[o3]; } } let r4 = e5[i4]; if (r4 === void 0) { let o3 = t4.nodeName; L("PropertyBinding: Trying to update property for track: " + o3 + "." + i4 + " but it wasn't found.", e5); return; } let a3 = this.Versioning.None; this.targetObject = e5, e5.isMaterial === true ? a3 = this.Versioning.NeedsUpdate : e5.isObject3D === true && (a3 = this.Versioning.MatrixWorldNeedsUpdate); let c2 = this.BindingType.Direct; if (s2 !== void 0) { if (i4 === "morphTargetInfluences") { if (!e5.geometry) { L("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this); return; } if (!e5.geometry.morphAttributes) { L("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this); return; } e5.morphTargetDictionary[s2] !== void 0 && (s2 = e5.morphTargetDictionary[s2]); } c2 = this.BindingType.ArrayElement, this.resolvedProperty = r4, this.propertyIndex = s2; } else r4.fromArray !== void 0 && r4.toArray !== void 0 ? (c2 = this.BindingType.HasFromToArray, this.resolvedProperty = r4) : Array.isArray(r4) ? (c2 = this.BindingType.EntireArray, this.resolvedProperty = r4) : this.propertyName = i4; this.getValue = this.GetterByBindingType[c2], this.setValue = this.SetterByBindingTypeAndVersioning[c2][a3]; } unbind() { this.node = null, this.getValue = this._getValue_unbound, this.setValue = this._setValue_unbound; } }; I.Composite = vt; I.prototype.BindingType = { Direct: 0, EntireArray: 1, ArrayElement: 2, HasFromToArray: 3 }; I.prototype.Versioning = { None: 0, NeedsUpdate: 1, MatrixWorldNeedsUpdate: 2 }; I.prototype.GetterByBindingType = [I.prototype._getValue_direct, I.prototype._getValue_array, I.prototype._getValue_arrayElement, I.prototype._getValue_toArray]; I.prototype.SetterByBindingTypeAndVersioning = [[I.prototype._setValue_direct, I.prototype._setValue_direct_setNeedsUpdate, I.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [I.prototype._setValue_array, I.prototype._setValue_array_setNeedsUpdate, I.prototype._setValue_array_setMatrixWorldNeedsUpdate], [I.prototype._setValue_arrayElement, I.prototype._setValue_arrayElement_setNeedsUpdate, I.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [I.prototype._setValue_fromArray, I.prototype._setValue_fromArray_setNeedsUpdate, I.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]]; var ga = new Float32Array(1); var en = class l10 { static { l10.prototype.isMatrix2 = true; } constructor(e5, t4, n5, i4) { this.elements = [1, 0, 0, 1], e5 !== void 0 && this.set(e5, t4, n5, i4); } identity() { return this.set(1, 0, 0, 1), this; } fromArray(e5, t4 = 0) { for (let n5 = 0; n5 < 4; n5++) this.elements[n5] = e5[n5 + t4]; return this; } set(e5, t4, n5, i4) { let s2 = this.elements; return s2[0] = e5, s2[2] = t4, s2[1] = n5, s2[3] = i4, this; } }; typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { revision: "184" } })); typeof window < "u" && (window.__THREE__ ? z("WARNING: Multiple instances of Three.js being imported.") : window.__THREE__ = "184"); var ei = `#ifdef USE_ALPHAHASH if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard; #endif`; var ti = `#ifdef USE_ALPHAHASH const float ALPHA_HASH_SCALE = 0.05; float hash2D( vec2 value ) { return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) ); } float hash3D( vec3 value ) { return hash2D( vec2( hash2D( value.xy ), value.z ) ); } float getAlphaHashThreshold( vec3 position ) { float maxDeriv = max( length( dFdx( position.xyz ) ), length( dFdy( position.xyz ) ) ); float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv ); vec2 pixScales = vec2( exp2( floor( log2( pixScale ) ) ), exp2( ceil( log2( pixScale ) ) ) ); vec2 alpha = vec2( hash3D( floor( pixScales.x * position.xyz ) ), hash3D( floor( pixScales.y * position.xyz ) ) ); float lerpFactor = fract( log2( pixScale ) ); float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y; float a = min( lerpFactor, 1.0 - lerpFactor ); vec3 cases = vec3( x * x / ( 2.0 * a * ( 1.0 - a ) ), ( x - 0.5 * a ) / ( 1.0 - a ), 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) ) ); float threshold = ( x < ( 1.0 - a ) ) ? ( ( x < a ) ? cases.x : cases.y ) : cases.z; return clamp( threshold , 1.0e-6, 1.0 ); } #endif`; var ni = `#ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g; #endif`; var ii = `#ifdef USE_ALPHAMAP uniform sampler2D alphaMap; #endif`; var si = `#ifdef USE_ALPHATEST #ifdef ALPHA_TO_COVERAGE diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a ); if ( diffuseColor.a == 0.0 ) discard; #else if ( diffuseColor.a < alphaTest ) discard; #endif #endif`; var ri = `#ifdef USE_ALPHATEST uniform float alphaTest; #endif`; var ai = `#ifdef USE_AOMAP float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0; reflectedLight.indirectDiffuse *= ambientOcclusion; #if defined( USE_CLEARCOAT ) clearcoatSpecularIndirect *= ambientOcclusion; #endif #if defined( USE_SHEEN ) sheenSpecularIndirect *= ambientOcclusion; #endif #if defined( USE_ENVMAP ) && defined( STANDARD ) float dotNV = saturate( dot( geometryNormal, geometryViewDir ) ); reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness ); #endif #endif`; var oi = `#ifdef USE_AOMAP uniform sampler2D aoMap; uniform float aoMapIntensity; #endif`; var li = `#ifdef USE_BATCHING #if ! defined( GL_ANGLE_multi_draw ) #define gl_DrawID _gl_DrawID uniform int _gl_DrawID; #endif uniform highp sampler2D batchingTexture; uniform highp usampler2D batchingIdTexture; mat4 getBatchingMatrix( const in float i ) { int size = textureSize( batchingTexture, 0 ).x; int j = int( i ) * 4; int x = j % size; int y = j / size; vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 ); vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 ); vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 ); vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } float getIndirectIndex( const in int i ) { int size = textureSize( batchingIdTexture, 0 ).x; int x = i % size; int y = i / size; return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r ); } #endif #ifdef USE_BATCHING_COLOR uniform sampler2D batchingColorTexture; vec4 getBatchingColor( const in float i ) { int size = textureSize( batchingColorTexture, 0 ).x; int j = int( i ); int x = j % size; int y = j / size; return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ); } #endif`; var ci = `#ifdef USE_BATCHING mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) ); #endif`; var hi = `vec3 transformed = vec3( position ); #ifdef USE_ALPHAHASH vPosition = vec3( position ); #endif`; var ui = `vec3 objectNormal = vec3( normal ); #ifdef USE_TANGENT vec3 objectTangent = vec3( tangent.xyz ); #endif`; var di = `float G_BlinnPhong_Implicit( ) { return 0.25; } float D_BlinnPhong( const in float shininess, const in float dotNH ) { return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess ); } vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) { vec3 halfDir = normalize( lightDir + viewDir ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( specularColor, 1.0, dotVH ); float G = G_BlinnPhong_Implicit( ); float D = D_BlinnPhong( shininess, dotNH ); return F * ( G * D ); } // validated`; var fi = `#ifdef USE_IRIDESCENCE const mat3 XYZ_TO_REC709 = mat3( 3.2404542, -0.9692660, 0.0556434, -1.5371385, 1.8760108, -0.2040259, -0.4985314, 0.0415560, 1.0572252 ); vec3 Fresnel0ToIor( vec3 fresnel0 ) { vec3 sqrtF0 = sqrt( fresnel0 ); return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 ); } vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) { return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) ); } float IorToFresnel0( float transmittedIor, float incidentIor ) { return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor )); } vec3 evalSensitivity( float OPD, vec3 shift ) { float phase = 2.0 * PI * OPD * 1.0e-9; vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 ); vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 ); vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 ); vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var ); xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) ); xyz /= 1.0685e-7; vec3 rgb = XYZ_TO_REC709 * xyz; return rgb; } vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) { vec3 I; float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) ); float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) ); float cosTheta2Sq = 1.0 - sinTheta2Sq; if ( cosTheta2Sq < 0.0 ) { return vec3( 1.0 ); } float cosTheta2 = sqrt( cosTheta2Sq ); float R0 = IorToFresnel0( iridescenceIOR, outsideIOR ); float R12 = F_Schlick( R0, 1.0, cosTheta1 ); float T121 = 1.0 - R12; float phi12 = 0.0; if ( iridescenceIOR < outsideIOR ) phi12 = PI; float phi21 = PI - phi12; vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR ); vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 ); vec3 phi23 = vec3( 0.0 ); if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI; if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI; if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI; float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2; vec3 phi = vec3( phi21 ) + phi23; vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 ); vec3 r123 = sqrt( R123 ); vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 ); vec3 C0 = R12 + Rs; I = C0; vec3 Cm = Rs - T121; for ( int m = 1; m <= 2; ++ m ) { Cm *= r123; vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi ); I += Cm * Sm; } return max( I, vec3( 0.0 ) ); } #endif`; var pi = `#ifdef USE_BUMPMAP uniform sampler2D bumpMap; uniform float bumpScale; vec2 dHdxy_fwd() { vec2 dSTdx = dFdx( vBumpMapUv ); vec2 dSTdy = dFdy( vBumpMapUv ); float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x; float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll; float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll; return vec2( dBx, dBy ); } vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) { vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) ); vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) ); vec3 vN = surf_norm; vec3 R1 = cross( vSigmaY, vN ); vec3 R2 = cross( vN, vSigmaX ); float fDet = dot( vSigmaX, R1 ) * faceDirection; vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 ); return normalize( abs( fDet ) * surf_norm - vGrad ); } #endif`; var mi = `#if NUM_CLIPPING_PLANES > 0 vec4 plane; #ifdef ALPHA_TO_COVERAGE float distanceToPlane, distanceGradient; float clipOpacity = 1.0; #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); if ( clipOpacity == 0.0 ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES float unionClipOpacity = 1.0; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); } #pragma unroll_loop_end clipOpacity *= 1.0 - unionClipOpacity; #endif diffuseColor.a *= clipOpacity; if ( diffuseColor.a == 0.0 ) discard; #else #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES bool clipped = true; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; } #pragma unroll_loop_end if ( clipped ) discard; #endif #endif #endif`; var gi = `#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; #endif`; var _i = `#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; #endif`; var xi = `#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; #endif`; var vi = `#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #endif`; var yi = `#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) varying vec4 vColor; #endif`; var Mi = `#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec4 vColor; #endif`; var Si = `#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) vColor = vec4( 1.0 ); #endif #ifdef USE_COLOR_ALPHA vColor *= color; #elif defined( USE_COLOR ) vColor.rgb *= color; #endif #ifdef USE_INSTANCING_COLOR vColor.rgb *= instanceColor.rgb; #endif #ifdef USE_BATCHING_COLOR vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) ); #endif`; var bi = `#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 #define RECIPROCAL_PI2 0.15915494309189535 #define EPSILON 1e-6 #ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif #define whiteComplement( a ) ( 1.0 - saturate( a ) ) float pow2( const in float x ) { return x*x; } vec3 pow2( const in vec3 x ) { return x*x; } float pow3( const in float x ) { return x*x*x; } float pow4( const in float x ) { float x2 = x*x; return x2*x2; } float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } highp float rand( const in vec2 uv ) { const highp float a = 12.9898, b = 78.233, c = 43758.5453; highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); return fract( sin( sn ) * c ); } #ifdef HIGH_PRECISION float precisionSafeLength( vec3 v ) { return length( v ); } #else float precisionSafeLength( vec3 v ) { float maxComponent = max3( abs( v ) ); return length( v / maxComponent ) * maxComponent; } #endif struct IncidentLight { vec3 color; vec3 direction; bool visible; }; struct ReflectedLight { vec3 directDiffuse; vec3 directSpecular; vec3 indirectDiffuse; vec3 indirectSpecular; }; #ifdef USE_ALPHAHASH varying vec3 vPosition; #endif vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); } bool isPerspectiveMatrix( mat4 m ) { return m[ 2 ][ 3 ] == - 1.0; } vec2 equirectUv( in vec3 dir ) { float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; return vec2( u, v ); } vec3 BRDF_Lambert( const in vec3 diffuseColor ) { return RECIPROCAL_PI * diffuseColor; } vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } // validated`; var Ti = `#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { vec3 absDirection = abs( direction ); float face = - 1.0; if ( absDirection.x > absDirection.z ) { if ( absDirection.x > absDirection.y ) face = direction.x > 0.0 ? 0.0 : 3.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } else { if ( absDirection.z > absDirection.y ) face = direction.z > 0.0 ? 2.0 : 5.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } return face; } vec2 getUV( vec3 direction, float face ) { vec2 uv; if ( face == 0.0 ) { uv = vec2( direction.z, direction.y ) / abs( direction.x ); } else if ( face == 1.0 ) { uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); } else if ( face == 2.0 ) { uv = vec2( - direction.x, direction.y ) / abs( direction.z ); } else if ( face == 3.0 ) { uv = vec2( - direction.z, direction.y ) / abs( direction.x ); } else if ( face == 4.0 ) { uv = vec2( - direction.x, direction.z ) / abs( direction.y ); } else { uv = vec2( direction.x, direction.y ) / abs( direction.z ); } return 0.5 * ( uv + 1.0 ); } vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { float face = getFace( direction ); float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); mipInt = max( mipInt, cubeUV_minMipLevel ); float faceSize = exp2( mipInt ); highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; if ( face > 2.0 ) { uv.y += faceSize; face -= 3.0; } uv.x += face * faceSize; uv.x += filterInt * 3.0 * cubeUV_minTileSize; uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); uv.x *= CUBEUV_TEXEL_WIDTH; uv.y *= CUBEUV_TEXEL_HEIGHT; #ifdef texture2DGradEXT return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; #else return texture2D( envMap, uv ).rgb; #endif } #define cubeUV_r0 1.0 #define cubeUV_m0 - 2.0 #define cubeUV_r1 0.8 #define cubeUV_m1 - 1.0 #define cubeUV_r4 0.4 #define cubeUV_m4 2.0 #define cubeUV_r5 0.305 #define cubeUV_m5 3.0 #define cubeUV_r6 0.21 #define cubeUV_m6 4.0 float roughnessToMip( float roughness ) { float mip = 0.0; if ( roughness >= cubeUV_r1 ) { mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; } else if ( roughness >= cubeUV_r4 ) { mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; } else if ( roughness >= cubeUV_r5 ) { mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; } else if ( roughness >= cubeUV_r6 ) { mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; } else { mip = - 2.0 * log2( 1.16 * roughness ); } return mip; } vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); float mipF = fract( mip ); float mipInt = floor( mip ); vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); if ( mipF == 0.0 ) { return vec4( color0, 1.0 ); } else { vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); return vec4( mix( color0, color1, mipF ), 1.0 ); } } #endif`; var Ei = `vec3 transformedNormal = objectNormal; #ifdef USE_TANGENT vec3 transformedTangent = objectTangent; #endif #ifdef USE_BATCHING mat3 bm = mat3( batchingMatrix ); transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); transformedNormal = bm * transformedNormal; #ifdef USE_TANGENT transformedTangent = bm * transformedTangent; #endif #endif #ifdef USE_INSTANCING mat3 im = mat3( instanceMatrix ); transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); transformedNormal = im * transformedNormal; #ifdef USE_TANGENT transformedTangent = im * transformedTangent; #endif #endif transformedNormal = normalMatrix * transformedNormal; #ifdef FLIP_SIDED transformedNormal = - transformedNormal; #endif #ifdef USE_TANGENT transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; #ifdef FLIP_SIDED transformedTangent = - transformedTangent; #endif #endif`; var Ai = `#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; #endif`; var wi = `#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); #endif`; var Ci = `#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; #endif`; var Ri = `#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; #endif`; var Ii = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; var Pi = `vec4 LinearTransferOETF( in vec4 value ) { return value; } vec4 sRGBTransferEOTF( in vec4 value ) { return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); } vec4 sRGBTransferOETF( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); }`; var Di = `#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToFrag = normalize( vWorldPosition - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vec3 reflectVec = reflect( cameraToFrag, worldNormal ); #else vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); #endif #else vec3 reflectVec = vReflect; #endif #ifdef ENVMAP_TYPE_CUBE vec4 envColor = textureCube( envMap, envMapRotation * reflectVec ); #ifdef ENVMAP_BLENDING_MULTIPLY outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_MIX ) outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif #endif #endif`; var Li = `#ifdef USE_ENVMAP uniform float envMapIntensity; uniform mat3 envMapRotation; #ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #else uniform sampler2D envMap; #endif #endif`; var Ni = `#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; uniform float refractionRatio; #else varying vec3 vReflect; #endif #endif`; var Ui = `#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; #else varying vec3 vReflect; uniform float refractionRatio; #endif #endif`; var Fi = `#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else vec3 cameraToVertex; if ( isOrthographic ) { cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vReflect = reflect( cameraToVertex, worldNormal ); #else vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif #endif`; var Oi = `#ifdef USE_FOG vFogDepth = - mvPosition.z; #endif`; var Bi = `#ifdef USE_FOG varying float vFogDepth; #endif`; var zi = `#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); #endif`; var Vi = `#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 uniform float fogDensity; #else uniform float fogNear; uniform float fogFar; #endif #endif`; var ki = `#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { float dotNL = dot( normal, lightDirection ); vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); #ifdef USE_GRADIENTMAP return vec3( texture2D( gradientMap, coord ).r ); #else vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif }`; var Gi = `#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; #endif`; var Hi = `LambertMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularStrength = specularStrength;`; var Wi = `varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; }; void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`; var Xi = `uniform bool receiveShadow; uniform vec3 ambientLightColor; #if defined( USE_LIGHT_PROBES ) uniform vec3 lightProbe[ 9 ]; #endif vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { float x = normal.x, y = normal.y, z = normal.z; vec3 result = shCoefficients[ 0 ] * 0.886227; result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); return result; } vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); return irradiance; } vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { vec3 irradiance = ambientLightColor; return irradiance; } float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); if ( cutoffDistance > 0.0 ) { distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); } return distanceFalloff; } float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { return smoothstep( coneCosine, penumbraCosine, angleCosine ); } #if NUM_DIR_LIGHTS > 0 struct DirectionalLight { vec3 direction; vec3 color; }; uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { light.color = directionalLight.color; light.direction = directionalLight.direction; light.visible = true; } #endif #if NUM_POINT_LIGHTS > 0 struct PointLight { vec3 position; vec3 color; float distance; float decay; }; uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = pointLight.position - geometryPosition; light.direction = normalize( lVector ); float lightDistance = length( lVector ); light.color = pointLight.color; light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } #endif #if NUM_SPOT_LIGHTS > 0 struct SpotLight { vec3 position; vec3 direction; vec3 color; float distance; float decay; float coneCos; float penumbraCos; }; uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = spotLight.position - geometryPosition; light.direction = normalize( lVector ); float angleCos = dot( light.direction, spotLight.direction ); float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); if ( spotAttenuation > 0.0 ) { float lightDistance = length( lVector ); light.color = spotLight.color * spotAttenuation; light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } else { light.color = vec3( 0.0 ); light.visible = false; } } #endif #if NUM_RECT_AREA_LIGHTS > 0 struct RectAreaLight { vec3 color; vec3 position; vec3 halfWidth; vec3 halfHeight; }; uniform sampler2D ltc_1; uniform sampler2D ltc_2; uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; #endif #if NUM_HEMI_LIGHTS > 0 struct HemisphereLight { vec3 direction; vec3 skyColor; vec3 groundColor; }; uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { float dotNL = dot( normal, hemiLight.direction ); float hemiDiffuseWeight = 0.5 * dotNL + 0.5; vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); return irradiance; } #endif #include `; var qi = `#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); return PI * envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 reflectVec = reflect( - viewDir, normal ); reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); return envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } #ifdef USE_ANISOTROPY vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 bentNormal = cross( bitangent, viewDir ); bentNormal = normalize( cross( bentNormal, bitangent ) ); bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); return getIBLRadiance( viewDir, bentNormal, roughness ); #else return vec3( 0.0 ); #endif } #endif #endif`; var Yi = `ToonMaterial material; material.diffuseColor = diffuseColor.rgb;`; var Zi = `varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`; var Ji = `BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; material.specularStrength = specularStrength;`; var $i = `varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; float specularShininess; float specularStrength; }; void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; } void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`; var Ki = `PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb; material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor ); material.metalness = metalnessFactor; vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; material.roughness = min( material.roughness, 1.0 ); #ifdef IOR material.ior = ior; #ifdef USE_SPECULAR float specularIntensityFactor = specularIntensity; vec3 specularColorFactor = specularColor; #ifdef USE_SPECULAR_COLORMAP specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; #endif #ifdef USE_SPECULAR_INTENSITYMAP specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; #endif material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); #else float specularIntensityFactor = 1.0; vec3 specularColorFactor = vec3( 1.0 ); material.specularF90 = 1.0; #endif material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor; material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); #else material.specularColor = vec3( 0.04 ); material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); material.specularF90 = 1.0; #endif #ifdef USE_CLEARCOAT material.clearcoat = clearcoat; material.clearcoatRoughness = clearcoatRoughness; material.clearcoatF0 = vec3( 0.04 ); material.clearcoatF90 = 1.0; #ifdef USE_CLEARCOATMAP material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; #endif material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); material.clearcoatRoughness += geometryRoughness; material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); #endif #ifdef USE_DISPERSION material.dispersion = dispersion; #endif #ifdef USE_IRIDESCENCE material.iridescence = iridescence; material.iridescenceIOR = iridescenceIOR; #ifdef USE_IRIDESCENCEMAP material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; #else material.iridescenceThickness = iridescenceThicknessMaximum; #endif #endif #ifdef USE_SHEEN material.sheenColor = sheenColor; #ifdef USE_SHEEN_COLORMAP material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; #endif material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 ); #ifdef USE_SHEEN_ROUGHNESSMAP material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; #endif #endif #ifdef USE_ANISOTROPY #ifdef USE_ANISOTROPYMAP mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; #else vec2 anisotropyV = anisotropyVector; #endif material.anisotropy = length( anisotropyV ); if( material.anisotropy == 0.0 ) { anisotropyV = vec2( 1.0, 0.0 ); } else { anisotropyV /= material.anisotropy; material.anisotropy = saturate( material.anisotropy ); } material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; #endif`; var Qi = `uniform sampler2D dfgLUT; struct PhysicalMaterial { vec3 diffuseColor; vec3 diffuseContribution; vec3 specularColor; vec3 specularColorBlended; float roughness; float metalness; float specularF90; float dispersion; #ifdef USE_CLEARCOAT float clearcoat; float clearcoatRoughness; vec3 clearcoatF0; float clearcoatF90; #endif #ifdef USE_IRIDESCENCE float iridescence; float iridescenceIOR; float iridescenceThickness; vec3 iridescenceFresnel; vec3 iridescenceF0; vec3 iridescenceFresnelDielectric; vec3 iridescenceFresnelMetallic; #endif #ifdef USE_SHEEN vec3 sheenColor; float sheenRoughness; #endif #ifdef IOR float ior; #endif #ifdef USE_TRANSMISSION float transmission; float transmissionAlpha; float thickness; float attenuationDistance; vec3 attenuationColor; #endif #ifdef USE_ANISOTROPY float anisotropy; float alphaT; vec3 anisotropyT; vec3 anisotropyB; #endif }; vec3 clearcoatSpecularDirect = vec3( 0.0 ); vec3 clearcoatSpecularIndirect = vec3( 0.0 ); vec3 sheenSpecularDirect = vec3( 0.0 ); vec3 sheenSpecularIndirect = vec3(0.0 ); vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); float x2 = x * x; float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); } float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { float a2 = pow2( alpha ); float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); return 0.5 / max( gv + gl, EPSILON ); } float D_GGX( const in float alpha, const in float dotNH ) { float a2 = pow2( alpha ); float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; return RECIPROCAL_PI * a2 / pow2( denom ); } #ifdef USE_ANISOTROPY float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); return 0.5 / max( gv + gl, EPSILON ); } float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { float a2 = alphaT * alphaB; highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); highp float v2 = dot( v, v ); float w2 = a2 / v2; return RECIPROCAL_PI * a2 * pow2 ( w2 ); } #endif #ifdef USE_CLEARCOAT vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { vec3 f0 = material.clearcoatF0; float f90 = material.clearcoatF90; float roughness = material.clearcoatRoughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); return F * ( V * D ); } #endif vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 f0 = material.specularColorBlended; float f90 = material.specularF90; float roughness = material.roughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); #ifdef USE_IRIDESCENCE F = mix( F, material.iridescenceFresnel, material.iridescence ); #endif #ifdef USE_ANISOTROPY float dotTL = dot( material.anisotropyT, lightDir ); float dotTV = dot( material.anisotropyT, viewDir ); float dotTH = dot( material.anisotropyT, halfDir ); float dotBL = dot( material.anisotropyB, lightDir ); float dotBV = dot( material.anisotropyB, viewDir ); float dotBH = dot( material.anisotropyB, halfDir ); float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); #else float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); #endif return F * ( V * D ); } vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { const float LUT_SIZE = 64.0; const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; const float LUT_BIAS = 0.5 / LUT_SIZE; float dotNV = saturate( dot( N, V ) ); vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); uv = uv * LUT_SCALE + LUT_BIAS; return uv; } float LTC_ClippedSphereFormFactor( const in vec3 f ) { float l = length( f ); return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); } vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { float x = dot( v1, v2 ); float y = abs( x ); float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; float b = 3.4175940 + ( 4.1616724 + y ) * y; float v = a / b; float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; return cross( v1, v2 ) * theta_sintheta; } vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; vec3 lightNormal = cross( v1, v2 ); if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); vec3 T1, T2; T1 = normalize( V - N * dot( V, N ) ); T2 = - cross( N, T1 ); mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); vec3 coords[ 4 ]; coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); coords[ 0 ] = normalize( coords[ 0 ] ); coords[ 1 ] = normalize( coords[ 1 ] ); coords[ 2 ] = normalize( coords[ 2 ] ); coords[ 3 ] = normalize( coords[ 3 ] ); vec3 vectorFormFactor = vec3( 0.0 ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); return vec3( result ); } #if defined( USE_SHEEN ) float D_Charlie( float roughness, float dotNH ) { float alpha = pow2( roughness ); float invAlpha = 1.0 / alpha; float cos2h = dotNH * dotNH; float sin2h = max( 1.0 - cos2h, 0.0078125 ); return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); } float V_Neubelt( float dotNV, float dotNL ) { return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); } vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float D = D_Charlie( sheenRoughness, dotNH ); float V = V_Neubelt( dotNV, dotNL ); return sheenColor * ( D * V ); } #endif float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); float r2 = roughness * roughness; float rInv = 1.0 / ( roughness + 0.1 ); float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv; float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv; float DG = exp( a * dotNV + b ); return saturate( DG ); } vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; return specularColor * fab.x + specularF90 * fab.y; } #ifdef USE_IRIDESCENCE void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #else void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #endif float dotNV = saturate( dot( normal, viewDir ) ); vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; #ifdef USE_IRIDESCENCE vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); #else vec3 Fr = specularColor; #endif vec3 FssEss = Fr * fab.x + specularF90 * fab.y; float Ess = fab.x + fab.y; float Ems = 1.0 - Ess; vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); singleScatter += FssEss; multiScatter += Fms * Ems; } vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg; vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg; vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y; vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y; float Ess_V = dfgV.x + dfgV.y; float Ess_L = dfgL.x + dfgL.y; float Ems_V = 1.0 - Ess_V; float Ems_L = 1.0 - Ess_L; vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619; vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON ); float compensationFactor = Ems_V * Ems_L; vec3 multiScatter = Fms * compensationFactor; return singleScatter + multiScatter; } #if NUM_RECT_AREA_LIGHTS > 0 void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { vec3 normal = geometryNormal; vec3 viewDir = geometryViewDir; vec3 position = geometryPosition; vec3 lightPos = rectAreaLight.position; vec3 halfWidth = rectAreaLight.halfWidth; vec3 halfHeight = rectAreaLight.halfHeight; vec3 lightColor = rectAreaLight.color; float roughness = material.roughness; vec3 rectCoords[ 4 ]; rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; vec2 uv = LTC_Uv( normal, viewDir, roughness ); vec4 t1 = texture2D( ltc_1, uv ); vec4 t2 = texture2D( ltc_2, uv ); mat3 mInv = mat3( vec3( t1.x, 0, t1.y ), vec3( 0, 1, 0 ), vec3( t1.z, 0, t1.w ) ); vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y ); reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); #ifdef USE_CLEARCOAT vec3 Ncc = geometryClearcoatNormal; vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness ); vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat ); vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat ); mat3 mInvClearcoat = mat3( vec3( t1Clearcoat.x, 0, t1Clearcoat.y ), vec3( 0, 1, 0 ), vec3( t1Clearcoat.z, 0, t1Clearcoat.w ) ); vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y; clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords ); #endif } #endif void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; #ifdef USE_CLEARCOAT float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); vec3 ccIrradiance = dotNLcc * directLight.color; clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); #endif #ifdef USE_SHEEN sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL ); irradiance *= sheenEnergyComp; #endif reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ); } void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ); #ifdef USE_SHEEN float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; diffuse *= sheenEnergyComp; #endif reflectedLight.indirectDiffuse += diffuse; } void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { #ifdef USE_CLEARCOAT clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); #endif #ifdef USE_SHEEN sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI; #endif vec3 singleScatteringDielectric = vec3( 0.0 ); vec3 multiScatteringDielectric = vec3( 0.0 ); vec3 singleScatteringMetallic = vec3( 0.0 ); vec3 multiScatteringMetallic = vec3( 0.0 ); #ifdef USE_IRIDESCENCE computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); #else computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); #endif vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness ); vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness ); vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric; vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric ); vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; vec3 indirectSpecular = radiance * singleScattering; indirectSpecular += multiScattering * cosineWeightedIrradiance; vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance; #ifdef USE_SHEEN float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; indirectSpecular *= sheenEnergyComp; indirectDiffuse *= sheenEnergyComp; #endif reflectedLight.indirectSpecular += indirectSpecular; reflectedLight.indirectDiffuse += indirectDiffuse; } #define RE_Direct RE_Direct_Physical #define RE_Direct_RectArea RE_Direct_RectArea_Physical #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); }`; var ji = ` vec3 geometryPosition = - vViewPosition; vec3 geometryNormal = normal; vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); vec3 geometryClearcoatNormal = vec3( 0.0 ); #ifdef USE_CLEARCOAT geometryClearcoatNormal = clearcoatNormal; #endif #ifdef USE_IRIDESCENCE float dotNVi = saturate( dot( normal, geometryViewDir ) ); if ( material.iridescenceThickness == 0.0 ) { material.iridescence = 0.0; } else { material.iridescence = saturate( material.iridescence ); } if ( material.iridescence > 0.0 ) { material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor ); material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness ); material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); } #endif IncidentLight directLight; #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) PointLight pointLight; #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { pointLight = pointLights[ i ]; getPointLightInfo( pointLight, geometryPosition, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) pointLightShadow = pointLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) SpotLight spotLight; vec4 spotColor; vec3 spotLightCoord; bool inSpotLightMap; #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { spotLight = spotLights[ i ]; getSpotLightInfo( spotLight, geometryPosition, directLight ); #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS #else #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #endif #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; #endif #undef SPOT_LIGHT_MAP_INDEX #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) spotLightShadow = spotLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) DirectionalLight directionalLight; #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) directionalLightShadow = directionalLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) RectAreaLight rectAreaLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { rectAreaLight = rectAreaLights[ i ]; RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if defined( RE_IndirectDiffuse ) vec3 iblIrradiance = vec3( 0.0 ); vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); #if defined( USE_LIGHT_PROBES ) irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); #endif #if ( NUM_HEMI_LIGHTS > 0 ) #pragma unroll_loop_start for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); } #pragma unroll_loop_end #endif #ifdef USE_LIGHT_PROBES_GRID vec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz; vec3 probeWorldNormal = inverseTransformDirection( geometryNormal, viewMatrix ); irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal ); #endif #endif #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); #endif`; var es = `#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; irradiance += lightMapIrradiance; #endif #if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV ) #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG ) iblIrradiance += getIBLIrradiance( geometryNormal ); #endif #endif #endif #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) #ifdef USE_ANISOTROPY radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); #else radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); #endif #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); #endif #endif`; var ts = `#if defined( RE_IndirectDiffuse ) #if defined( LAMBERT ) || defined( PHONG ) irradiance += iblIrradiance; #endif RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif`; var ns = `#ifdef USE_LIGHT_PROBES_GRID uniform highp sampler3D probesSH; uniform vec3 probesMin; uniform vec3 probesMax; uniform vec3 probesResolution; vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) { vec3 res = probesResolution; vec3 gridRange = probesMax - probesMin; vec3 resMinusOne = res - 1.0; vec3 probeSpacing = gridRange / resMinusOne; vec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5; vec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 ); uvw = uvw * resMinusOne / res + 0.5 / res; float nz = res.z; float paddedSlices = nz + 2.0; float atlasDepth = 7.0 * paddedSlices; float uvZBase = uvw.z * nz + 1.0; vec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) ); vec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) ); vec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) ); vec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) ); vec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) ); vec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) ); vec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) ); vec3 c0 = s0.xyz; vec3 c1 = vec3( s0.w, s1.xy ); vec3 c2 = vec3( s1.zw, s2.x ); vec3 c3 = s2.yzw; vec3 c4 = s3.xyz; vec3 c5 = vec3( s3.w, s4.xy ); vec3 c6 = vec3( s4.zw, s5.x ); vec3 c7 = s5.yzw; vec3 c8 = s6.xyz; float x = worldNormal.x, y = worldNormal.y, z = worldNormal.z; vec3 result = c0 * 0.886227; result += c1 * 2.0 * 0.511664 * y; result += c2 * 2.0 * 0.511664 * z; result += c3 * 2.0 * 0.511664 * x; result += c4 * 2.0 * 0.429043 * x * y; result += c5 * 2.0 * 0.429043 * y * z; result += c6 * ( 0.743125 * z * z - 0.247708 ); result += c7 * 2.0 * 0.429043 * x * z; result += c8 * 0.429043 * ( x * x - y * y ); return max( result, vec3( 0.0 ) ); } #endif`; var is = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; #endif`; var ss = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; #endif`; var rs = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER varying float vFragDepth; varying float vIsPerspective; #endif`; var as = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); #endif`; var os = `#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; #endif`; var ls = `#ifdef USE_MAP uniform sampler2D map; #endif`; var cs = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; #endif #endif #ifdef USE_MAP diffuseColor *= texture2D( map, uv ); #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; #endif`; var hs = `#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) uniform mat3 uvTransform; #endif #endif #ifdef USE_MAP uniform sampler2D map; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; #endif`; var us = `float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; #endif`; var ds = `#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; #endif`; var fs = `#ifdef USE_INSTANCING_MORPH float morphTargetInfluences[ MORPHTARGETS_COUNT ]; float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; } #endif`; var ps = `#if defined( USE_MORPHCOLORS ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; #elif defined( USE_COLOR ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } #endif`; var ms = `#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } #endif`; var gs = `#ifdef USE_MORPHTARGETS #ifndef USE_INSTANCING_MORPH uniform float morphTargetBaseInfluence; uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; #endif uniform sampler2DArray morphTargetsTexture; uniform ivec2 morphTargetsTextureSize; vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; int y = texelIndex / morphTargetsTextureSize.x; int x = texelIndex - y * morphTargetsTextureSize.x; ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } #endif`; var _s = `#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } #endif`; var xs = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); vec3 normal = normalize( cross( fdx, fdy ) ); #else vec3 normal = normalize( vNormal ); #ifdef DOUBLE_SIDED normal *= faceDirection; #endif #endif #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) #ifdef USE_TANGENT mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn = getTangentFrame( - vViewPosition, normal, #if defined( USE_NORMALMAP ) vNormalMapUv #elif defined( USE_CLEARCOAT_NORMALMAP ) vClearcoatNormalMapUv #else vUv #endif ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn[0] *= faceDirection; tbn[1] *= faceDirection; #endif #endif #ifdef USE_CLEARCOAT_NORMALMAP #ifdef USE_TANGENT mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn2[0] *= faceDirection; tbn2[1] *= faceDirection; #endif #endif vec3 nonPerturbedNormal = normal;`; var vs = `#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; #endif #ifdef DOUBLE_SIDED normal = normal * faceDirection; #endif normal = normalize( normalMatrix * normal ); #elif defined( USE_NORMALMAP_TANGENTSPACE ) vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #if defined( USE_PACKED_NORMALMAP ) mapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) ); #endif mapN.xy *= normalScale; normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); #endif`; var ys = `#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`; var Ms = `#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`; var Ss = `#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif #endif`; var bs = `#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif #ifdef USE_NORMALMAP_OBJECTSPACE uniform mat3 normalMatrix; #endif #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { vec3 q0 = dFdx( eye_pos.xyz ); vec3 q1 = dFdy( eye_pos.xyz ); vec2 st0 = dFdx( uv.st ); vec2 st1 = dFdy( uv.st ); vec3 N = surf_norm; vec3 q1perp = cross( q1, N ); vec3 q0perp = cross( N, q0 ); vec3 T = q1perp * st0.x + q0perp * st1.x; vec3 B = q1perp * st0.y + q0perp * st1.y; float det = max( dot( T, T ), dot( B, B ) ); float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } #endif`; var Ts = `#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; #endif`; var Es = `#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); #endif`; var As = `#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform sampler2D clearcoatNormalMap; uniform vec2 clearcoatNormalScale; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; #endif`; var ws = `#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; #endif`; var Cs = `#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif gl_FragColor = vec4( outgoingLight, diffuseColor.a );`; var Rs = `vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { return 2.0 * rgb.xyz - 1.0; } const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; const float Inv255 = 1. / 255.; const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); vec4 packDepthToRGBA( const in float v ) { if( v <= 0.0 ) return vec4( 0., 0., 0., 0. ); if( v >= 1.0 ) return vec4( 1., 1., 1., 1. ); float vuf; float af = modf( v * PackFactors.a, vuf ); float bf = modf( vuf * ShiftRight8, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); } vec3 packDepthToRGB( const in float v ) { if( v <= 0.0 ) return vec3( 0., 0., 0. ); if( v >= 1.0 ) return vec3( 1., 1., 1. ); float vuf; float bf = modf( v * PackFactors.b, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec3( vuf * Inv255, gf * PackUpscale, bf ); } vec2 packDepthToRG( const in float v ) { if( v <= 0.0 ) return vec2( 0., 0. ); if( v >= 1.0 ) return vec2( 1., 1. ); float vuf; float gf = modf( v * 256., vuf ); return vec2( vuf * Inv255, gf ); } float unpackRGBAToDepth( const in vec4 v ) { return dot( v, UnpackFactors4 ); } float unpackRGBToDepth( const in vec3 v ) { return dot( v, UnpackFactors3 ); } float unpackRGToDepth( const in vec2 v ) { return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; } vec4 pack2HalfToRGBA( const in vec2 v ) { vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); } vec2 unpackRGBATo2Half( const in vec4 v ) { return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); } float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { return ( viewZ + near ) / ( near - far ); } float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { #ifdef USE_REVERSED_DEPTH_BUFFER return depth * ( far - near ) - far; #else return depth * ( near - far ) - near; #endif } float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); } float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { #ifdef USE_REVERSED_DEPTH_BUFFER return ( near * far ) / ( ( near - far ) * depth - near ); #else return ( near * far ) / ( ( far - near ) * depth - far ); #endif }`; var Is = `#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; #endif`; var Ps = `vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING mvPosition = batchingMatrix * mvPosition; #endif #ifdef USE_INSTANCING mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; gl_Position = projectionMatrix * mvPosition;`; var Ds = `#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); #endif`; var Ls = `#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } #endif`; var Ns = `float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; #endif`; var Us = `#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; #endif`; var Fs = `#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; #else uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; #endif varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; #else uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; #endif struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; #elif defined( SHADOWMAP_TYPE_BASIC ) uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; #endif varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #if defined( SHADOWMAP_TYPE_PCF ) float interleavedGradientNoise( vec2 position ) { return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ); } vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) { const float goldenAngle = 2.399963229728653; float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) ); float theta = float( sampleIndex ) * goldenAngle + phi; return vec2( cos( theta ), sin( theta ) ) * r; } #endif #if defined( SHADOWMAP_TYPE_PCF ) float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; shadowCoord.z += shadowBias; bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float radius = shadowRadius * texelSize.x; float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; shadow = ( texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) ) ) * 0.2; } return mix( 1.0, shadow, shadowIntensity ); } #elif defined( SHADOWMAP_TYPE_VSM ) float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; #ifdef USE_REVERSED_DEPTH_BUFFER shadowCoord.z -= shadowBias; #else shadowCoord.z += shadowBias; #endif bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg; float mean = distribution.x; float variance = distribution.y * distribution.y; #ifdef USE_REVERSED_DEPTH_BUFFER float hard_shadow = step( mean, shadowCoord.z ); #else float hard_shadow = step( shadowCoord.z, mean ); #endif if ( hard_shadow == 1.0 ) { shadow = 1.0; } else { variance = max( variance, 0.0000001 ); float d = shadowCoord.z - mean; float p_max = variance / ( variance + d * d ); p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 ); shadow = max( hard_shadow, p_max ); } } return mix( 1.0, shadow, shadowIntensity ); } #else float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; #ifdef USE_REVERSED_DEPTH_BUFFER shadowCoord.z -= shadowBias; #else shadowCoord.z += shadowBias; #endif bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { float depth = texture2D( shadowMap, shadowCoord.xy ).r; #ifdef USE_REVERSED_DEPTH_BUFFER shadow = step( depth, shadowCoord.z ); #else shadow = step( shadowCoord.z, depth ); #endif } return mix( 1.0, shadow, shadowIntensity ); } #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec3 lightToPosition = shadowCoord.xyz; vec3 bd3D = normalize( lightToPosition ); vec3 absVec = abs( lightToPosition ); float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { #ifdef USE_REVERSED_DEPTH_BUFFER float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp -= shadowBias; #else float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp += shadowBias; #endif float texelSize = shadowRadius / shadowMapSize.x; vec3 absDir = abs( bd3D ); vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 ); tangent = normalize( cross( bd3D, tangent ) ); vec3 bitangent = cross( bd3D, tangent ); float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; vec2 sample0 = vogelDiskSample( 0, 5, phi ); vec2 sample1 = vogelDiskSample( 1, 5, phi ); vec2 sample2 = vogelDiskSample( 2, 5, phi ); vec2 sample3 = vogelDiskSample( 3, 5, phi ); vec2 sample4 = vogelDiskSample( 4, 5, phi ); shadow = ( texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) ) ) * 0.2; } return mix( 1.0, shadow, shadowIntensity ); } #elif defined( SHADOWMAP_TYPE_BASIC ) float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec3 lightToPosition = shadowCoord.xyz; vec3 absVec = abs( lightToPosition ); float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp += shadowBias; vec3 bd3D = normalize( lightToPosition ); float depth = textureCube( shadowMap, bd3D ).r; #ifdef USE_REVERSED_DEPTH_BUFFER depth = 1.0 - depth; #endif shadow = step( dp, depth ); } return mix( 1.0, shadow, shadowIntensity ); } #endif #endif #endif`; var Os = `#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #endif`; var Bs = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) #ifdef HAS_NORMAL vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); #else vec3 shadowWorldNormal = vec3( 0.0 ); #endif vec4 shadowWorldPosition; #endif #if defined( USE_SHADOWMAP ) #if NUM_DIR_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #endif #if NUM_SPOT_LIGHT_COORDS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { shadowWorldPosition = worldPosition; #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; #endif vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif`; var zs = `float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { directionalLight = directionalLightShadows[ i ]; shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { spotLight = spotLightShadows[ i ]; shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) PointLightShadow pointLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { pointLight = pointLightShadows[ i ]; shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; } #pragma unroll_loop_end #endif #endif return shadow; }`; var Vs = `#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); #endif`; var ks = `#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; mat4 getBoneMatrix( const in float i ) { int size = textureSize( boneTexture, 0 ).x; int j = int( i ) * 4; int x = j % size; int y = j / size; vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } #endif`; var Gs = `#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; skinned += boneMatY * skinVertex * skinWeight.y; skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; #endif`; var Hs = `#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; skinMatrix += skinWeight.z * boneMatZ; skinMatrix += skinWeight.w * boneMatW; skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif #endif`; var Ws = `float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; #endif`; var Xs = `#ifdef USE_SPECULARMAP uniform sampler2D specularMap; #endif`; var qs = `#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); #endif`; var Ys = `#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; vec3 LinearToneMapping( vec3 color ) { return saturate( toneMappingExposure * color ); } vec3 ReinhardToneMapping( vec3 color ) { color *= toneMappingExposure; return saturate( color / ( vec3( 1.0 ) + color ) ); } vec3 CineonToneMapping( vec3 color ) { color *= toneMappingExposure; color = max( vec3( 0.0 ), color - 0.004 ); return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); } vec3 RRTAndODTFit( vec3 v ) { vec3 a = v * ( v + 0.0245786 ) - 0.000090537; vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; return a / b; } vec3 ACESFilmicToneMapping( vec3 color ) { const mat3 ACESInputMat = mat3( vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), vec3( 0.04823, 0.01566, 0.83777 ) ); const mat3 ACESOutputMat = mat3( vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), vec3( -0.07367, -0.00605, 1.07602 ) ); color *= toneMappingExposure / 0.6; color = ACESInputMat * color; color = RRTAndODTFit( color ); color = ACESOutputMat * color; return saturate( color ); } const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); vec3 agxDefaultContrastApprox( vec3 x ) { vec3 x2 = x * x; vec3 x4 = x2 * x2; return + 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232; } vec3 AgXToneMapping( vec3 color ) { const mat3 AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); const mat3 AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; color *= toneMappingExposure; color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; color = AgXInsetMatrix * color; color = max( color, 1e-10 ); color = log2( color ); color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); color = clamp( color, 0.0, 1.0 ); color = agxDefaultContrastApprox( color ); color = AgXOutsetMatrix * color; color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); color = LINEAR_REC2020_TO_LINEAR_SRGB * color; color = clamp( color, 0.0, 1.0 ); return color; } vec3 NeutralToneMapping( vec3 color ) { const float StartCompression = 0.8 - 0.04; const float Desaturation = 0.15; color *= toneMappingExposure; float x = min( color.r, min( color.g, color.b ) ); float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; color -= offset; float peak = max( color.r, max( color.g, color.b ) ); if ( peak < StartCompression ) return color; float d = 1. - StartCompression; float newPeak = 1. - d * d / ( peak + d - StartCompression ); color *= newPeak / peak; float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); return mix( color, vec3( newPeak ), g ); } vec3 CustomToneMapping( vec3 color ) { return color; }`; var Zs = `#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; material.attenuationDistance = attenuationDistance; material.attenuationColor = attenuationColor; #ifdef USE_TRANSMISSIONMAP material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; #endif #ifdef USE_THICKNESSMAP material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; #endif vec3 pos = vWorldPosition; vec3 v = normalize( cameraPosition - pos ); vec3 n = inverseTransformDirection( normal, viewMatrix ); vec4 transmitted = getIBLVolumeRefraction( n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90, pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); #endif`; var Js = `#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; uniform vec3 attenuationColor; #ifdef USE_TRANSMISSIONMAP uniform sampler2D transmissionMap; #endif #ifdef USE_THICKNESSMAP uniform sampler2D thicknessMap; #endif uniform vec2 transmissionSamplerSize; uniform sampler2D transmissionSamplerMap; uniform mat4 modelMatrix; uniform mat4 projectionMatrix; varying vec3 vWorldPosition; float w0( float a ) { return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); } float w1( float a ) { return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); } float w2( float a ){ return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); } float w3( float a ) { return ( 1.0 / 6.0 ) * ( a * a * a ); } float g0( float a ) { return w0( a ) + w1( a ); } float g1( float a ) { return w2( a ) + w3( a ); } float h0( float a ) { return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); } float h1( float a ) { return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); } vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { uv = uv * texelSize.zw + 0.5; vec2 iuv = floor( uv ); vec2 fuv = fract( uv ); float g0x = g0( fuv.x ); float g1x = g1( fuv.x ); float h0x = h0( fuv.x ); float h1x = h1( fuv.x ); float h0y = h0( fuv.y ); float h1y = h1( fuv.y ); vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); } vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); vec2 fLodSizeInv = 1.0 / fLodSize; vec2 cLodSizeInv = 1.0 / cLodSize; vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); return mix( fSample, cSample, fract( lod ) ); } vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); vec3 modelScale; modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); return normalize( refractionVector ) * thickness * modelScale; } float applyIorToRoughness( const in float roughness, const in float ior ) { return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); } vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); } vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { if ( isinf( attenuationDistance ) ) { return vec3( 1.0 ); } else { vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; } } vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, const in vec3 attenuationColor, const in float attenuationDistance ) { vec4 transmittedLight; vec3 transmittance; #ifdef USE_DISPERSION float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); for ( int i = 0; i < 3; i ++ ) { vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); transmittedLight[ i ] = transmissionSample[ i ]; transmittedLight.a += transmissionSample.a; transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; } transmittedLight.a /= 3.0; #else vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); #endif vec3 attenuatedColor = transmittance * transmittedLight.rgb; vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } #endif`; var $s = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP varying vec2 vNormalMapUv; #endif #ifdef USE_EMISSIVEMAP varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SHEEN_COLORMAP varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_SPECULARMAP varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`; var Ks = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP uniform mat3 mapTransform; varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP uniform mat3 alphaMapTransform; varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP uniform mat3 lightMapTransform; varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP uniform mat3 aoMapTransform; varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP uniform mat3 bumpMapTransform; varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP uniform mat3 normalMapTransform; varying vec2 vNormalMapUv; #endif #ifdef USE_DISPLACEMENTMAP uniform mat3 displacementMapTransform; varying vec2 vDisplacementMapUv; #endif #ifdef USE_EMISSIVEMAP uniform mat3 emissiveMapTransform; varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP uniform mat3 metalnessMapTransform; varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP uniform mat3 roughnessMapTransform; varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP uniform mat3 anisotropyMapTransform; varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP uniform mat3 clearcoatMapTransform; varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform mat3 clearcoatNormalMapTransform; varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform mat3 clearcoatRoughnessMapTransform; varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_SHEEN_COLORMAP uniform mat3 sheenColorMapTransform; varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform mat3 sheenRoughnessMapTransform; varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP uniform mat3 iridescenceMapTransform; varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform mat3 iridescenceThicknessMapTransform; varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SPECULARMAP uniform mat3 specularMapTransform; varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP uniform mat3 specularColorMapTransform; varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform mat3 specularIntensityMapTransform; varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`; var Qs = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; #endif #ifdef USE_ALPHAMAP vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; #endif #ifdef USE_LIGHTMAP vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; #endif #ifdef USE_AOMAP vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; #endif #ifdef USE_BUMPMAP vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; #endif #ifdef USE_NORMALMAP vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_DISPLACEMENTMAP vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; #endif #ifdef USE_EMISSIVEMAP vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; #endif #ifdef USE_METALNESSMAP vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ROUGHNESSMAP vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ANISOTROPYMAP vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOATMAP vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_NORMALMAP vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCEMAP vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_COLORMAP vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_ROUGHNESSMAP vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULARMAP vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_COLORMAP vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_INTENSITYMAP vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; #endif #ifdef USE_TRANSMISSIONMAP vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; #endif`; var js = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING worldPosition = batchingMatrix * worldPosition; #endif #ifdef USE_INSTANCING worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; #endif`; var er = `varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); }`; var tr = `uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { vec4 texColor = texture2D( t2D, vUv ); #ifdef DECODE_VIDEO_TEXTURE texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`; var nr = `varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`; var ir = `#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; #endif uniform float backgroundBlurriness; uniform float backgroundIntensity; uniform mat3 backgroundRotation; varying vec3 vWorldDirection; #include void main() { #ifdef ENVMAP_TYPE_CUBE vec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection ); #elif defined( ENVMAP_TYPE_CUBE_UV ) vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); #else vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`; var sr = `varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`; var rr = `uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; void main() { vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); gl_FragColor = texColor; gl_FragColor.a *= opacity; #include #include }`; var ar = `#include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vHighPrecisionZW = gl_Position.zw; }`; var or = `#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include #include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { vec4 diffuseColor = vec4( 1.0 ); #include #if DEPTH_PACKING == 3200 diffuseColor.a = opacity; #endif #include #include #include #include #include #ifdef USE_REVERSED_DEPTH_BUFFER float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; #else float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; #endif #if DEPTH_PACKING == 3200 gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); #elif DEPTH_PACKING == 3201 gl_FragColor = packDepthToRGBA( fragCoordZ ); #elif DEPTH_PACKING == 3202 gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); #elif DEPTH_PACKING == 3203 gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); #endif }`; var lr = `#define DISTANCE varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vWorldPosition = worldPosition.xyz; }`; var cr = `#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main () { vec4 diffuseColor = vec4( 1.0 ); #include #include #include #include #include float dist = length( vWorldPosition - referencePosition ); dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 ); }`; var hr = `varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include }`; var ur = `uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include }`; var dr = `uniform float scale; attribute float lineDistance; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vLineDistance = scale * lineDistance; #include #include #include #include #include #include #include #include #include #include }`; var fr = `uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include if ( mod( vLineDistance, totalSize ) > dashSize ) { discard; } vec3 outgoingLight = vec3( 0.0 ); #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`; var pr = `#include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) #include #include #include #include #include #endif #include #include #include #include #include #include #include #include #include }`; var mr = `uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; #else reflectedLight.indirectDiffuse += vec3( 1.0 ); #endif #include reflectedLight.indirectDiffuse *= diffuseColor.rgb; vec3 outgoingLight = reflectedLight.indirectDiffuse; #include #include #include #include #include #include #include }`; var gr = `#define LAMBERT varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`; var _r = `#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include #include }`; var xr = `#define MATCAP varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; }`; var vr = `#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include #include vec3 viewDir = normalize( vViewPosition ); vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); vec3 y = cross( viewDir, x ); vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; #ifdef USE_MATCAP vec4 matcapColor = texture2D( matcap, uv ); #else vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); #endif vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; #include #include #include #include #include #include }`; var yr = `#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif }`; var Mr = `#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); #include #include #include #include gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a ); #ifdef OPAQUE gl_FragColor.a = 1.0; #endif }`; var Sr = `#define PHONG varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`; var br = `#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; uniform float shininess; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; #include #include #include #include #include #include #include }`; var Tr = `#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; #endif #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif }`; var Er = `#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR #endif uniform vec3 diffuse; uniform vec3 emissive; uniform float roughness; uniform float metalness; uniform float opacity; #ifdef IOR uniform float ior; #endif #ifdef USE_SPECULAR uniform float specularIntensity; uniform vec3 specularColor; #ifdef USE_SPECULAR_COLORMAP uniform sampler2D specularColorMap; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform sampler2D specularIntensityMap; #endif #endif #ifdef USE_CLEARCOAT uniform float clearcoat; uniform float clearcoatRoughness; #endif #ifdef USE_DISPERSION uniform float dispersion; #endif #ifdef USE_IRIDESCENCE uniform float iridescence; uniform float iridescenceIOR; uniform float iridescenceThicknessMinimum; uniform float iridescenceThicknessMaximum; #endif #ifdef USE_SHEEN uniform vec3 sheenColor; uniform float sheenRoughness; #ifdef USE_SHEEN_COLORMAP uniform sampler2D sheenColorMap; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform sampler2D sheenRoughnessMap; #endif #endif #ifdef USE_ANISOTROPY uniform vec2 anisotropyVector; #ifdef USE_ANISOTROPYMAP uniform sampler2D anisotropyMap; #endif #endif varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; #include vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; #ifdef USE_SHEEN outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect; #endif #ifdef USE_CLEARCOAT float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; #endif #include #include #include #include #include #include }`; var Ar = `#define TOON varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include }`; var wr = `#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include }`; var Cr = `uniform float size; uniform float scale; #include #include #include #include #include #include #ifdef USE_POINTS_UV varying vec2 vUv; uniform mat3 uvTransform; #endif void main() { #ifdef USE_POINTS_UV vUv = ( uvTransform * vec3( uv, 1 ) ).xy; #endif #include #include #include #include #include #include gl_PointSize = size; #ifdef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); #endif #include #include #include #include }`; var Rr = `uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`; var Ir = `#include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include }`; var Pr = `uniform vec3 color; uniform float opacity; #include #include #include #include #include #include #include void main() { #include gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); #include #include #include #include }`; var Dr = `uniform float rotation; uniform vec2 center; #include #include #include #include #include void main() { #include vec4 mvPosition = modelViewMatrix[ 3 ]; vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); #ifndef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) scale *= - mvPosition.z; #endif vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; vec2 rotatedPosition; rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; #include #include #include }`; var Lr = `uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include }`; var T = { alphahash_fragment: ei, alphahash_pars_fragment: ti, alphamap_fragment: ni, alphamap_pars_fragment: ii, alphatest_fragment: si, alphatest_pars_fragment: ri, aomap_fragment: ai, aomap_pars_fragment: oi, batching_pars_vertex: li, batching_vertex: ci, begin_vertex: hi, beginnormal_vertex: ui, bsdfs: di, iridescence_fragment: fi, bumpmap_pars_fragment: pi, clipping_planes_fragment: mi, clipping_planes_pars_fragment: gi, clipping_planes_pars_vertex: _i, clipping_planes_vertex: xi, color_fragment: vi, color_pars_fragment: yi, color_pars_vertex: Mi, color_vertex: Si, common: bi, cube_uv_reflection_fragment: Ti, defaultnormal_vertex: Ei, displacementmap_pars_vertex: Ai, displacementmap_vertex: wi, emissivemap_fragment: Ci, emissivemap_pars_fragment: Ri, colorspace_fragment: Ii, colorspace_pars_fragment: Pi, envmap_fragment: Di, envmap_common_pars_fragment: Li, envmap_pars_fragment: Ni, envmap_pars_vertex: Ui, envmap_physical_pars_fragment: qi, envmap_vertex: Fi, fog_vertex: Oi, fog_pars_vertex: Bi, fog_fragment: zi, fog_pars_fragment: Vi, gradientmap_pars_fragment: ki, lightmap_pars_fragment: Gi, lights_lambert_fragment: Hi, lights_lambert_pars_fragment: Wi, lights_pars_begin: Xi, lights_toon_fragment: Yi, lights_toon_pars_fragment: Zi, lights_phong_fragment: Ji, lights_phong_pars_fragment: $i, lights_physical_fragment: Ki, lights_physical_pars_fragment: Qi, lights_fragment_begin: ji, lights_fragment_maps: es, lights_fragment_end: ts, lightprobes_pars_fragment: ns, logdepthbuf_fragment: is, logdepthbuf_pars_fragment: ss, logdepthbuf_pars_vertex: rs, logdepthbuf_vertex: as, map_fragment: os, map_pars_fragment: ls, map_particle_fragment: cs, map_particle_pars_fragment: hs, metalnessmap_fragment: us, metalnessmap_pars_fragment: ds, morphinstance_vertex: fs, morphcolor_vertex: ps, morphnormal_vertex: ms, morphtarget_pars_vertex: gs, morphtarget_vertex: _s, normal_fragment_begin: xs, normal_fragment_maps: vs, normal_pars_fragment: ys, normal_pars_vertex: Ms, normal_vertex: Ss, normalmap_pars_fragment: bs, clearcoat_normal_fragment_begin: Ts, clearcoat_normal_fragment_maps: Es, clearcoat_pars_fragment: As, iridescence_pars_fragment: ws, opaque_fragment: Cs, packing: Rs, premultiplied_alpha_fragment: Is, project_vertex: Ps, dithering_fragment: Ds, dithering_pars_fragment: Ls, roughnessmap_fragment: Ns, roughnessmap_pars_fragment: Us, shadowmap_pars_fragment: Fs, shadowmap_pars_vertex: Os, shadowmap_vertex: Bs, shadowmask_pars_fragment: zs, skinbase_vertex: Vs, skinning_pars_vertex: ks, skinning_vertex: Gs, skinnormal_vertex: Hs, specularmap_fragment: Ws, specularmap_pars_fragment: Xs, tonemapping_fragment: qs, tonemapping_pars_fragment: Ys, transmission_fragment: Zs, transmission_pars_fragment: Js, uv_pars_fragment: $s, uv_pars_vertex: Ks, uv_vertex: Qs, worldpos_vertex: js, background_vert: er, background_frag: tr, backgroundCube_vert: nr, backgroundCube_frag: ir, cube_vert: sr, cube_frag: rr, depth_vert: ar, depth_frag: or, distance_vert: lr, distance_frag: cr, equirect_vert: hr, equirect_frag: ur, linedashed_vert: dr, linedashed_frag: fr, meshbasic_vert: pr, meshbasic_frag: mr, meshlambert_vert: gr, meshlambert_frag: _r, meshmatcap_vert: xr, meshmatcap_frag: vr, meshnormal_vert: yr, meshnormal_frag: Mr, meshphong_vert: Sr, meshphong_frag: br, meshphysical_vert: Tr, meshphysical_frag: Er, meshtoon_vert: Ar, meshtoon_frag: wr, points_vert: Cr, points_frag: Rr, shadow_vert: Ir, shadow_frag: Pr, sprite_vert: Dr, sprite_frag: Lr }; var x = { common: { diffuse: { value: new N(16777215) }, opacity: { value: 1 }, map: { value: null }, mapTransform: { value: new b() }, alphaMap: { value: null }, alphaMapTransform: { value: new b() }, alphaTest: { value: 0 } }, specularmap: { specularMap: { value: null }, specularMapTransform: { value: new b() } }, envmap: { envMap: { value: null }, envMapRotation: { value: new b() }, reflectivity: { value: 1 }, ior: { value: 1.5 }, refractionRatio: { value: 0.98 }, dfgLUT: { value: null } }, aomap: { aoMap: { value: null }, aoMapIntensity: { value: 1 }, aoMapTransform: { value: new b() } }, lightmap: { lightMap: { value: null }, lightMapIntensity: { value: 1 }, lightMapTransform: { value: new b() } }, bumpmap: { bumpMap: { value: null }, bumpMapTransform: { value: new b() }, bumpScale: { value: 1 } }, normalmap: { normalMap: { value: null }, normalMapTransform: { value: new b() }, normalScale: { value: new Z(1, 1) } }, displacementmap: { displacementMap: { value: null }, displacementMapTransform: { value: new b() }, displacementScale: { value: 1 }, displacementBias: { value: 0 } }, emissivemap: { emissiveMap: { value: null }, emissiveMapTransform: { value: new b() } }, metalnessmap: { metalnessMap: { value: null }, metalnessMapTransform: { value: new b() } }, roughnessmap: { roughnessMap: { value: null }, roughnessMapTransform: { value: new b() } }, gradientmap: { gradientMap: { value: null } }, fog: { fogDensity: { value: 25e-5 }, fogNear: { value: 1 }, fogFar: { value: 2e3 }, fogColor: { value: new N(16777215) } }, lights: { ambientLightColor: { value: [] }, lightProbe: { value: [] }, directionalLights: { value: [], properties: { direction: {}, color: {} } }, directionalLightShadows: { value: [], properties: { shadowIntensity: 1, shadowBias: {}, shadowNormalBias: {}, shadowRadius: {}, shadowMapSize: {} } }, directionalShadowMatrix: { value: [] }, spotLights: { value: [], properties: { color: {}, position: {}, direction: {}, distance: {}, coneCos: {}, penumbraCos: {}, decay: {} } }, spotLightShadows: { value: [], properties: { shadowIntensity: 1, shadowBias: {}, shadowNormalBias: {}, shadowRadius: {}, shadowMapSize: {} } }, spotLightMap: { value: [] }, spotLightMatrix: { value: [] }, pointLights: { value: [], properties: { color: {}, position: {}, decay: {}, distance: {} } }, pointLightShadows: { value: [], properties: { shadowIntensity: 1, shadowBias: {}, shadowNormalBias: {}, shadowRadius: {}, shadowMapSize: {}, shadowCameraNear: {}, shadowCameraFar: {} } }, pointShadowMatrix: { value: [] }, hemisphereLights: { value: [], properties: { direction: {}, skyColor: {}, groundColor: {} } }, rectAreaLights: { value: [], properties: { color: {}, position: {}, width: {}, height: {} } }, ltc_1: { value: null }, ltc_2: { value: null }, probesSH: { value: null }, probesMin: { value: new w() }, probesMax: { value: new w() }, probesResolution: { value: new w() } }, points: { diffuse: { value: new N(16777215) }, opacity: { value: 1 }, size: { value: 1 }, scale: { value: 1 }, map: { value: null }, alphaMap: { value: null }, alphaMapTransform: { value: new b() }, alphaTest: { value: 0 }, uvTransform: { value: new b() } }, sprite: { diffuse: { value: new N(16777215) }, opacity: { value: 1 }, center: { value: new Z(0.5, 0.5) }, rotation: { value: 0 }, map: { value: null }, mapTransform: { value: new b() }, alphaMap: { value: null }, alphaMapTransform: { value: new b() }, alphaTest: { value: 0 } } }; var _n = { basic: { uniforms: V([x.common, x.specularmap, x.envmap, x.aomap, x.lightmap, x.fog]), vertexShader: T.meshbasic_vert, fragmentShader: T.meshbasic_frag }, lambert: { uniforms: V([x.common, x.specularmap, x.envmap, x.aomap, x.lightmap, x.emissivemap, x.bumpmap, x.normalmap, x.displacementmap, x.fog, x.lights, { emissive: { value: new N(0) }, envMapIntensity: { value: 1 } }]), vertexShader: T.meshlambert_vert, fragmentShader: T.meshlambert_frag }, phong: { uniforms: V([x.common, x.specularmap, x.envmap, x.aomap, x.lightmap, x.emissivemap, x.bumpmap, x.normalmap, x.displacementmap, x.fog, x.lights, { emissive: { value: new N(0) }, specular: { value: new N(1118481) }, shininess: { value: 30 }, envMapIntensity: { value: 1 } }]), vertexShader: T.meshphong_vert, fragmentShader: T.meshphong_frag }, standard: { uniforms: V([x.common, x.envmap, x.aomap, x.lightmap, x.emissivemap, x.bumpmap, x.normalmap, x.displacementmap, x.roughnessmap, x.metalnessmap, x.fog, x.lights, { emissive: { value: new N(0) }, roughness: { value: 1 }, metalness: { value: 0 }, envMapIntensity: { value: 1 } }]), vertexShader: T.meshphysical_vert, fragmentShader: T.meshphysical_frag }, toon: { uniforms: V([x.common, x.aomap, x.lightmap, x.emissivemap, x.bumpmap, x.normalmap, x.displacementmap, x.gradientmap, x.fog, x.lights, { emissive: { value: new N(0) } }]), vertexShader: T.meshtoon_vert, fragmentShader: T.meshtoon_frag }, matcap: { uniforms: V([x.common, x.bumpmap, x.normalmap, x.displacementmap, x.fog, { matcap: { value: null } }]), vertexShader: T.meshmatcap_vert, fragmentShader: T.meshmatcap_frag }, points: { uniforms: V([x.points, x.fog]), vertexShader: T.points_vert, fragmentShader: T.points_frag }, dashed: { uniforms: V([x.common, x.fog, { scale: { value: 1 }, dashSize: { value: 1 }, totalSize: { value: 2 } }]), vertexShader: T.linedashed_vert, fragmentShader: T.linedashed_frag }, depth: { uniforms: V([x.common, x.displacementmap]), vertexShader: T.depth_vert, fragmentShader: T.depth_frag }, normal: { uniforms: V([x.common, x.bumpmap, x.normalmap, x.displacementmap, { opacity: { value: 1 } }]), vertexShader: T.meshnormal_vert, fragmentShader: T.meshnormal_frag }, sprite: { uniforms: V([x.sprite, x.fog]), vertexShader: T.sprite_vert, fragmentShader: T.sprite_frag }, background: { uniforms: { uvTransform: { value: new b() }, t2D: { value: null }, backgroundIntensity: { value: 1 } }, vertexShader: T.background_vert, fragmentShader: T.background_frag }, backgroundCube: { uniforms: { envMap: { value: null }, backgroundBlurriness: { value: 0 }, backgroundIntensity: { value: 1 }, backgroundRotation: { value: new b() } }, vertexShader: T.backgroundCube_vert, fragmentShader: T.backgroundCube_frag }, cube: { uniforms: { tCube: { value: null }, tFlip: { value: -1 }, opacity: { value: 1 } }, vertexShader: T.cube_vert, fragmentShader: T.cube_frag }, equirect: { uniforms: { tEquirect: { value: null } }, vertexShader: T.equirect_vert, fragmentShader: T.equirect_frag }, distance: { uniforms: V([x.common, x.displacementmap, { referencePosition: { value: new w() }, nearDistance: { value: 1 }, farDistance: { value: 1e3 } }]), vertexShader: T.distance_vert, fragmentShader: T.distance_frag }, shadow: { uniforms: V([x.lights, x.fog, { color: { value: new N(0) }, opacity: { value: 1 } }]), vertexShader: T.shadow_vert, fragmentShader: T.shadow_frag } }; _n.physical = { uniforms: V([_n.standard.uniforms, { clearcoat: { value: 0 }, clearcoatMap: { value: null }, clearcoatMapTransform: { value: new b() }, clearcoatNormalMap: { value: null }, clearcoatNormalMapTransform: { value: new b() }, clearcoatNormalScale: { value: new Z(1, 1) }, clearcoatRoughness: { value: 0 }, clearcoatRoughnessMap: { value: null }, clearcoatRoughnessMapTransform: { value: new b() }, dispersion: { value: 0 }, iridescence: { value: 0 }, iridescenceMap: { value: null }, iridescenceMapTransform: { value: new b() }, iridescenceIOR: { value: 1.3 }, iridescenceThicknessMinimum: { value: 100 }, iridescenceThicknessMaximum: { value: 400 }, iridescenceThicknessMap: { value: null }, iridescenceThicknessMapTransform: { value: new b() }, sheen: { value: 0 }, sheenColor: { value: new N(0) }, sheenColorMap: { value: null }, sheenColorMapTransform: { value: new b() }, sheenRoughness: { value: 1 }, sheenRoughnessMap: { value: null }, sheenRoughnessMapTransform: { value: new b() }, transmission: { value: 0 }, transmissionMap: { value: null }, transmissionMapTransform: { value: new b() }, transmissionSamplerSize: { value: new Z() }, transmissionSamplerMap: { value: null }, thickness: { value: 0 }, thicknessMap: { value: null }, thicknessMapTransform: { value: new b() }, attenuationDistance: { value: 0 }, attenuationColor: { value: new N(0) }, specularColor: { value: new N(1, 1, 1) }, specularColorMap: { value: null }, specularColorMapTransform: { value: new b() }, specularIntensity: { value: 1 }, specularIntensityMap: { value: null }, specularIntensityMapTransform: { value: new b() }, anisotropyVector: { value: new Z() }, anisotropyMap: { value: null }, anisotropyMapTransform: { value: new b() } }]), vertexShader: T.meshphysical_vert, fragmentShader: T.meshphysical_frag }; var Nr = new b(); Nr.set(-1, 0, 0, 0, 1, 0, 0, 0, 1); var tc = { [yt]: "LINEAR_TONE_MAPPING", [Mt]: "REINHARD_TONE_MAPPING", [St]: "CINEON_TONE_MAPPING", [bt]: "ACES_FILMIC_TONE_MAPPING", [Et]: "AGX_TONE_MAPPING", [At]: "NEUTRAL_TONE_MAPPING", [Tt]: "CUSTOM_TONE_MAPPING" }; var nc = new Float32Array(16); var ic = new Float32Array(9); var sc = new Float32Array(4); var rc = { [yt]: "Linear", [Mt]: "Reinhard", [St]: "Cineon", [bt]: "ACESFilmic", [Et]: "AgX", [At]: "Neutral", [Tt]: "Custom" }; var ac = { [tn]: "SHADOWMAP_TYPE_PCF", [nn]: "SHADOWMAP_TYPE_VSM" }; var oc = { [ln]: "ENVMAP_TYPE_CUBE", [wt]: "ENVMAP_TYPE_CUBE", [cn]: "ENVMAP_TYPE_CUBE_UV" }; var lc = { [wt]: "ENVMAP_MODE_REFRACTION" }; var cc = { [sn]: "ENVMAP_BLENDING_MULTIPLY", [rn]: "ENVMAP_BLENDING_MIX", [an]: "ENVMAP_BLENDING_ADD" }; var Ur = new b(); Ur.set(-1, 0, 0, 0, 1, 0, 0, 0, 1); var hc = new Uint16Array([12469, 15057, 12620, 14925, 13266, 14620, 13807, 14376, 14323, 13990, 14545, 13625, 14713, 13328, 14840, 12882, 14931, 12528, 14996, 12233, 15039, 11829, 15066, 11525, 15080, 11295, 15085, 10976, 15082, 10705, 15073, 10495, 13880, 14564, 13898, 14542, 13977, 14430, 14158, 14124, 14393, 13732, 14556, 13410, 14702, 12996, 14814, 12596, 14891, 12291, 14937, 11834, 14957, 11489, 14958, 11194, 14943, 10803, 14921, 10506, 14893, 10278, 14858, 9960, 14484, 14039, 14487, 14025, 14499, 13941, 14524, 13740, 14574, 13468, 14654, 13106, 14743, 12678, 14818, 12344, 14867, 11893, 14889, 11509, 14893, 11180, 14881, 10751, 14852, 10428, 14812, 10128, 14765, 9754, 14712, 9466, 14764, 13480, 14764, 13475, 14766, 13440, 14766, 13347, 14769, 13070, 14786, 12713, 14816, 12387, 14844, 11957, 14860, 11549, 14868, 11215, 14855, 10751, 14825, 10403, 14782, 10044, 14729, 9651, 14666, 9352, 14599, 9029, 14967, 12835, 14966, 12831, 14963, 12804, 14954, 12723, 14936, 12564, 14917, 12347, 14900, 11958, 14886, 11569, 14878, 11247, 14859, 10765, 14828, 10401, 14784, 10011, 14727, 9600, 14660, 9289, 14586, 8893, 14508, 8533, 15111, 12234, 15110, 12234, 15104, 12216, 15092, 12156, 15067, 12010, 15028, 11776, 14981, 11500, 14942, 11205, 14902, 10752, 14861, 10393, 14812, 9991, 14752, 9570, 14682, 9252, 14603, 8808, 14519, 8445, 14431, 8145, 15209, 11449, 15208, 11451, 15202, 11451, 15190, 11438, 15163, 11384, 15117, 11274, 15055, 10979, 14994, 10648, 14932, 10343, 14871, 9936, 14803, 9532, 14729, 9218, 14645, 8742, 14556, 8381, 14461, 8020, 14365, 7603, 15273, 10603, 15272, 10607, 15267, 10619, 15256, 10631, 15231, 10614, 15182, 10535, 15118, 10389, 15042, 10167, 14963, 9787, 14883, 9447, 14800, 9115, 14710, 8665, 14615, 8318, 14514, 7911, 14411, 7507, 14279, 7198, 15314, 9675, 15313, 9683, 15309, 9712, 15298, 9759, 15277, 9797, 15229, 9773, 15166, 9668, 15084, 9487, 14995, 9274, 14898, 8910, 14800, 8539, 14697, 8234, 14590, 7790, 14479, 7409, 14367, 7067, 14178, 6621, 15337, 8619, 15337, 8631, 15333, 8677, 15325, 8769, 15305, 8871, 15264, 8940, 15202, 8909, 15119, 8775, 15022, 8565, 14916, 8328, 14804, 8009, 14688, 7614, 14569, 7287, 14448, 6888, 14321, 6483, 14088, 6171, 15350, 7402, 15350, 7419, 15347, 7480, 15340, 7613, 15322, 7804, 15287, 7973, 15229, 8057, 15148, 8012, 15046, 7846, 14933, 7611, 14810, 7357, 14682, 7069, 14552, 6656, 14421, 6316, 14251, 5948, 14007, 5528, 15356, 5942, 15356, 5977, 15353, 6119, 15348, 6294, 15332, 6551, 15302, 6824, 15249, 7044, 15171, 7122, 15070, 7050, 14949, 6861, 14818, 6611, 14679, 6349, 14538, 6067, 14398, 5651, 14189, 5311, 13935, 4958, 15359, 4123, 15359, 4153, 15356, 4296, 15353, 4646, 15338, 5160, 15311, 5508, 15263, 5829, 15188, 6042, 15088, 6094, 14966, 6001, 14826, 5796, 14678, 5543, 14527, 5287, 14377, 4985, 14133, 4586, 13869, 4257, 15360, 1563, 15360, 1642, 15358, 2076, 15354, 2636, 15341, 3350, 15317, 4019, 15273, 4429, 15203, 4732, 15105, 4911, 14981, 4932, 14836, 4818, 14679, 4621, 14517, 4386, 14359, 4156, 14083, 3795, 13808, 3437, 15360, 122, 15360, 137, 15358, 285, 15355, 636, 15344, 1274, 15322, 2177, 15281, 2765, 15215, 3223, 15120, 3451, 14995, 3569, 14846, 3567, 14681, 3466, 14511, 3305, 14344, 3121, 14037, 2800, 13753, 2467, 15360, 0, 15360, 1, 15359, 21, 15355, 89, 15346, 253, 15325, 479, 15287, 796, 15225, 1148, 15133, 1492, 15008, 1749, 14856, 1882, 14685, 1886, 14506, 1783, 14324, 1608, 13996, 1398, 13702, 1183]); // src/tools/load.weather.ts var ENERGYPLUS_BASE = "https://energyplus-weather.s3.amazonaws.com"; var DEFAULT_WEATHER_BASE = "https://deta.city/studio/data"; function weatherLibraryBase() { try { const raw = String(process.env?.DETA_WEATHER_BASE_URL ?? "").replace(/\/+$/, ""); return raw || DEFAULT_WEATHER_BASE; } catch { return DEFAULT_WEATHER_BASE; } } var STATION_CSV_COLUMNS = { station: "\u7AD9\u540D", city: "\u57CE\u5E02", zip: "Onebuliding" }; function parseStationCsv(text2) { const lines = text2.split(/\r?\n/).filter((l13) => l13.trim() !== ""); if (lines.length < 2) return []; const header = lines[0].replace(/^\uFEFF/, "").split(","); const iStation = header.indexOf(STATION_CSV_COLUMNS.station); const iCity = header.indexOf(STATION_CSV_COLUMNS.city); const iZip = header.indexOf(STATION_CSV_COLUMNS.zip); if (iZip < 0) return []; const out = []; for (const line2 of lines.slice(1)) { const cols = line2.split(","); const zip2 = (cols[iZip] ?? "").trim(); if (!zip2 || zip2 === "0" || !zip2.toLowerCase().endsWith(".zip")) continue; out.push({ station: iStation >= 0 ? (cols[iStation] ?? "").trim() : "", city: iCity >= 0 ? (cols[iCity] ?? "").trim() : "", zip: zip2 }); } return out; } var stationIndexCache = null; async function loadStationIndex(base = weatherLibraryBase()) { if (stationIndexCache) return stationIndexCache; const pending = (async () => { const resp = await fetch(`${base}/stationlist.csv`, { signal: AbortSignal.timeout(15e3) }); if (!resp.ok) throw new Error(`\u7AD9\u70B9\u6E05\u5355\u62C9\u53D6\u5931\u8D25\uFF1AHTTP ${resp.status}`); return parseStationCsv(await resp.text()); })(); stationIndexCache = pending; pending.catch(() => { if (stationIndexCache === pending) stationIndexCache = null; }); return pending; } function normalizePlace(s2) { return String(s2 ?? "").trim().replace(/[\s\u3000]/g, "").replace(/(市|省|自治区)$/, ""); } function matchStation(records, location) { const loc = normalizePlace(location); if (!loc) return null; const same = (v2) => normalizePlace(v2) === loc; const contains = (v2) => { const n5 = normalizePlace(v2); return n5 !== "" && (n5.includes(loc) || loc.includes(n5)); }; const byStation = records.find((r4) => same(r4.station)); if (byStation) return byStation; const sameCity = records.filter((r4) => same(r4.city)); if (sameCity.length > 0) { return sameCity.find((r4) => contains(r4.station)) ?? sameCity[0]; } const fuzzy = records.find((r4) => contains(r4.station) || contains(r4.city)); if (fuzzy) return fuzzy; const locLower = loc.toLowerCase(); return records.find((r4) => r4.zip.toLowerCase().includes(locLower)) ?? null; } async function fetchLibraryEpw(zipFilename, base = weatherLibraryBase()) { const resp = await fetch(`${base}/weather/${encodeURIComponent(zipFilename)}`, { signal: AbortSignal.timeout(2e4) }); if (!resp.ok) return null; const bytes = new Uint8Array(await resp.arrayBuffer()); if (bytes.length < 4 || bytes[0] !== 80 || bytes[1] !== 75) return null; const { unzipSync: unzipSync2 } = await Promise.resolve().then(() => (init_esm(), esm_exports)); const files = unzipSync2(bytes); const epwName = Object.keys(files).find((n5) => n5.toLowerCase().endsWith(".epw")); if (!epwName) return null; const data = Mn(new TextDecoder().decode(files[epwName])); return data.rows?.length ? data : null; } async function fetchRealEpw(location, baseUrl) { const libraryBase = weatherLibraryBase(); const libraryMiss = []; try { const records = await loadStationIndex(libraryBase); const hit = matchStation(records, location); if (hit) { const data = await fetchLibraryEpw(hit.zip, libraryBase); if (data) return data; libraryMiss.push(`\u5E93\u5185\u6587\u4EF6\u4E0D\u53EF\u7528\uFF1A${hit.zip}`); } else { libraryMiss.push(`\u7AD9\u70B9\u6E05\u5355\u65E0\u300C${location}\u300D`); } } catch (e5) { libraryMiss.push(`\u6C14\u8C61\u5E93\u4E0D\u53EF\u8FBE\uFF1A${e5?.message ?? e5}`); } const url2 = baseUrl || ENERGYPLUS_BASE; const candidates = buildCandidateUrls(location, url2); for (const epwUrl of candidates) { try { const response = await fetch(epwUrl, { signal: AbortSignal.timeout(8e3) }); if (!response.ok) continue; const text2 = await response.text(); const data = Mn(text2); if (data.rows.length > 0) return data; } catch { continue; } } throw new Error( `\u65E0\u6CD5\u83B7\u53D6 ${location} \u7684 EPW \u6570\u636E\uFF08\u81EA\u5E26\u6C14\u8C61\u5E93\uFF1A${libraryMiss.join("\uFF1B") || "\u672A\u547D\u4E2D"}\uFF1B\u5728\u7EBF\u6E90 ${url2} \u4E0D\u53EF\u8FBE\uFF09` ); } function buildCandidateUrls(location, baseUrl) { const candidates = []; const loc = location.toLowerCase(); if (baseUrl !== ENERGYPLUS_BASE) { candidates.push(`${baseUrl}/${loc.replace(/\s+/g, "_")}.epw`); } if (/beijing|北京/.test(loc)) { candidates.push( "https://climate.onebuilding.org/WMO_Region_2_Asia/CHN_China/CHN_BJ_Beijing.545110_TMYx.epw" ); } if (/shanghai|上海/.test(loc)) { candidates.push( "https://climate.onebuilding.org/WMO_Region_2_Asia/CHN_China/CHN_SH_Shanghai.583620_TMYx.epw" ); } if (/shenzhen|深圳/.test(loc)) { candidates.push( "https://climate.onebuilding.org/WMO_Region_2_Asia/CHN_China/CHN_GD_Shenzhen.594930_TMYx.epw" ); } return candidates; } function formatWeatherSummary(epwData, location, source) { const { header, rows } = epwData; const byMonth = groupByMonth(rows); const temps = rows.map((r4) => r4.dryBulbTemperature); const hums = rows.filter((r4) => r4.relativeHumidity >= 0).map((r4) => r4.relativeHumidity); const winds = rows.map((r4) => r4.windSpeed); const solars = rows.map((r4) => r4.globalHorizontalRad); const avgTemp = average(temps); const minTemp = Math.min(...temps); const maxTemp = Math.max(...temps); let hdd = 0; let cdd = 0; for (const t4 of temps) { if (t4 < 18) hdd += 18 - t4; else cdd += t4 - 18; } hdd /= 24; cdd /= 24; const totalSolar = solars.reduce((sum, v2) => sum + Math.max(0, v2), 0) / 1e3; const monthly = []; for (let m3 = 1; m3 <= 12; m3++) { const mRows = byMonth.get(m3) || []; if (mRows.length === 0) { monthly.push({ month: m3, avgTemp: 0, minTemp: 0, maxTemp: 0, avgHumidity: 0, avgWindSpeed: 0, totalGlobalHorizontalRad: 0 }); continue; } const mTemps = mRows.map((r4) => r4.dryBulbTemperature); const mHums = mRows.filter((r4) => r4.relativeHumidity >= 0).map((r4) => r4.relativeHumidity); const mWinds = mRows.map((r4) => r4.windSpeed); const mSolars = mRows.map((r4) => r4.globalHorizontalRad); monthly.push({ month: m3, avgTemp: average(mTemps), minTemp: Math.min(...mTemps), maxTemp: Math.max(...mTemps), avgHumidity: mHums.length > 0 ? average(mHums) : 0, avgWindSpeed: average(mWinds), totalGlobalHorizontalRad: mSolars.reduce((s2, v2) => s2 + Math.max(0, v2), 0) / 1e3 }); } return { location, source, station: { name: header.location, country: header.country, latitude: header.latitude, longitude: header.longitude, elevation: header.elevation, timezone: header.timeZone }, annual: { avgTemperature: round1(avgTemp), minTemperature: round1(minTemp), maxTemperature: round1(maxTemp), avgRelativeHumidity: round1(hums.length > 0 ? average(hums) : 0), avgWindSpeed: round1(average(winds)), maxWindSpeed: round1(Math.max(...winds)), totalGlobalHorizontalRad: round1(totalSolar), heatingDegreeDays: round1(hdd), coolingDegreeDays: round1(cdd) }, monthly, message: buildMessage(location, avgTemp, minTemp, maxTemp) }; } var MOCK_CLIMATE_DATA = { beijing: createMockSummary( "\u5317\u4EAC", { name: "\u5317\u4EAC\u9996\u90FD\u56FD\u9645\u673A\u573A", country: "CHN", latitude: 39.93, longitude: 116.28, elevation: 55, timezone: 8 }, { avgT: 12.5, minT: -8, maxT: 35, avgH: 50, avgW: 2.5, maxW: 12, sol: 1450, hdd: 2720, cdd: 890 }, [ { m: 1, at: -3, mit: -8, mat: 2, ah: 45, aw: 2.8, sr: 85 }, { m: 2, at: 0.5, mit: -5, mat: 6, ah: 42, aw: 2.9, sr: 95 }, { m: 3, at: 7, mit: 1, mat: 14, ah: 44, aw: 2.8, sr: 125 }, { m: 4, at: 15, mit: 8, mat: 22, ah: 47, aw: 2.7, sr: 145 }, { m: 5, at: 21, mit: 14, mat: 28, ah: 52, aw: 2.5, sr: 160 }, { m: 6, at: 26, mit: 19, mat: 33, ah: 58, aw: 2.2, sr: 155 }, { m: 7, at: 28, mit: 22, mat: 35, ah: 65, aw: 2, sr: 150 }, { m: 8, at: 26.5, mit: 21, mat: 33, ah: 66, aw: 2, sr: 140 }, { m: 9, at: 21, mit: 14, mat: 28, ah: 58, aw: 2.2, sr: 125 }, { m: 10, at: 14, mit: 7, mat: 21, ah: 52, aw: 2.4, sr: 105 }, { m: 11, at: 5, mit: -1, mat: 12, ah: 47, aw: 2.6, sr: 85 }, { m: 12, at: -1, mit: -6, mat: 4, ah: 44, aw: 2.7, sr: 80 } ] ), shanghai: createMockSummary( "\u4E0A\u6D77", { name: "\u4E0A\u6D77\u8679\u6865\u56FD\u9645\u673A\u573A", country: "CHN", latitude: 31.2, longitude: 121.33, elevation: 10, timezone: 8 }, { avgT: 16.5, minT: -3, maxT: 36, avgH: 72, avgW: 3, maxW: 14, sol: 1250, hdd: 1690, cdd: 1260 }, [ { m: 1, at: 4.5, mit: -1, mat: 9, ah: 70, aw: 3, sr: 75 }, { m: 2, at: 6, mit: 1, mat: 11, ah: 69, aw: 3.1, sr: 80 }, { m: 3, at: 10, mit: 5, mat: 15, ah: 68, aw: 3.2, sr: 100 }, { m: 4, at: 15.5, mit: 10, mat: 21, ah: 70, aw: 3, sr: 115 }, { m: 5, at: 21, mit: 16, mat: 26, ah: 73, aw: 2.8, sr: 120 }, { m: 6, at: 25, mit: 20, mat: 31, ah: 80, aw: 2.6, sr: 115 }, { m: 7, at: 28.5, mit: 24, mat: 35, ah: 82, aw: 2.8, sr: 135 }, { m: 8, at: 28, mit: 24, mat: 36, ah: 82, aw: 2.9, sr: 125 }, { m: 9, at: 24, mit: 19, mat: 30, ah: 78, aw: 2.7, sr: 100 }, { m: 10, at: 18.5, mit: 13, mat: 24, ah: 73, aw: 2.8, sr: 90 }, { m: 11, at: 12.5, mit: 7, mat: 18, ah: 70, aw: 2.9, sr: 75 }, { m: 12, at: 6.5, mit: 1, mat: 12, ah: 68, aw: 3, sr: 70 } ] ), shenzhen: createMockSummary( "\u6DF1\u5733", { name: "\u6DF1\u5733\u5B9D\u5B89\u56FD\u9645\u673A\u573A", country: "CHN", latitude: 22.64, longitude: 114.01, elevation: 4, timezone: 8 }, { avgT: 22.5, minT: 5, maxT: 36, avgH: 78, avgW: 2.8, maxW: 14, sol: 1300, hdd: 380, cdd: 2250 }, [ { m: 1, at: 15, mit: 8, mat: 20, ah: 72, aw: 2.8, sr: 90 }, { m: 2, at: 16, mit: 10, mat: 21, ah: 74, aw: 2.9, sr: 85 }, { m: 3, at: 19, mit: 14, mat: 24, ah: 76, aw: 2.8, sr: 95 }, { m: 4, at: 23, mit: 18, mat: 28, ah: 80, aw: 2.6, sr: 105 }, { m: 5, at: 26.5, mit: 22, mat: 32, ah: 82, aw: 2.5, sr: 120 }, { m: 6, at: 28.5, mit: 24, mat: 34, ah: 84, aw: 2.4, sr: 120 }, { m: 7, at: 29.5, mit: 25, mat: 36, ah: 84, aw: 2.5, sr: 135 }, { m: 8, at: 29, mit: 25, mat: 35, ah: 84, aw: 2.5, sr: 125 }, { m: 9, at: 27.5, mit: 23, mat: 33, ah: 81, aw: 2.6, sr: 110 }, { m: 10, at: 24.5, mit: 19, mat: 30, ah: 75, aw: 2.9, sr: 100 }, { m: 11, at: 20.5, mit: 14, mat: 26, ah: 72, aw: 2.9, sr: 90 }, { m: 12, at: 16.5, mit: 10, mat: 22, ah: 70, aw: 2.8, sr: 85 } ] ), denver: createMockSummary( "Denver", { name: "Denver International Airport", country: "USA", latitude: 39.86, longitude: -104.67, elevation: 1656, timezone: -7 }, { avgT: 10.5, minT: -12, maxT: 36, avgH: 52, avgW: 3.5, maxW: 16, sol: 1680, hdd: 3280, cdd: 580 }, [ { m: 1, at: -0.5, mit: -8, mat: 6, ah: 56, aw: 3.3, sr: 100 }, { m: 2, at: 1.5, mit: -6, mat: 8, ah: 54, aw: 3.4, sr: 115 }, { m: 3, at: 5.5, mit: -3, mat: 13, ah: 52, aw: 3.6, sr: 145 }, { m: 4, at: 10, mit: 2, mat: 18, ah: 50, aw: 3.8, sr: 155 }, { m: 5, at: 15, mit: 7, mat: 23, ah: 52, aw: 3.7, sr: 165 }, { m: 6, at: 21, mit: 11, mat: 30, ah: 48, aw: 3.5, sr: 175 }, { m: 7, at: 24, mit: 15, mat: 33, ah: 47, aw: 3.3, sr: 175 }, { m: 8, at: 22.5, mit: 14, mat: 32, ah: 49, aw: 3.2, sr: 160 }, { m: 9, at: 17.5, mit: 8, mat: 27, ah: 50, aw: 3.3, sr: 140 }, { m: 10, at: 10.5, mit: 2, mat: 20, ah: 52, aw: 3.3, sr: 120 }, { m: 11, at: 4, mit: -4, mat: 12, ah: 55, aw: 3.3, sr: 95 }, { m: 12, at: -0.5, mit: -8, mat: 7, ah: 57, aw: 3.2, sr: 90 } ] ) }; var CITY_ALIAS = { "\u5317\u4EAC": "beijing", "\u4E0A\u6D77": "shanghai", "\u6DF1\u5733": "shenzhen" }; function getMockWeatherData(location) { const key = location.toLowerCase().replace(/[^a-z\u4e00-\u9fff]/g, ""); const aliasKey = CITY_ALIAS[key]; if (aliasKey && MOCK_CLIMATE_DATA[aliasKey]) { return { ...MOCK_CLIMATE_DATA[aliasKey], location, source: "mock" }; } if (MOCK_CLIMATE_DATA[key]) { return { ...MOCK_CLIMATE_DATA[key], source: "mock" }; } for (const [cityKey, data] of Object.entries(MOCK_CLIMATE_DATA)) { if (key.includes(cityKey) || cityKey.includes(key)) { return { ...data, location, source: "mock" }; } } return { location, source: "mock", station: { name: location, country: "Unknown", latitude: 30, longitude: 120, elevation: 50, timezone: 8 }, annual: { avgTemperature: 18, minTemperature: 0, maxTemperature: 35, avgRelativeHumidity: 65, avgWindSpeed: 2.5, maxWindSpeed: 12, totalGlobalHorizontalRad: 1300, heatingDegreeDays: 1200, coolingDegreeDays: 1500 }, monthly: Array.from({ length: 12 }, (_2, i4) => ({ month: i4 + 1, avgTemp: 5 + i4 * 2.5, minTemp: 0 + i4 * 2, maxTemp: 10 + i4 * 2.5, avgHumidity: 60 + (i4 < 6 ? i4 * 2 : (12 - i4) * 2), avgWindSpeed: 2.5, totalGlobalHorizontalRad: 80 + i4 * 8 })), message: `\u300C${location}\u300D\u672A\u627E\u5230\u7CBE\u786E\u5339\u914D\u7684\u6C14\u8C61\u6570\u636E\uFF0C\u4F7F\u7528\u901A\u7528\u9ED8\u8BA4\u503C\u3002\u5EFA\u8BAE\u63D0\u4F9B\u66F4\u7CBE\u786E\u7684\u5730\u70B9\u540D\u79F0\u3002` }; } function groupByMonth(rows) { const map2 = /* @__PURE__ */ new Map(); for (const row of rows) { const list = map2.get(row.month); if (list) list.push(row); else map2.set(row.month, [row]); } return map2; } function average(values) { if (values.length === 0) return 0; return values.reduce((s2, v2) => s2 + v2, 0) / values.length; } function round1(v2) { return Math.round(v2 * 10) / 10; } function buildMessage(location, avgTemp, minTemp, maxTemp, source = "live") { const facts = `\u5E74\u5747\u6E29 ${round1(avgTemp)}\xB0C\uFF0C\u6781\u7AEF\u4F4E\u6E29 ${round1(minTemp)}\xB0C\uFF0C\u6781\u7AEF\u9AD8\u6E29 ${round1(maxTemp)}\xB0C\u3002`; return source === "live" ? [`\u300C${location}\u300D\u6C14\u8C61\u6570\u636E\u5DF2\u5C31\u7EEA\u3002`, facts, `\u53EF\u57FA\u4E8E\u6B64\u6570\u636E\u8FDB\u884C\u80FD\u8017\u6A21\u62DF\u3001\u70ED\u5DE5\u5206\u6790\u548C\u88AB\u52A8\u5F0F\u7B56\u7565\u8BC4\u4F30\u3002`].join(" ") : [`\u300C${location}\u300D\u4E3A\u6A21\u62DF\u6458\u8981\uFF08\u975E\u771F\u5B9E EPW\uFF09\uFF0C\u4EC5\u4F5C\u5360\u4F4D\u3002`, facts, `**\u4E0D\u53EF\u7528\u4E8E\u80FD\u8017\u6A21\u62DF\u6216\u5408\u89C4\u5224\u5B9A**\uFF1A\u8BF7\u6539\u7528\u81EA\u5E26\u6C14\u8C61\u5E93\u5185\u6709\u6570\u636E\u7684\u7AD9\u70B9\uFF0C\u6216\u663E\u5F0F\u4F20 epwUrl\u3002`].join(" "); } function createMockSummary(location, station, annual, monthData) { return { location, source: "mock", station, annual: { avgTemperature: annual.avgT, minTemperature: annual.minT, maxTemperature: annual.maxT, avgRelativeHumidity: annual.avgH, avgWindSpeed: annual.avgW, maxWindSpeed: annual.maxW, totalGlobalHorizontalRad: annual.sol, heatingDegreeDays: annual.hdd, coolingDegreeDays: annual.cdd }, monthly: monthData.map((d2) => ({ month: d2.m, avgTemp: d2.at, minTemp: d2.mit, maxTemp: d2.mat, avgHumidity: d2.ah, avgWindSpeed: d2.aw, totalGlobalHorizontalRad: d2.sr })), message: buildMessage(location, annual.avgT, annual.minT, annual.maxT, "mock") }; } function createLoadWeather(options) { return tool({ description: "\u52A0\u8F7D\u6C14\u8C61\u6570\u636E\uFF08EPW\uFF09\u2014\u2014**\u6A21\u62DF\u7684\u524D\u7F6E\u6761\u4EF6**\u3002\u6709 Studio \u6267\u884C\u5668\u65F6\u59D4\u6258 Studio \u5185\u7F6E\u547D\u4EE4\u771F\u6B63\u8F7D\u5165\u9879\u76EE\uFF08\u4E0E\u9762\u677F\u540C\u6E90\uFF09\uFF1B\u65E0\u6267\u884C\u5668\u65F6\u4EC5\u8FD4\u56DE\u6C14\u5019\u6458\u8981\u5E76\u6807\u6CE8\u300C\u672A\u8F7D\u5165\u300D\u3002\u8FD4\u56DE\u542B\u5E74\u5747\u6E29\u3001\u8F90\u5C04\u3001\u5EA6\u65E5\u6570\u7B49\u6458\u8981\u6307\u6807\u3002Studio \u4FA7\u540C\u540D\u547D\u4EE4\u662F `load_weather_data`\uFF08\u8981\u76F4\u63A5\u8C03\u5B83\u5F97\u7ECF studio_command\uFF09\uFF0C**\u65E5\u5E38\u7528\u672C\u5DE5\u5177\u5373\u53EF**\uFF0C\u4E0D\u5FC5\u7ED5\u9053\u3002", inputSchema: external_exports2.object({ location: external_exports2.string().describe('\u57CE\u5E02/\u5730\u70B9\u540D\u79F0\uFF0C\u5982 "\u5317\u4EAC"\u3001"Shanghai"\u3001"Tokyo"\u3001"Denver"') }), execute: async ({ location }, execOpts) => { const context = execOpts?.context ?? {}; const run = context?.runCommand; if (typeof run === "function") { const out = await run("load_weather_data", { location }); const ok = !(out && typeof out === "object" && out.error); return { status: ok ? "success" : "error", location, loaded_into_studio: ok, executor: "studio", message: ok ? String(out?.message ?? `\u6C14\u8C61\u6570\u636E\u5DF2\u52A0\u8F7D: ${location}`) : String(out?.error ?? "Studio \u8F7D\u5165\u6C14\u8C61\u6570\u636E\u5931\u8D25"), result: out ?? null }; } try { const epwData = await fetchRealEpw(location, options?.baseUrl); return { ...formatWeatherSummary(epwData, location, "live"), loaded_into_studio: false, note: "Studio \u6267\u884C\u5668\u672A\u63A5\u5165\uFF1A\u4EC5\u8FD4\u56DE\u6C14\u5019\u6458\u8981\uFF0C**\u672A\u8F7D\u5165 Studio \u9879\u76EE**\uFF1B\u8F7D\u5165\u9700\u5728 ant-model \u6253\u5F00\u9879\u76EE\u540E\u91CD\u8BD5\uFF08\u6A21\u62DF\u7684\u524D\u7F6E\u6761\u4EF6\uFF09" }; } catch { return { ...getMockWeatherData(location), loaded_into_studio: false, note: "Studio \u6267\u884C\u5668\u672A\u63A5\u5165\u4E14\u5728\u7EBF\u6C14\u8C61\u6E90\u4E0D\u53EF\u7528\uFF1A\u4EE5\u4E0B\u4E3A\u6A21\u62DF\u6458\u8981\uFF0C**\u672A\u8F7D\u5165 Studio \u9879\u76EE**" }; } } }); } // skills/design-arch/scripts/aml-parse.js function _attrs(tag) { const out = {}; const re2 = /([\w-]+)="([^"]*)"/g; let m3; while (m3 = re2.exec(tag)) out[m3[1]] = m3[2]; return out; } function amlLabelPosition(lbl, spacings, labels) { const m3 = lbl.match(/^([A-Za-z0-9]+)([+-]\d+(?:\.\d+)?)m?$/); const baseLabel = m3 ? m3[1] : lbl; const offset = m3 ? parseFloat(m3[2]) : 0; const idx = labels.indexOf(baseLabel); if (idx < 0) return null; let pos = 0; for (let i4 = 0; i4 < idx; i4++) pos += spacings[i4] ?? 0; return pos + offset; } function parseAmlLite(aml) { const out = { rooms: [], levels: [] }; if (!aml || typeof aml !== "string" || !aml.includes("<")) return out; const dims = []; const dimRe = /]*?)\/?>/g; let dm; while (dm = dimRe.exec(aml)) { const a3 = _attrs(dm[1]); const id = a3.id; if (!id) continue; dims.push({ id, labels: (a3.labels ?? "").trim().split(/\s+/).filter(Boolean), // 量值带单位(schema 规范:8.4m / 3m),parseFloat 兼容带/不带单位后缀 spacings: (a3.spacings ?? "").trim().split(/\s+/).filter(Boolean).map((v2) => parseFloat(v2)) }); } if (dims.length > 0) out.dote = { dote_dims: dims }; const levelRe = /]*?)>([\s\S]*?)<\/level>/g; let lm; while (lm = levelRe.exec(aml)) { const la = _attrs(lm[1]); const lid = la.id ?? ""; out.levels.push({ id: lid, elevation: la.elevation !== void 0 ? parseFloat(la.elevation) : void 0, height: la.height !== void 0 ? parseFloat(la.height) : void 0 }); const body = lm[2]; const spaceRe = /]*?)\/?>/g; let sm; while (sm = spaceRe.exec(body)) { const sa = _attrs(sm[1]); const bounds = (sa["dote-bounds"] ?? "").trim().split(/\s+/).filter(Boolean); out.rooms.push({ id: sa.id ?? "", name: sa.name ?? sa.id ?? "", type: sa.type, dote_bounds: bounds.length === 4 ? bounds : void 0, level: lid || void 0, area: sa.area !== void 0 && sa.area !== "" ? parseFloat(sa.area) : void 0 }); } } const naText = /]*\bname="NORTH_ANGLE"[^>]*>([\s\S]*?)<\/param>/.exec(aml); const naAttr = /]*\bname="NORTH_ANGLE"[^>]*\bvalue="([^"]*)"/.exec(aml) ?? /]*\bvalue="([^"]*)"[^>]*\bname="NORTH_ANGLE"/.exec(aml); const naRaw = naText?.[1] ?? naAttr?.[1]; if (naRaw !== void 0) { const v2 = Number(naRaw.trim()); if (Number.isFinite(v2)) out.north_angle = v2; } return out; } function deriveFromAml(aml, subModule) { const lite = parseAmlLite(aml); const z2 = amlZonesForDoteVerify(lite, subModule); return { dote: lite.dote, rooms: lite.rooms, levels: lite.levels, north_angle: lite.north_angle, floor_height: lite.levels.find((l13) => l13.height !== void 0)?.height, zones: z2?.zones, dote_bounds: lite.dote }; } function amlZonesForDoteVerify(lite, subModule) { const dims = lite.dote?.dote_dims ?? []; const dx = dims.find((d2) => d2.id === "X"); const dy = dims.find((d2) => d2.id === "Y"); if (!dx || !dy) return null; let smx = 1.2, smy = 1.2; if (typeof subModule === "object" && subModule !== null && !Array.isArray(subModule)) { smx = Number(subModule.x ?? 1.2); smy = Number(subModule.y ?? smx); } else if (Array.isArray(subModule)) { smx = Number(subModule[0]); smy = subModule.length > 1 ? Number(subModule[1]) : smx; } else if (subModule !== void 0) { smx = smy = Number(subModule); } if (!(smx > 0) || !(smy > 0)) return null; const zones = []; for (const r4 of lite.rooms) { const gb = r4.dote_bounds; if (!gb) continue; const [y1, y2, x1, x22] = gb; const py1 = amlLabelPosition(y1, dy.spacings, dy.labels); const py2 = amlLabelPosition(y2, dy.spacings, dy.labels); const px1 = amlLabelPosition(x1, dx.spacings, dx.labels); const px2 = amlLabelPosition(x22, dx.spacings, dx.labels); if (py1 === null || py2 === null || px1 === null || px2 === null) continue; const yMin = Math.min(py1, py2), yMax = Math.max(py1, py2); const xMin = Math.min(px1, px2), xMax = Math.max(px1, px2); const rect = { y0: Math.round(yMin / smy), y1: Math.max(Math.round(yMin / smy), Math.round(yMax / smy) - 1), x0: Math.round(xMin / smx), x1: Math.max(Math.round(xMin / smx), Math.round(xMax / smx) - 1) }; const actualArea = (yMax - yMin) * (xMax - xMin); zones.push({ id: r4.id, name: r4.name, planned_area: r4.area ?? Math.round(actualArea * 10) / 10, occupied: [rect] }); } return zones.length > 0 ? { zones, smx, smy } : null; } // skills/design-arch/scripts/room-type.js function detectRoomType(room) { const name24 = String(room.name || room.display_name || ""); const prog = String(room.type || room.program_type || "").toLowerCase(); if (/主卧|主卧室/.test(name24)) return "master_bedroom"; if (/次卧|卧室|客房|儿童房|老人房/.test(name24)) return "bedroom"; if (/客餐厅|起居餐厅|客厅餐厅/.test(name24)) return "living_dining"; if (/客厅|起居室/.test(name24)) return "living"; if (/餐厅/.test(name24)) return "dining"; if (/厨房|厨/.test(name24)) return "kitchen"; if (/卫生间|厕所|洗手|浴室|卫$/.test(name24)) return "bathroom"; if (/书房/.test(name24)) return "study"; if (/电梯井|楼梯井|竖井|管井|风井|电井|水井|井道|烟道/.test(name24)) return "shaft"; if (/前室/.test(name24)) return "vestibule"; if (/电梯厅|候梯厅/.test(name24)) return "elevator_lobby"; if (/玄关|门厅/.test(name24)) return "foyer"; if (/走廊|过道|走道|交通|楼梯/.test(name24)) return "circulation"; if (/阳台|露台|花池/.test(name24)) return "balcony"; if (/新风机房|空调机房|冷热源|水泵房|设备机房|风机房/.test(name24)) return "mechanical"; if (/储藏|储物|库房|设备|机房/.test(name24)) return "storage"; if (/会议/.test(name24)) return "meeting"; if (/办公/.test(name24)) return "office"; if (/前台|接待/.test(name24)) return "reception"; if (/天井|庭院|中庭|void|室外/.test(name24)) return "void"; if (prog === "shaft") return "shaft"; if (prog === "vestibule") return "vestibule"; if (prog === "elevator_lobby") return "elevator_lobby"; if (prog === "bedroom") return "bedroom"; if (prog === "living") return "living"; if (prog === "living_dining") return "living_dining"; if (prog === "kitchen") return "kitchen"; if (prog === "restroom") return "bathroom"; if (prog === "circulation") return "circulation"; if (prog === "foyer") return "foyer"; if (prog === "office") return "office"; if (prog === "meeting") return "meeting"; if (prog === "storage") return "storage"; if (prog === "mechanical") return "mechanical"; if (prog === "balcony") return "balcony"; if (prog === "reception") return "reception"; if (prog === "void") return "void"; return prog || "unknown"; } // skills/design-arch/scripts/layout-eval.js function layoutEval(params) { const building = params.building; if (!building) return { error: "\u672A\u83B7\u5F97 building \u6570\u636E\u5BF9\u8C61\uFF08\u8BF7\u5148\u8C03 apply_design \u7F16\u8BD1\u2014\u2014\u7ED3\u679C\u4F1A\u81EA\u52A8\u6CE8\u5165\uFF0C\u6216\u663E\u5F0F\u4F20\u5165 building \u5B57\u6BB5\uFF09" }; const rooms = building.rooms || []; const apertures = building.apertures || []; if (!rooms.length) return { error: "building.rooms \u4E3A\u7A7A\uFF0C\u65E0\u6CD5\u8BC4\u4F30" }; const bldgType = params.building_type || building.type || "residential"; const isResidential = bldgType === "residential" || bldgType === "apartment" || bldgType === "house"; const northAngle = params.north_angle ?? (Number(building.north_angle) || deriveFromAml(params.aml).north_angle || 0); const partyWalls = (params.party_walls || []).filter((d2) => COMPASS_DIRS.includes(d2)); const allowedDirsText = COMPASS_DIRS.filter((d2) => !partyWalls.includes(d2)).map((d2) => DIR_CN[d2]).join("\u3001"); const allowedHint = partyWalls.length > 0 ? `\u5141\u8BB8\u5F00\u7A97\u671D\u5411\uFF1A${allowedDirsText}` : ""; const criteriaTable = { ...DEFAULT_CRITERIA, ...params.criteria || {} }; const apsByRoom = /* @__PURE__ */ new Map(); for (const ap of apertures) { for (const rid of ap.rooms || []) { if (!apsByRoom.has(rid)) apsByRoom.set(rid, []); apsByRoom.get(rid).push(ap); } } const roomScores = []; const allFixes = []; const warnings = []; const unscoredRooms = []; let totalArea = 0; let circulationArea = 0; for (const room of rooms) { const rtype = detectRoomType(room); const crit = criteriaTable[rtype]; const m3 = computeMetrics(room, apsByRoom.get(room.identifier) || [], northAngle, partyWalls); if (m3._degenerate) warnings.push(`${room.display_name} \u51E0\u4F55\u9000\u5316\uFF08region \u9876\u70B9\u4E0D\u8DB3 3 \u4E2A\uFF09\uFF0C\u8BC4\u5206\u4E0D\u53EF\u9760`); totalArea += m3.area; if (rtype === "circulation") { circulationArea += m3.area; continue; } if (!crit) { unscoredRooms.push(`${room.display_name ?? room.identifier}\uFF08${rtype}\uFF09`); continue; } const failures = []; const fixes = []; let score = 100; if (crit.area && m3.area > 0) { if (m3.area < crit.area[0]) { score -= 20; failures.push("area_low"); fixes.push({ lever: "wall", code: "area_low", action: `${room.display_name} \u9762\u79EF ${m3.area}\u33A1 < \u6807\u51C6 ${crit.area[0]}\u33A1\uFF1A\u5411\u76F8\u90BB\u7A7A\u95F4\u501F\u8C03\uFF08\u79FB\u52A8\u5171\u7528\u5899\u4F53\uFF09\uFF0C\u6216\u6269\u5927\u5916\u8F6E\u5ED3` }); } else if (m3.area > crit.area[1]) { score -= 10; failures.push("area_high"); fixes.push({ lever: "wall", code: "area_high", action: `${room.display_name} \u9762\u79EF ${m3.area}\u33A1 \u8D85\u8FC7 ${crit.area[1]}\u33A1\uFF1A\u53EF\u62C6\u5206\u6216\u7F29\u8FDB\u6DF1\uFF0C\u628A\u9762\u79EF\u8BA9\u7ED9\u4E0D\u8DB3\u7684\u623F\u95F4` }); } } if (crit.minWidth && m3.minWidth > 0 && m3.minWidth < crit.minWidth) { score -= 25; failures.push("width_low"); fixes.push({ lever: "grid", code: "width_low", action: `${room.display_name} \u9762\u5BBD ${m3.minWidth}m < \u6700\u5C0F ${crit.minWidth}m\uFF1A\u4F18\u5148\u8C03\u6574\u7F51\u683C\u8DE8\u8DDD\uFF08dote-calc module \u6570\u7EC4\uFF09\uFF1B\u5355\u623F\u95F4\u95EE\u9898\u53EF\u6539\u7528\u5C40\u90E8\u5899\u4F53\u504F\u79FB` }); } if (crit.maxRatio && m3.ratio > crit.maxRatio) { score -= 15; failures.push("ratio_high"); fixes.push({ lever: "wall", code: "ratio_high", action: `${room.display_name} \u957F\u5BBD\u6BD4 ${m3.ratio}:1 \u8D85\u8FC7 ${crit.maxRatio}:1\uFF1A\u6CBF\u957F\u8FB9\u62C6\u5206\u7A7A\u95F4\uFF0C\u6216\u65CB\u8F6C 90\xB0 \u91CD\u6392` }); } if (crit.needsWindow && m3.validWindowCount === 0) { score -= 25; failures.push("no_window"); fixes.push({ lever: "envelope", code: "no_window", action: `${room.display_name} \u65E0\u6709\u6548\u5916\u7A97\uFF1A\u8BE5\u623F\u95F4\u4E0D\u5728\u8F6E\u5ED3\u8FB9\u7F18${m3.windowCount > 0 ? "\uFF08\u73B0\u6709\u7A97\u5747\u5728\u5206\u6237\u5899\u4E0A\uFF0C\u4E0D\u8BA1\u5165\uFF09" : ""}\u3002\u5C06\u5176\u4E0E\u8FB9\u7F18\u623F\u95F4\u4EA4\u6362\u4F4D\u7F6E\uFF08swap\uFF09\uFF0C\u6216\u8C03\u6574\u8F6E\u5ED3\u4F7F\u5176\u51FA\u6311${allowedHint ? `\u3002${allowedHint}` : ""}` }); } else if (crit.needsWindow && m3.validWindowCount > 0 && m3.wwr < (crit.minWWR ?? 0.1)) { score -= 8; failures.push("wwr_low"); fixes.push({ lever: "window", code: "wwr_low", action: `${room.display_name} \u7A97\u5730\u6BD4 ${(m3.wwr * 100).toFixed(1)}% < ${((crit.minWWR ?? 0.1) * 100).toFixed(0)}%\uFF1A\u52A0\u5927\u7A97\u5BBD\u6216\u589E\u52A0\u5F00\u7A97${allowedHint ? `\uFF08${allowedHint}\uFF09` : ""}` }); } if (crit.preferSouth && m3.validWindowCount > 0 && !m3.hasSouthWindow) { score -= 15; failures.push("not_south"); fixes.push({ lever: "swap", code: "not_south", action: `${room.display_name} \u6709\u7A97\u4F46\u65E0\u5357\u5411\u7A97\uFF1A\u4E0E\u5357\u5411\u623F\u95F4\u4EA4\u6362\u4F4D\u7F6E\uFF08swap\uFF09\uFF0C\u6216\u8C03\u6574\u8F6E\u5ED3/\u5E03\u5C40\u4F7F\u5176\u83B7\u5F97\u5357\u5411\u91C7\u5149\u9762` }); } if (m3.partyWallWindowDirs.length > 0) { score -= 15; failures.push("window_on_party_wall"); const dirsText = m3.partyWallWindowDirs.map((d2) => DIR_CN[d2] || d2).join("\u3001"); fixes.push({ lever: "window", code: "window_on_party_wall", action: `${room.display_name} \u5728\u5206\u6237\u5899\uFF08${dirsText}\u5411\uFF09\u5F00\u4E86\u7A97\uFF1A\u5206\u6237\u5899\u4E0A\u7684\u7A97\u65E0\u6548\uFF08\u65E0\u91C7\u5149\u6743\uFF09\uFF0C\u5E94\u79FB\u9664\u6216\u6539\u5230\u5141\u8BB8\u671D\u5411\uFF08${allowedDirsText}\uFF09` }); } if (m3.interiorWindowCount > 0) { score -= 15; failures.push("window_on_interior_wall"); const dirsText = m3.interiorWallWindowDirs.map((d2) => DIR_CN[d2] || d2).join("\u3001"); const neighborText = m3.interiorWindowNeighbors.length > 0 ? `\uFF08\u4E0E ${m3.interiorWindowNeighbors.join("\u3001")} \u76F8\u90BB\uFF09` : ""; fixes.push({ lever: "wall", code: "window_on_interior_wall", action: `${room.display_name} \u7684\u7A97\u5F00\u5728\u5185\u5899\u4E0A${dirsText ? `\uFF08${dirsText}\u5411\uFF09` : ""}${neighborText}\uFF0C\u65E0\u91C7\u5149\u6743\uFF0C\u5E94\u79FB\u9664\u6216\u6539\u5230\u5916\u5899` }); } const entry = { id: room.identifier, name: room.display_name, type: rtype, score: Math.max(0, score), metrics: m3, failures, fixes }; roomScores.push(entry); allFixes.push(...fixes.map((f2) => ({ ...f2, room: room.display_name, room_id: room.identifier }))); } const graph = building.spatialGraph; if (graph?.edges) { const HUB_TYPES = new Set(isResidential ? ["circulation", "living", "living_dining", "foyer"] : ["circulation"]); const hubIds = new Set(rooms.filter((r4) => HUB_TYPES.has(detectRoomType(r4))).map((r4) => r4.identifier)); const notConnected2 = []; const isolatedBaths = []; for (const room of rooms) { const rtype = detectRoomType(room); if (HUB_TYPES.has(rtype)) continue; const edges = graph.edges[room.identifier] ?? []; const adjIds = new Set(edges.filter((e5) => e5.type === "adjacent").map((e5) => e5.to)); if (![...adjIds].some((id) => hubIds.has(id))) { if (!(rtype === "bathroom" && [...adjIds].some((id) => detectRoomType(rooms.find((r4) => r4.identifier === id) ?? {}) === "master_bedroom"))) { notConnected2.push(room.display_name || room.identifier); } } if (rtype === "bathroom") { const ok = [...adjIds].some((id) => { const t4 = detectRoomType(rooms.find((r4) => r4.identifier === id) ?? {}); return HUB_TYPES.has(t4) || t4 === "master_bedroom"; }); if (!ok) isolatedBaths.push(room.display_name || room.identifier); } } if (notConnected2.length > 0) { const msg = `\u4EE5\u4E0B\u623F\u95F4\u672A\u4E0E\u8D70\u5ECA/\u8D77\u5C45\u67A2\u7EBD\u8FDE\u901A\uFF1A${notConnected2.join("\u3001")}\u3002\u9700\u901A\u8FC7 edit_source \u8C03\u6574 dote-bounds \u4F7F\u5176\u90BB\u63A5\u4EA4\u901A\u7A7A\u95F4\u6216\u5BA2\u9910\u5385\uFF0C\u6216\u8865\u5145\u8D70\u5ECA`; allFixes.push({ lever: "envelope", code: "disconnected", action: msg }); warnings.push(msg); } if (isolatedBaths.length > 0) { const msg = `\u4EE5\u4E0B\u536B\u751F\u95F4\u65E2\u4E0D\u901A\u8D70\u5ECA/\u8D77\u5C45\u533A\u4E5F\u4E0D\u90BB\u4E3B\u5367\uFF0C\u4F7F\u7528\u9700\u7A7F\u8D8A\u5176\u4ED6\u5367\u5BA4\uFF1A${isolatedBaths.join("\u3001")}\u3002\u5EFA\u8BAE\u79FB\u81F3\u5E72\u6E7F\u5206\u533A\u6838\u5FC3\uFF08\u4E0E\u53A8\u623F/\u67A2\u7EBD\u76F8\u90BB\uFF09`; allFixes.push({ lever: "swap", code: "wet_zone_isolated", action: msg }); warnings.push(msg); } } const circUpper = isResidential ? 25 : 20; const circLower = isResidential ? 5 : 4; const circulationRatio = totalArea > 0 ? Math.round(circulationArea / totalArea * 1e3) / 10 : 0; if (circulationRatio > circUpper) { allFixes.push({ lever: "envelope", code: "circulation_high", action: `\u4EA4\u901A\u9762\u79EF\u5360\u6BD4 ${circulationRatio}% > ${circUpper}%\uFF08${isResidential ? "\u4F4F\u5B85" : "\u975E\u4F4F\u5B85"}\u4E0A\u9650\uFF09\u3002\u8F6E\u5ED3\u8FC7\u5927\u6216\u6D41\u7EBF\u4F4E\u6548\uFF1A\u538B\u7F29\u8F6E\u5ED3\u3001\u5408\u5E76\u8D70\u5ECA\u4E0E\u5BA2\u5385\u3001\u6216\u6539\u7528\u56F4\u5408\u5F0F\u5E03\u5C40` }); } else if (circulationRatio < circLower && circulationRatio > 0) { allFixes.push({ lever: "wall", code: "circulation_low", action: `\u4EA4\u901A\u9762\u79EF\u5360\u6BD4\u4EC5 ${circulationRatio}% < ${circLower}%\u3002\u53EF\u80FD\u7A7F\u5957\uFF08\u5367\u5BA4\u7A7F\u5367\u5BA4\uFF09\uFF0C\u68C0\u67E5\u79C1\u5BC6\u6027` }); } if (isResidential) { const bathArea = rooms.filter((r4) => detectRoomType(r4) === "bathroom").reduce((s2, r4) => s2 + (r4.area ?? 0), 0); const bathRatio = totalArea > 0 ? Math.round(bathArea / totalArea * 1e3) / 10 : 0; if (bathRatio > 15) { allFixes.push({ lever: "wall", code: "bathroom_high", action: `\u536B\u751F\u95F4\u9762\u79EF\u5360\u6BD4 ${bathRatio}% > 15%\uFF08\u4F4F\u5B85\u4E0A\u9650\uFF09\u3002\u536B\u751F\u95F4\u603B\u9762\u79EF\u8FC7\u5927\uFF0C\u538B\u7F29\u975E\u5FC5\u8981\u536B\u751F\u95F4\u9762\u79EF` }); } } const foyerRooms = rooms.filter((r4) => detectRoomType(r4) === "foyer"); if (foyerRooms.length > 0 && rooms.length > 1) { const metricsByRoom = new Map(rooms.map((r4) => [r4, computeMetrics(r4, [], 0)])); const floorGroups = /* @__PURE__ */ new Map(); for (const r4 of rooms) { const key = r4.parent ?? "__default__"; if (!floorGroups.has(key)) floorGroups.set(key, []); floorGroups.get(key).push(r4); } for (const fRoom of foyerRooms) { const fm = metricsByRoom.get(fRoom); if (!fm || fm._degenerate) continue; const siblings = (floorGroups.get(fRoom.parent ?? "__default__") ?? []).map((r4) => metricsByRoom.get(r4)).filter((b5) => b5 && !b5._degenerate); if (siblings.length === 0) continue; const bMinX = Math.min(...siblings.map((b5) => b5.minX)); const bMaxX = Math.max(...siblings.map((b5) => b5.maxX)); const bMinY = Math.min(...siblings.map((b5) => b5.minY)); const bMaxY = Math.max(...siblings.map((b5) => b5.maxY)); const onEdge = fm.minX <= bMinX + 0.1 || fm.maxX >= bMaxX - 0.1 || fm.minY <= bMinY + 0.1 || fm.maxY >= bMaxY - 0.1; if (!onEdge) { allFixes.push({ lever: "swap", code: "foyer_center", action: `"${fRoom.display_name}" \u7384\u5173\u4F4D\u4E8E\u5EFA\u7B51\u5185\u6838\u533A\uFF0C\u4E0D\u5728\u5165\u53E3\u8FB9\u7F18\u3002\u5E94\u5C06\u5176\u4E0E\u8FB9\u7F18\u623F\u95F4\u4EA4\u6362\u4F4D\u7F6E\uFF0C\u6216\u8C03\u6574 dote-bounds \u4F7F\u5176\u8D34\u8FB9`, room: fRoom.display_name }); } } } const kitchens = rooms.filter((r4) => detectRoomType(r4) === "kitchen"); const baths = rooms.filter((r4) => detectRoomType(r4) === "bathroom"); for (const k of kitchens) { for (const b5 of baths) { if (k.parent && b5.parent && k.parent !== b5.parent) continue; const d2 = centroidDistance(k.point, b5.point); if (!isFinite(d2)) continue; if (d2 > 6) { allFixes.push({ lever: "swap", code: "plumbing_far", action: `\u53A8\u623F\u4E0E\u536B\u751F\u95F4\u76F8\u8DDD ${d2.toFixed(1)}m > 6m\uFF1A\u7BA1\u7EBF\u8FC7\u957F\u3002\u4EA4\u6362\u623F\u95F4\u4F4D\u7F6E\u4F7F\u53A8\u536B\u76F8\u90BB\uFF08\u5171\u7528\u7BA1\u7EBF\u5899\uFF09`, room: `${k.display_name}/${b5.display_name}` }); } } } const LEVER_ORDER = { grid: 0, envelope: 1, wall: 2, window: 3, swap: 4 }; const topFixes = allFixes.sort((a3, b5) => (LEVER_ORDER[a3.lever] ?? 9) - (LEVER_ORDER[b5.lever] ?? 9)).filter((f2, i4, arr) => arr.findIndex((x4) => x4.action === f2.action) === i4).slice(0, 8); const scored = roomScores.filter((r4) => r4.score !== void 0); const aggregate = scored.length ? Math.round(scored.reduce((s2, r4) => s2 + r4.score, 0) / scored.length) : 0; const failedRooms = roomScores.filter((r4) => r4.failures.length > 0); if (unscoredRooms.length > 0) { warnings.push(`\u4EE5\u4E0B\u623F\u95F4\u7C7B\u578B\u65E0\u8BC4\u5206\u6807\u51C6\uFF0C\u672A\u8BA1\u5206\uFF08aggregate \u4E0D\u542B\u5B83\u4EEC\uFF09\uFF1A${unscoredRooms.join("\u3001")}`); } const summary = aggregate >= 85 ? `\u2705 \u5E03\u5C40\u54C1\u8D28\u826F\u597D\uFF08${aggregate} \u5206\uFF09\uFF0C${scored.length} \u4E2A\u623F\u95F4\u8FBE\u6807` : aggregate >= 70 ? `\u26A0\uFE0F \u5E03\u5C40\u54C1\u8D28\u4E2D\u7B49\uFF08${aggregate} \u5206\uFF09\uFF0C${failedRooms.length}/${scored.length} \u4E2A\u623F\u95F4\u6709\u95EE\u9898\uFF1A${failedRooms.map((r4) => r4.name).join("\u3001")}\u3002\u6309 top_fixes \u4F18\u5316` : `\u274C \u5E03\u5C40\u54C1\u8D28\u8F83\u5DEE\uFF08${aggregate} \u5206\uFF09\u3002\u5EFA\u8BAE\u6309\u6760\u6746\u4F18\u5148\u7EA7\u8C03\u6574\uFF1A\u5148\u7F51\u683C/\u8F6E\u5ED3\uFF0C\u518D\u5899\u4F53\u504F\u79FB\uFF0C\u6700\u540E\u5F00\u7A97`; return { aggregate_score: aggregate, circulation_ratio_pct: circulationRatio, north_angle: northAngle, room_scores: roomScores.sort((a3, b5) => a3.score - b5.score), top_fixes: topFixes, total_rooms: scored.length, failed_rooms: failedRooms.length, ...unscoredRooms.length > 0 ? { unscored_rooms: unscoredRooms } : {}, summary, ...warnings.length > 0 ? { warnings } : {} }; } var DEFAULT_CRITERIA = { // ── 居住空间 ── master_bedroom: { area: [12, 22], minWidth: 3.3, maxRatio: 1.5, needsWindow: true, preferSouth: true, minWWR: 0.1 }, bedroom: { area: [8, 16], minWidth: 3, maxRatio: 1.5, needsWindow: true, preferSouth: true, minWWR: 0.1 }, living: { area: [16, 35], minWidth: 3.6, maxRatio: 2, needsWindow: true, preferSouth: true, minWWR: 0.12 }, dining: { area: [6, 14], minWidth: 2.4, maxRatio: 2, needsWindow: true, minWWR: 0.08 }, living_dining: { area: [22, 50], minWidth: 4.2, maxRatio: 2, needsWindow: true, preferSouth: true, minWWR: 0.1 }, kitchen: { area: [4.5, 10], minWidth: 1.8, maxRatio: 2, needsWindow: true, minWWR: 0.08 }, bathroom: { area: [3, 7], minWidth: 1.5, maxRatio: 2.5, needsWindow: false }, balcony: { area: [3, 10], minWidth: 1.2, maxRatio: 3, needsWindow: false }, study: { area: [6, 12], minWidth: 2.4, maxRatio: 1.8, needsWindow: true, minWWR: 0.08 }, // ── 商业办公 ── office: { area: [10, 80], minWidth: 3.6, maxRatio: 2, needsWindow: true, preferSouth: true, minWWR: 0.12 }, meeting: { area: [15, 100], minWidth: 3.6, maxRatio: 1.5, needsWindow: true, minWWR: 0.08 }, reception: { area: [8, 40], minWidth: 3, maxRatio: 2, needsWindow: true, minWWR: 0.1 }, corridor: { area: [2, 20], minWidth: 1.2, maxRatio: 5, needsWindow: false }, // 走廊可无窗 foyer: { area: [2, 4], minWidth: 1.2, maxRatio: 2, needsWindow: false }, // ── 核心筒(办公/公共建筑)── vestibule: { area: [6, 16], minWidth: 2.4, maxRatio: 2, needsWindow: false }, // 防火前室 ≥6㎡/合用≥10㎡,短边≥2.4m(GB 50016 6.4.3/7.3.5) elevator_lobby: { area: [8, 40], minWidth: 2.4, maxRatio: 2.5, needsWindow: false }, // 候梯厅净深≥2.4m(GB 50352) shaft: { area: [0.4, 10], minWidth: 0.5, maxRatio: 3, needsWindow: false }, // 管井/风井/电井/给排水竖井 // ── 辅助空间 ── storage: { area: [2, 10], minWidth: 1, maxRatio: 3, needsWindow: false }, mechanical: { area: [4, 40], minWidth: 1.5, maxRatio: 2.5, needsWindow: false } // 新风机房等,服务 1000㎡ 级约 10-15㎡ }; var COMPASS_DIRS = ["north", "east", "south", "west"]; var DIR_CN = { north: "\u5317", east: "\u4E1C", south: "\u5357", west: "\u897F" }; var DIR_ANGLE = { north: 0, east: 90, south: 180, west: 270 }; function windowOrientation(ap, cx, cy, northAngle) { const pts = ap.plan_crv || []; if (!pts.length) return null; const wx = pts.reduce((s2, p2) => s2 + p2[0], 0) / pts.length; const wy = pts.reduce((s2, p2) => s2 + p2[1], 0) / pts.length; const dx = wx - cx, dy = wy - cy; if (Math.hypot(dx, dy) < 1e-6) return null; let best = null; let bestDot = -Infinity; for (const dir of COMPASS_DIRS) { const a3 = (DIR_ANGLE[dir] + northAngle) * Math.PI / 180; const dot = dx * Math.sin(a3) + dy * Math.cos(a3); if (dot > bestDot) { bestDot = dot; best = dir; } } return best; } function computeMetrics(room, roomAps, northAngle, partyWalls = []) { const rawRegion = Array.isArray(room.region) ? room.region : []; const poly = rawRegion.map((p2) => [p2[0], p2[1]]); const degenerate = poly.length < 3; const area = room.area ?? (degenerate ? 0 : polygonArea(poly)); let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity; for (const [x4, y2] of poly) { if (x4 < minX) minX = x4; if (x4 > maxX) maxX = x4; if (y2 < minY) minY = y2; if (y2 > maxY) maxY = y2; } const w3 = poly.length >= 2 ? +(maxX - minX).toFixed(2) : 0; const d2 = poly.length >= 2 ? +(maxY - minY).toFixed(2) : 0; const ratio = w3 > 0 && d2 > 0 ? +(Math.max(w3, d2) / Math.min(w3, d2)).toFixed(2) : 0; const minWidth = +Math.min(w3, d2).toFixed(2); const windows = roomAps.filter((a3) => a3.geometry_type === "window"); const cx = room.point?.[0] ?? (minX < Infinity ? (minX + maxX) / 2 : 0); const cy = room.point?.[1] ?? (minY < Infinity ? (minY + maxY) / 2 : 0); const party = new Set(partyWalls); const winDirs = windows.map((a3) => windowOrientation(a3, cx, cy, northAngle)); const isInterior = (i4) => windows[i4].hosting?.on_exterior_wall === false; const validIdx = windows.map((_2, i4) => i4).filter((i4) => windows[i4].hosting?.on_exterior_wall === true || windows[i4].hosting?.on_exterior_wall === void 0 && (!winDirs[i4] || !party.has(winDirs[i4]))); const validWindows = validIdx.map((i4) => windows[i4]); const partyWallWindowDirs = [...new Set(winDirs.filter((d3, i4) => !!d3 && windows[i4].hosting?.on_exterior_wall === void 0 && party.has(d3)))]; const interiorIdx = windows.map((_2, i4) => i4).filter(isInterior); const interiorWallWindowDirs = [...new Set(interiorIdx.map((i4) => winDirs[i4]).filter((d3) => !!d3))]; const interiorWindowNeighbors = [...new Set(interiorIdx.flatMap((i4) => windows[i4].hosting?.neighbor_spaces || []))]; const winArea = validWindows.reduce((s2, a3) => s2 + (a3.area || a3.width * a3.height || 0), 0); const wwr = area > 0 ? +(winArea / area).toFixed(3) : 0; const hasSouthWindow = validIdx.some((i4) => winDirs[i4] === "south"); return { area: +Number(area).toFixed(1), width: w3, depth: d2, minWidth, ratio, minX: minX < Infinity ? minX : 0, maxX: maxX > -Infinity ? maxX : 0, minY: minY < Infinity ? minY : 0, maxY: maxY > -Infinity ? maxY : 0, windowCount: windows.length, validWindowCount: validWindows.length, partyWallWindowDirs, /** GSA 真值判定的内墙窗数量与朝向(hosting.on_exterior_wall === false 的窗) */ interiorWindowCount: interiorIdx.length, interiorWallWindowDirs, /** 内墙窗的邻居空间 id(hosting.neighbor_spaces 汇总,用于修复建议文案) */ interiorWindowNeighbors, wwr, hasSouthWindow, _degenerate: degenerate }; } function polygonArea(poly) { let a3 = 0; for (let i4 = 0; i4 < poly.length; i4++) { const [x1, y1] = poly[i4]; const [x22, y2] = poly[(i4 + 1) % poly.length]; a3 += x1 * y2 - x22 * y1; } return Math.abs(a3 / 2); } function centroidDistance(p1, p2) { if (!p1 || !p2 || p1.length < 2 || p2.length < 2) return Infinity; if (!isFinite(p1[0]) || !isFinite(p1[1]) || !isFinite(p2[0]) || !isFinite(p2[1])) return Infinity; return Math.hypot(p1[0] - p2[0], p1[1] - p2[1]); } // skills/design-arch/scripts/dote-room-check.js function spanBetween(lbl1, lbl2, spacings, labels) { const p1 = amlLabelPosition(lbl1, spacings, labels); const p2 = amlLabelPosition(lbl2, spacings, labels); if (p1 === null || p2 === null) return null; return Math.abs(p2 - p1); } function doteRoomCheck(params) { const derived = deriveFromAml(params.aml); const rawRooms = params.rooms ?? derived.rooms; const dote = params.dote ?? derived.dote; const buildingType = params.building_type ?? "residential"; if (!rawRooms || rawRooms.length === 0) { return { error: "\u7F3A\u5C11 rooms \u6570\u636E\uFF08\u53EF\u7531 aml \u6D3E\u751F\uFF1B\u8BF7\u4F20 aml \u6216\u5148\u7F16\u5199 AML\uFF09" }; } if (!dote) { return { error: "\u7F3A\u5C11 dote \u8F74\u7F51\u5B9A\u4E49\uFF08\u53EF\u7531 aml \u6D3E\u751F\uFF1BAML \u9700\u542B dote-system/dote-dim\uFF09" }; } const dims = dote.dote_dims ?? []; const xDim = dims.find((d2) => d2.id === "X"); const yDim = dims.find((d2) => d2.id === "Y"); if (!xDim || !yDim) { return { error: "dote_dims \u7F3A\u5C11 X \u6216 Y \u7EF4\u5EA6\u5B9A\u4E49" }; } const xSp = xDim.spacings ?? []; const ySp = yDim.spacings ?? []; const xLabels = xDim.labels ?? []; const yLabels = yDim.labels ?? []; const criteriaTable = { ...DEFAULT_CRITERIA, ...params.criteria || {} }; const roomChecks = []; const violations = []; for (const room of rawRooms) { const gb = room.dote_bounds; if (!gb || !Array.isArray(gb) || gb.length !== 4) { roomChecks.push({ id: room.id || room.name || "?", name: room.display_name || room.name || "?", type: detectRoomType(room), error: "\u7F3A\u5C11 dote_bounds\uFF08\u9700\u4E3A [y1,y2,x1,x2] \u6570\u7EC4\uFF09" }); continue; } const [y1, y2, x1, x22] = gb; const ySpan = spanBetween(y1, y2, ySp, yLabels); const xSpan = spanBetween(x1, x22, xSp, xLabels); if (ySpan === null || xSpan === null || ySpan <= 0 || xSpan <= 0) { roomChecks.push({ id: room.id || room.name || "?", name: room.display_name || room.name || "?", type: detectRoomType(room), dote_bounds: gb, error: `dote_bounds \u8BA1\u7B97\u9762\u79EF\u65E0\u6548\uFF08ySpan=${ySpan}, xSpan=${xSpan}\uFF0C\u6807\u7B7E\u53EF\u80FD\u4E0D\u5728 dote_dims.labels \u4E2D\uFF09` }); continue; } const area = Math.round(ySpan * xSpan * 10) / 10; const minWidth = Math.min(ySpan, xSpan); const maxDim = Math.max(ySpan, xSpan); const ratio = minWidth > 0 ? +(maxDim / minWidth).toFixed(2) : 0; const rtype = detectRoomType(room); const crit = criteriaTable[rtype]; const name24 = room.display_name || room.name || room.id || "?"; if (!crit) { roomChecks.push({ id: room.id || name24, name: name24, type: rtype, area, width: xSpan, depth: ySpan, minWidth, ratio, note: "\u65E0\u5BF9\u5E94\u7528\u9014\u6807\u51C6\uFF0C\u8DF3\u8FC7\u6821\u9A8C" }); continue; } const failures = []; const fixes = []; if (crit.area) { if (area < crit.area[0]) { failures.push("area_low"); fixes.push({ lever: "wall", code: "area_low", action: `${name24} \u9762\u79EF ${area}\u33A1 < \u6807\u51C6\u4E0B\u9650 ${crit.area[0]}\u33A1\uFF1A\u6269 dote-bounds \u6216\u8C03\u6574\u7F51\u683C` }); } else if (area > crit.area[1]) { failures.push("area_high"); fixes.push({ lever: "wall", code: "area_high", action: `${name24} \u9762\u79EF ${area}\u33A1 > \u6807\u51C6\u4E0A\u9650 ${crit.area[1]}\u33A1\uFF1A\u7F29 dote-bounds \u6216\u62C6\u5206\u7A7A\u95F4` }); } } if (crit.minWidth && minWidth < crit.minWidth) { failures.push("width_low"); fixes.push({ lever: "grid", code: "width_low", action: `${name24} \u9762\u5BBD ${minWidth}m < \u6700\u5C0F ${crit.minWidth}m\uFF1A\u8C03\u7F51\u683C\u8DE8\u8DDD\u6216\u6539 dote-bounds` }); } if (crit.maxRatio && ratio > crit.maxRatio) { failures.push("ratio_high"); fixes.push({ lever: "wall", code: "ratio_high", action: `${name24} \u957F\u5BBD\u6BD4 ${ratio}:1 > \u4E0A\u9650 ${crit.maxRatio}:1\uFF1A\u8C03\u6574\u5207\u5206\u65B9\u5411` }); } roomChecks.push({ id: room.id || name24, name: name24, type: rtype, area, width: xSpan, depth: ySpan, minWidth, ratio, criteria: { area: crit.area, minWidth: crit.minWidth, maxRatio: crit.maxRatio }, failures, fixes, pass: failures.length === 0 }); violations.push(...fixes); } const failed = roomChecks.filter((r4) => r4.failures && r4.failures.length > 0); const passed = roomChecks.filter((r4) => r4.pass !== void 0 && r4.pass); const skipped = roomChecks.filter((r4) => r4.note); const errored = roomChecks.filter((r4) => r4.error); const LEVER_ORDER = { grid: 0, wall: 1 }; const sortedViolations = violations.sort((a3, b5) => (LEVER_ORDER[a3.lever] ?? 9) - (LEVER_ORDER[b5.lever] ?? 9)).filter((v2, i4, arr) => arr.findIndex((x4) => x4.action === v2.action) === i4).slice(0, 12); return { room_checks: roomChecks, summary: { total: roomChecks.length, passed: passed.length, failed: failed.length, skipped: skipped.length, errored: errored.length, pass: failed.length === 0 && errored.length === 0, message: failed.length === 0 ? errored.length === 0 ? `\u2705 \u6240\u6709\u623F\u95F4\u5C3A\u5BF8\u5728\u7528\u9014\u6807\u51C6\u8303\u56F4\u5185\uFF08${passed.length} \u4E2A\u901A\u8FC7\uFF09` : `\u26A0\uFE0F ${errored.length} \u4E2A\u623F\u95F4\u8BA1\u7B97\u9519\u8BEF\uFF0C${passed.length} \u4E2A\u901A\u8FC7` : `\u274C ${failed.length}/${roomChecks.length} \u4E2A\u623F\u95F4\u8D85\u51FA\u6807\u51C6\u8303\u56F4\uFF1A${failed.map((r4) => `${r4.name}(${r4.failures.join(",")})`).join("\u3001")}` }, violations: sortedViolations }; } // skills/design-arch/scripts/post-check.js function postCheck(params) { const building = params.building; const stage = params.stage ?? "massing"; const planned = params.planned ?? {}; if (!building) { return { error: "\u672A\u83B7\u5F97 building \u6570\u636E\u5BF9\u8C61\uFF08\u8BF7\u5148\u8C03 apply_design \u7F16\u8BD1\u2014\u2014\u7ED3\u679C\u4F1A\u81EA\u52A8\u6CE8\u5165\uFF0C\u6216\u663E\u5F0F\u4F20\u5165 building \u5B57\u6BB5\uFF09" }; } const stageConfig = { massing: { level: "L1", threshold: 0.05 }, structure: { level: "L2", threshold: 0.05 }, full: { level: "L2", threshold: 0.03 } }; const cfg = stageConfig[stage] ?? stageConfig.massing; const level = cfg.level; const threshold = cfg.threshold; const { info, floors, indicators, issues } = _analyze(building, planned, level); const verification = []; if (stage === "massing" || stage === "structure" || stage === "full") { _checkMassing(indicators, planned, verification, threshold); } if (stage === "structure" || stage === "full") { _checkStructure(floors, indicators, planned, verification, issues, threshold); } if (stage === "full") { _checkFull(building, issues); } const summary = _summary(verification, issues, stage, threshold); return { stage, level, threshold, building_info: info, floors, indicators, verification, issues, summary }; } function _checkMassing(indicators, planned, checks, threshold) { if (planned.total_area != null) { const a3 = indicators.total_area ?? 0; const p2 = planned.total_area; _addCheck(checks, "\u603B\u5EFA\u7B51\u9762\u79EF", p2, a3, threshold); } if (planned.site_area != null && indicators.far != null) { const a3 = indicators.far; const p2 = planned.far ?? a3; _addCheck(checks, "\u5BB9\u79EF\u7387(FAR)", p2, a3, threshold); } if (planned.floors != null) { const a3 = indicators.floor_count ?? 0; const p2 = planned.floors; _addCheck(checks, "\u5C42\u6570", p2, a3, 0); } } function _checkStructure(floors, indicators, planned, checks, issues, threshold) { if (indicators.core_ratio != null && planned.core_ratio != null) { _addCheck(checks, "\u6838\u5FC3\u7B52\u5360\u6BD4(%)", planned.core_ratio, indicators.core_ratio, 0.15); } if (planned.floor_area != null) { for (const fl2 of floors) { if (fl2.area != null) { const r4 = fl2.area / planned.floor_area; if (r4 < 0.7 || r4 > 1.3) { issues.push({ type: "warn", stage: "structure", msg: `\u5C42 ${fl2.id} \u9762\u79EF ${fl2.area}\u33A1 \u4E0E\u6807\u51C6\u5C42 ${planned.floor_area}\u33A1 \u504F\u5DEE ${Math.round((r4 - 1) * 100)}%` }); } } } } } function _checkFull(data, issues) { const dote = data.dote ?? {}; if (Object.keys(dote).length > 0) { const dx = dote.dote_dims?.find((d2) => d2.id === "X"); const dy = dote.dote_dims?.find((d2) => d2.id === "Y"); const nx = dx?.labels?.length ? dx.labels.length - 1 : "?"; const ny = dy?.labels?.length ? dy.labels.length - 1 : "?"; issues.push({ type: "info", msg: `\u7F51\u683C: ${nx}\xD7${ny}` }); } const rooms = data.rooms ?? data.spaces ?? []; if (rooms.length > 0) { issues.push({ type: "info", msg: `\u623F\u95F4/\u7A7A\u95F4: ${rooms.length} \u4E2A` }); } } function _addCheck(checks, item, planned, actual, threshold) { const diff = actual - planned; const devPct = planned > 0.01 ? Math.round(diff / planned * 1e3) / 10 : 0; let status; if (threshold === 0) { status = diff === 0 ? "ok" : diff > 0 ? "\u8D85\u9650" : "\u4E0D\u8DB3"; } else { status = Math.abs(devPct / 100) <= threshold ? "ok" : diff > 0 ? "\u8D85\u9650" : "\u4E0D\u8DB3"; } checks.push({ item, planned, actual, diff: Math.round(diff * 10) / 10, deviation_pct: devPct, status }); } function _analyze(data, planned, _level) { const bldg = data.building ?? data; const info = {}; const floors = []; const issues = []; const levelsData = bldg.levels ?? bldg.floors ?? []; const roomsData = bldg.rooms ?? bldg.spaces ?? []; info.level_count = levelsData.length; info.room_count = roomsData.length; let totalArea = 0; let totalBuildingArea = 0; let totalCoreArea = 0; for (const lv of levelsData) { const lid = lv.id ?? lv.name ?? "?"; const area = _n2(lv, "area", "floor_area", "gross_area"); const usable = _n2(lv, "usable_area", "net_area"); const core = _n2(lv, "core_area", "service_area"); floors.push({ id: lid, area, usable_area: usable, core_area: core }); totalArea += area ?? 0; totalBuildingArea += area ?? usable ?? 0; totalCoreArea += core ?? 0; } if (!totalArea && roomsData.length > 0) { totalArea = roomsData.reduce((sum, r4) => { return sum + (_n2(r4, "area", "floor_area") ?? 0); }, 0); } const siteArea = planned.site_area ?? null; const far = siteArea ? Math.round(totalArea / siteArea * 100) / 100 : null; if (!siteArea) { issues.push({ type: "info", msg: "\u672A\u63D0\u4F9B\u7528\u5730\u9762\u79EF\uFF08planned.site_area\uFF09\uFF0C\u8DF3\u8FC7\u5BB9\u79EF\u7387(FAR)\u6307\u6807\u4E0E\u6821\u6838" }); } const indicators = { total_area: totalArea, building_area: totalBuildingArea, floor_count: levelsData.length || info.level_count, far, site_area: siteArea, core_area: totalCoreArea, core_ratio: totalBuildingArea > 0 ? Math.round(totalCoreArea / totalBuildingArea * 1e3) / 10 : 0 }; return { info, floors, indicators, issues }; } function _summary(checks, issues, stage, _threshold) { const ok = checks.filter((c2) => c2.status === "ok").length; const failed = checks.filter((c2) => c2.status !== "ok"); if (checks.length === 0) { return `[${stage}] \u672A\u4F20\u5165\u89C4\u5212\u6307\u6807\uFF0C\u4EC5\u8F93\u51FA\u57FA\u7840\u6570\u636E`; } if (failed.length === 0) { return `[${stage}] ${checks.length} \u9879\u5168\u90E8\u901A\u8FC7 \u2713`; } const action = stage !== "full" ? "\u56DE\u5230\u672C\u9636\u6BB5\u91CD\u7B97" : "\u56DE\u5230 structure \u9636\u6BB5\u8C03\u6574"; const items = failed.map((c2) => c2.item).join(", "); return `[${stage}] ${failed.length}/${checks.length} \u672A\u901A\u8FC7: ${items}\u3002${action}`; } function _n2(obj, ...keys) { for (const k of keys) { const v2 = obj[k]; if (v2 != null) { return Number(v2); } } return null; } // skills/design-arch/scripts/dote-verify.js function doteVerify(params) { const subModule = params.sub_module ?? 1.2; const derived = deriveFromAml(params.aml, subModule); const zones = params.zones ?? derived.zones ?? []; const doteBounds = params.dote_bounds ?? derived.dote_bounds ?? {}; let smx, smy; if (typeof subModule === "object" && !Array.isArray(subModule)) { smx = Number(subModule.x ?? subModule.sub_module_x ?? 1.2); smy = Number(subModule.y ?? subModule.sub_module_y ?? smx); } else if (Array.isArray(subModule)) { smx = Number(subModule[0]); smy = subModule.length > 1 ? Number(subModule[1]) : smx; } else { smx = Number(subModule); smy = smx; } if (smx <= 0 || smy <= 0) { return { error: "sub_module: \u5FC5\u987B > 0" }; } const cellArea = smx * smy; const dx = doteBounds.dote_dims?.find((d2) => d2.id === "X"); const dy = doteBounds.dote_dims?.find((d2) => d2.id === "Y"); const gnx = dx?.labels?.length ? dx.labels.length - 1 : 9999; const gny = dy?.labels?.length ? dy.labels.length - 1 : 9999; let totalPlanned = 0; let totalActual = 0; const verification = []; for (const zone of zones) { const zid = zone.id ?? "?"; const name24 = zone.name ?? "?"; const planned = zone.planned_area ?? 0; const occupied = zone.occupied ?? []; let actualCells = 0; const outOfBounds = []; const overlapCells = /* @__PURE__ */ new Set(); for (const rect of occupied) { const y0 = rect.y0 ?? 0; const y1 = rect.y1 ?? 0; const x0 = rect.x0 ?? 0; const x1 = rect.x1 ?? 0; if (y1 >= gny || x1 >= gnx) { outOfBounds.push({ rect, max: `ny=${gny}, nx=${gnx}` }); } for (let y2 = y0; y2 <= y1; y2++) { for (let x4 = x0; x4 <= x1; x4++) { const key = `${y2},${x4}`; if (overlapCells.has(key)) continue; overlapCells.add(key); actualCells++; } } } const actualArea = Math.round(actualCells * cellArea * 10) / 10; const diff = Math.round((actualArea - planned) * 10) / 10; const devPct = planned ? Math.round(diff / Math.max(1, planned) * 100 * 10) / 10 : 0; totalPlanned += planned; totalActual += actualArea; const result = { id: zid, name: name24, planned_area: planned, actual_area: actualArea, diff, deviation_pct: devPct, cells: actualCells, status: Math.abs(devPct) <= 10 ? "ok" : devPct > 0 ? "\u4F4E\u4F30" : "\u9AD8\u4F30" }; if (outOfBounds.length > 0) { result.out_of_bounds = outOfBounds; result.status = "\u51FA\u754C"; } verification.push(result); } const totalDiff = Math.round((totalActual - totalPlanned) * 10) / 10; const totalDevPct = totalPlanned ? Math.round(totalDiff / Math.max(1, totalPlanned) * 100 * 10) / 10 : 0; return { verification, total_planned_area: totalPlanned, total_actual_area: totalActual, total_diff: totalDiff, total_deviation_pct: totalDevPct, total_status: Math.abs(totalDevPct) <= 10 ? "ok" : totalDevPct > 0 ? "\u4F4E\u4F30" : "\u9AD8\u4F30", cell_area: cellArea, note: "planned_area \u6765\u81EA dote-calc \u7684\u5206\u914D\u5EFA\u8BAE\uFF0Cactual_area \u6765\u81EA AI \u5B9E\u9645\u586B\u5199\u7684 grid bounds" }; } // skills/design-arch/scripts/daylight-depth.js var DAYLIGHT_REQUIREMENTS = { master_bedroom: { needsDaylight: true, maxDepthRatio: 2 }, bedroom: { needsDaylight: true, maxDepthRatio: 2 }, living: { needsDaylight: true, maxDepthRatio: 2 }, dining: { needsDaylight: true, maxDepthRatio: 2 }, living_dining: { needsDaylight: true, maxDepthRatio: 2 }, kitchen: { needsDaylight: true, maxDepthRatio: 1.8 }, study: { needsDaylight: true, maxDepthRatio: 2 }, office: { needsDaylight: true, maxDepthRatio: 2 }, meeting: { needsDaylight: true, maxDepthRatio: 1.5 }, reception: { needsDaylight: true, maxDepthRatio: 2 }, bathroom: { needsDaylight: false, maxDepthRatio: 0 }, balcony: { needsDaylight: false, maxDepthRatio: 0 }, corridor: { needsDaylight: false, maxDepthRatio: 0 }, circulation: { needsDaylight: false, maxDepthRatio: 0 }, storage: { needsDaylight: false, maxDepthRatio: 0 }, mechanical: { needsDaylight: false, maxDepthRatio: 0 } }; function _boundPosition(bound, labels, spacings) { if (typeof bound !== "string") return null; return amlLabelPosition(bound.trim(), spacings, labels); } function _doteBoundsToDepth(bounds, spacingsX, spacingsY, xLabels, yLabels) { if (!bounds || bounds.length !== 4) return null; const y1 = _boundPosition(bounds[0], yLabels, spacingsY); const y2 = _boundPosition(bounds[1], yLabels, spacingsY); const x1 = _boundPosition(bounds[2], xLabels, spacingsX); const x22 = _boundPosition(bounds[3], xLabels, spacingsX); if (y1 == null || y2 == null || x1 == null || x22 == null) return null; return { width: Math.abs(x22 - x1), depth: Math.abs(y2 - y1) }; } function daylightDepth(params) { const derived = deriveFromAml(params.aml); const rooms = params.rooms ?? derived.rooms; const floorHeight = params.floor_height ?? derived.floor_height ?? 3; const dsfRatio = params.dsf_ratio ?? 2; const dote = params.dote ?? derived.dote; if (!rooms || rooms.length === 0) { return { error: "\u7F3A\u5C11 rooms \u6570\u636E\uFF08\u53EF\u7531 aml \u6D3E\u751F\uFF1B\u8BF7\u4F20 aml \u6216\u5148\u7F16\u5199 AML\uFF09" }; } if (!dote) { return { error: "\u7F3A\u5C11 dote \u8F74\u7F51\u5B9A\u4E49\uFF08\u53EF\u7531 aml \u6D3E\u751F\uFF1BAML \u9700\u542B dote-system/dote-dim\uFF09" }; } const dims = dote.dote_dims ?? []; const xDim = dims.find((d2) => d2.id === "X"); const yDim = dims.find((d2) => d2.id === "Y"); const spacingsX = xDim?.spacings ?? [8.4]; const spacingsY = yDim?.spacings ?? [8.4]; const xLabels = xDim?.labels ?? []; const yLabels = yDim?.labels ?? []; const maxDaylightDepth = floorHeight * dsfRatio; const roomResults = []; const warnings = []; let totalExcess = 0; let unverified = 0; for (const room of rooms) { const name24 = room.name ?? room.id ?? "?"; const rtype = detectRoomType(room); const bounds = room.dote_bounds; const req = DAYLIGHT_REQUIREMENTS[rtype] ?? { needsDaylight: true, maxDepthRatio: 2 }; if (!bounds || bounds.length !== 4) { roomResults.push({ name: name24, type: rtype, needs_daylight: req.needsDaylight, error: "\u7F3A\u5C11 dote_bounds\uFF0C\u65E0\u6CD5\u8BA1\u7B97\u8FDB\u6DF1" }); unverified++; continue; } const dims2 = _doteBoundsToDepth(bounds, spacingsX, spacingsY, xLabels, yLabels); if (!dims2) { roomResults.push({ id: room.id, name: name24, type: rtype, needs_daylight: req.needsDaylight, error: `dote_bounds [${bounds.join(", ")}] \u65E0\u6CD5\u5728\u8F74\u7F51\u4E2D\u89E3\u6790\uFF08label \u4E0D\u5728 X/Y labels \u4E2D\uFF09\uFF0C\u65E0\u6CD5\u6821\u9A8C\u8FDB\u6DF1` }); unverified++; continue; } const { width, depth } = dims2; const actualDepth = Math.max(width, depth); const actualWidth = Math.min(width, depth); const depthRatio = actualDepth > 0 ? Math.round(actualDepth / floorHeight * 10) / 10 : 0; const exceeded = actualDepth > maxDaylightDepth; const excessPct = exceeded ? Math.round((actualDepth - maxDaylightDepth) / maxDaylightDepth * 100) : 0; const entry = { id: room.id, name: name24, type: rtype, floor_height: floorHeight, width: Math.round(actualWidth * 10) / 10, depth: Math.round(actualDepth * 10) / 10, aspect_ratio: actualDepth > 0 ? Math.round(actualWidth / actualDepth * 10) / 10 : 0, max_daylight_depth: Math.round(maxDaylightDepth * 10) / 10, depth_to_floor_ratio: depthRatio, depth_exceeded: exceeded, excess_pct: excessPct, needs_daylight: req.needsDaylight }; if (exceeded) { entry.warning = `\u8FDB\u6DF1 ${entry.depth}m \u8D85\u8FC7\u91C7\u5149\u6781\u9650 ${maxDaylightDepth}m\uFF08\u5C42\u9AD8${floorHeight}m \xD7 ${dsfRatio}\uFF09\uFF0C\u8D85\u51FA ${excessPct}%\u3002\u540E\u534A\u90E8\u5206\u9700\u8981\u4EBA\u5DE5\u7167\u660E`; if (req.needsDaylight) { warnings.push(`${name24}\uFF08${rtype}\uFF09\u8FDB\u6DF1${entry.depth}m > ${maxDaylightDepth}m\uFF0C\u8D85\u51FA${excessPct}%`); totalExcess++; } } else if (actualDepth > 0) { entry.status = `\u8FDB\u6DF1 ${entry.depth}m\uFF0C\u5728\u91C7\u5149\u6781\u9650 ${maxDaylightDepth}m \u8303\u56F4\u5185`; } roomResults.push(entry); } return { rooms: roomResults, warnings, summary: { total_rooms: rooms.length, daylight_rooms: roomResults.filter((r4) => r4.needs_daylight).length, excess_count: totalExcess, unverified_count: unverified, pass: totalExcess === 0 && unverified === 0, message: totalExcess > 0 ? `\u26A0\uFE0F ${totalExcess} \u4E2A\u623F\u95F4\u8FDB\u6DF1\u8D85\u8FC7\u4FA7\u7A97\u91C7\u5149\u6781\u9650\uFF0C\u5EFA\u8BAE\u51CF\u5C0F\u8FDB\u6DF1\u6216\u91C7\u7528\u53CC\u4FA7\u91C7\u5149/\u5929\u7A97` : unverified > 0 ? `\u26A0\uFE0F ${unverified} \u4E2A\u623F\u95F4\u65E0\u6CD5\u89E3\u6790 dote_bounds\uFF0C\u8FDB\u6DF1\u672A\u6821\u9A8C\uFF08\u8BE6\u89C1\u5404\u623F\u95F4 error\uFF09` : "\u2705 \u6240\u6709\u623F\u95F4\u8FDB\u6DF1\u5728\u91C7\u5149\u6781\u9650\u5185" }, config: { floor_height: floorHeight, depth_ratio: dsfRatio, max_daylight_depth: maxDaylightDepth } }; } // skills/design-arch/scripts/adjacency-check.js function _roomList(params) { const norm = (r4) => { const id = r4?.id ?? r4?.identifier; if (typeof id !== "string" || id === "") return null; const name24 = r4?.name ?? r4?.display_name ?? id; return { id, name: typeof name24 === "string" ? name24 : String(name24) }; }; if (Array.isArray(params.rooms) && params.rooms.length > 0) { return params.rooms.map(norm).filter((r4) => r4 !== null); } const building = params.building; if (building?.floors) { return building.floors.flatMap((f2) => (f2.rooms ?? []).map(norm).filter((r4) => r4 !== null)); } return []; } function adjacencyCheck(params) { const pairs = params.adjacency_pairs; if (!Array.isArray(pairs)) { return { error: "\u9700\u8981 adjacency_pairs \u6570\u636E\uFF08GSA \u90BB\u63A5\u5206\u6790\u7ED3\u679C\uFF09\uFF1A\u8BF7\u5148\u8C03 apply_design \u7F16\u8BD1\u6216 query_spatial_graph \u67E5\u8BE2" }; } if (params.mode !== void 0 && params.mode !== "adjacencies") { return { error: `\u672A\u77E5\u7684 mode: "${params.mode}"\uFF08\u4EC5\u652F\u6301 adjacencies\uFF1B\u6D41\u7EBF/\u8FDE\u901A\u6027\u6821\u9A8C\u8BF7\u7528 validate_model\uFF09` }; } const rooms = _roomList(params); const connected = /* @__PURE__ */ new Set(); for (const p2 of pairs) { connected.add(p2.from); connected.add(p2.to); } const orphan_ids = rooms.length > 0 ? rooms.filter((r4) => !connected.has(r4.id)).map((r4) => r4.id).sort() : []; return { adjacencies: pairs, orphan_ids, source: "gsa", summary: rooms.length > 0 ? orphan_ids.length > 0 ? `${pairs.length} \u5BF9\u76F8\u90BB, ${orphan_ids.length} \u4E2A\u5B64\u7ACB\u7A7A\u95F4 (gsa)` : `${pairs.length} \u5BF9\u76F8\u90BB, \u5168\u90E8\u8FDE\u901A (gsa)` : `${pairs.length} \u5BF9\u76F8\u90BB (gsa\uFF1B\u672A\u63D0\u4F9B\u7A7A\u95F4\u5217\u8868\uFF0C\u8DF3\u8FC7\u5B64\u7ACB\u68C0\u6D4B)` }; } // skills/design-arch/scripts/tech-indicators.js function _check(item, value, limit, unit, op) { const ok = op === "\u2264" ? value <= limit : value >= limit; return { item, value: Math.round(value * 10) / 10, limit: Math.round(limit * 10) / 10, unit, operator: op, status: ok ? "ok" : "\u8D85\u9650" }; } function _floorUse(i4, total) { if (total <= 2) return "\u901A\u7528"; if (i4 === 0) return "\u5927\u5802/\u516C\u5171"; if (i4 === total - 1) return "\u7BA1\u7406\u5C42/\u4F1A\u8BAE"; return "\u6807\u51C6\u529E\u516C"; } function techIndicators(params) { const missing = ["site_area", "total_area", "floors"].find((k) => !(params[k] > 0)); if (missing) return { error: `${missing}: \u5FC5\u586B\u53C2\u6570\uFF08number>0\uFF09` }; const site = Number(params.site_area); const total = Number(params.total_area); const floors = Number(params.floors); const floorA = params.floor_area ?? total / floors; const coreA = params.core_area; const hLimit = params.height_limit; const fHeight = params.floor_height ?? 4; const gr2 = params.green_ratio ?? 0.3; const footprint = floorA; const height = floors * fHeight; const usable = coreA ? total - coreA : total * 0.78; const farV = Math.round(total / site * 100) / 100; const densityV = Math.round(footprint / site * 100 * 10) / 10; const greenArea = Math.round(site * gr2 * 10) / 10; const compliance = []; if (hLimit) { compliance.push(_check("\u5EFA\u7B51\u9AD8\u5EA6", height, hLimit, "m", "\u2264")); } compliance.push(_check("\u5BB9\u79EF\u7387", farV, params.far_max ?? 2, "", "\u2264")); compliance.push(_check("\u5EFA\u7B51\u5BC6\u5EA6", densityV, params.density_max ?? 45, "%", "\u2264")); if (coreA) { const cr2 = Math.round(coreA / total * 100 * 10) / 10; compliance.push(_check("\u6838\u5FC3\u7B52\u5360\u6BD4", cr2, 25, "%", "\u2264")); } const perFloor = []; if (floors > 0) { for (let i4 = 0; i4 < Math.floor(floors); i4++) { perFloor.push({ floor: `F${i4 + 1}`, area: Math.round(floorA * 10) / 10, height: i4 > 0 ? fHeight : Math.min(fHeight + 0.5, 5.5), use: _floorUse(i4, floors) }); } } return { site: { area: site, footprint: Math.round(footprint * 10) / 10, floor_area_ratio: farV }, far: { value: farV, max: params.far_max ?? 2 }, building: { floors, height: Math.round(height * 10) / 10, height_limit: hLimit || null, total_area: Math.round(total * 10) / 10, floor_area: Math.round(floorA * 10) / 10, floor_height: fHeight }, density: { value_pct: densityV, coverage_area: Math.round(footprint * 10) / 10 }, green: { ratio_pct: Math.round(gr2 * 100), area: greenArea }, efficiency: { core_area: coreA ? Math.round(coreA * 10) / 10 : null, core_ratio: coreA ? Math.round(coreA / total * 100 * 10) / 10 : null, usable_area: Math.round(usable * 10) / 10, usable_ratio: Math.round(usable / total * 100 * 10) / 10 }, compliance, per_floor: perFloor }; } // skills/design-arch/scripts/core-efficiency.js function coreEfficiency(params) { const fa = Number(params.floor_area); const ec2 = Number(params.elevator_count); const sc2 = Number(params.stair_count); const cw = Number(params.corridor_width); const la = Number(params.lobby_area); const elevator_shaft = ec2 * 3 * 2.4; const stair_shaft = sc2 * 6 * 3; const vestibule_area = Number(params.vestibule_area ?? sc2 * 8); const shaft_ratio = Number(params.shaft_ratio ?? 0.12); const mechanical_ratio = Number(params.mechanical_ratio ?? 0.06); const base = elevator_shaft + stair_shaft + vestibule_area + la; const shaft_area = base * shaft_ratio; const mechanical_area = base * mechanical_ratio; let usable_approx = fa - base - shaft_area - mechanical_area; if (usable_approx < 0) { usable_approx = 0; } const corridor_area = Math.sqrt(usable_approx) * cw * 2; const core = base + shaft_area + mechanical_area + corridor_area; let core_ratio; if (fa > 0) { core_ratio = core / fa * 100; } else { core_ratio = 0; } const usable = fa - core; let usable_ratio; if (fa > 0) { usable_ratio = usable / fa * 100; } else { usable_ratio = 0; } return { core_area: Number(core.toFixed(2)), core_ratio: Number(core_ratio.toFixed(2)), usable_area: Number(usable.toFixed(2)), usable_ratio: Number(usable_ratio.toFixed(2)), elevator_shaft_area: Number(elevator_shaft.toFixed(2)), stair_shaft_area: Number(stair_shaft.toFixed(2)), vestibule_area: Number(vestibule_area.toFixed(2)), shaft_area: Number(shaft_area.toFixed(2)), mechanical_area: Number(mechanical_area.toFixed(2)), corridor_area: Number(corridor_area.toFixed(2)), lobby_area_input: la }; } // skills/design-arch/scripts/layout-tells.js var LAYOUT_TELLS = [ { id: "uniform-grid-module", category: "slop", severity: "advisory", name: "\u8F74\u7F51\u4E00\u5200\u5207", description: "\u5168\u90E8\u8DE8\u8DDD\u76F8\u540C\uFF08\u5982 8.4m\xD78.4m \u7B49\u8DE8\uFF09\u7684\u8F74\u7F51\u662F\u672A\u7ECF\u529F\u80FD\u5206\u6790\u7684\u6A21\u677F\u5316\u7279\u5F81\u2014\u2014\u771F\u5B9E\u8BBE\u8BA1\u4E2D\u8DE8\u8DDD\u7531\u623F\u95F4\u9762\u5BBD\u9700\u6C42\u4E0E\u529F\u80FD\u5206\u533A\u63A8\u51FA\uFF0C\u4F4F\u5B85\u4E0E\u529E\u516C\u6DF7\u6392\u3001\u5927\u5C0F\u623F\u95F4\u5171\u5B58\u65F6\u51E0\u4E4E\u4E0D\u53EF\u80FD\u5168\u7B49\u8DE8\u3002", prevention: "\u7981\u6B62\u672A\u7ECF\u529F\u80FD\u5206\u6790\u5C31\u91C7\u7528\u5168\u7B49\u8DE8\u8F74\u7F51\uFF08\u5982\u5168\u90E8 8.4m\xD78.4m\uFF09\u2014\u2014\u8DE8\u8DDD\u5E94\u7531\u623F\u95F4\u9762\u5BBD\u9700\u6C42\u4E0E\u529F\u80FD\u5206\u533A\u63A8\u51FA\uFF0C\u7528 dote-calc \u7684 module \u6570\u7EC4\u6216 zones \u5206\u533A\u6A21\u5F0F\u8868\u8FBE\u4E0D\u7B49\u8DE8", fix: "\u6309\u5404\u529F\u80FD\u533A\u623F\u95F4\u9762\u5BBD\u9700\u6C42\u91CD\u8DD1 dote-calc\uFF08module \u6570\u7EC4\u9010\u8DE8\u6307\u5B9A\uFF0C\u6216\u591A\u529F\u80FD\u533A zones \u6A21\u5F0F\uFF09\uFF0C\u8BA9\u8DE8\u8DDD\u53CD\u6620\u529F\u80FD\u5DEE\u5F02" }, { id: "south-squeeze", category: "slop", severity: "advisory", name: "\u5168\u671D\u5357\u786C\u6324", description: '\u6240\u6709\u5C45\u5BA4\u5168\u90E8\u671D\u5357\u4E14\u51FA\u73B0\u9762\u5BBD\u4E0D\u8DB3/\u72ED\u957F\u623F\u95F4\u2014\u2014\u4E3A\u8FFD\u6C42"\u5168\u671D\u5357"\u628A\u623F\u95F4\u538B\u6241\uFF0C\u662F LLM \u6392\u623F\u7684\u5178\u578B\u5957\u8DEF\u3002\u5357\u5411\u9762\u5BBD\u662F\u7A00\u7F3A\u8D44\u6E90\uFF0C\u771F\u5B9E\u8BBE\u8BA1\u6309\u4F18\u5148\u7EA7\u5206\u914D\u5E76\u63A5\u53D7\u90E8\u5206\u623F\u95F4\u975E\u5357\u5411\u3002', prevention: '\u7981\u6B62\u4E3A"\u6240\u6709\u5C45\u5BA4\u671D\u5357"\u628A\u623F\u95F4\u538B\u6210\u9762\u5BBD\u4E0D\u8FBE\u6807\u7684\u72ED\u957F\u6761\u2014\u2014\u5357\u5411\u9762\u5BBD\u6309\u4F18\u5148\u7EA7\u5206\u914D\uFF08\u4E3B\u5367/\u5BA2\u5385/\u4E3B\u8981\u529E\u516C\u7A7A\u95F4\u4F18\u5148\uFF09\uFF0C\u9762\u5BBD\u4E0D\u8DB3\u65F6\u6B21\u5367/\u4E66\u623F\u5B81\u53EF\u975E\u5357\u5411\u4E5F\u8981\u4FDD\u4F4F\u9762\u5BBD\u4E0E\u957F\u5BBD\u6BD4', fix: "\u628A\u88AB\u6324\u6241\u7684\u623F\u95F4\u4E0E\u5317\u5411\u623F\u95F4\u4EA4\u6362\u6216\u5408\u5E76\u5F00\u95F4\uFF0C\u63A5\u53D7\u6B21\u8981\u623F\u95F4\u975E\u5357\u5411\uFF0C\u4F18\u5148\u4FDD\u4F4F\u6BCF\u4E2A\u623F\u95F4\u7684\u9762\u5BBD\u4E0E\u957F\u5BBD\u6BD4\u8FBE\u6807" }, { id: "mono-orientation", category: "slop", severity: "advisory", name: "\u5168\u697C\u5355\u5411\u91C7\u5149", description: "\u5168\u697C\u6709\u7A97\u623F\u95F4\u671D\u540C\u4E00\u65B9\u5411\u5F00\u7A97\u2014\u2014\u5355\u4FA7\u91C7\u5149\u65E0\u6CD5\u5F62\u6210\u7A7F\u5802\u98CE\u8DEF\u5F84\uFF0C\u8FDB\u6DF1\u5927\u7684\u5E73\u9762\u5185\u533A\u660F\u6697\uFF0C\u662F LLM \u6309\u5355\u4E00\u671D\u5411\u903B\u8F91\u6392\u623F\u7684\u7ED3\u679C\u3002", prevention: "\u7981\u6B62\u5168\u697C\u623F\u95F4\u671D\u540C\u4E00\u65B9\u5411\u5F00\u7A97\u2014\u2014\u4F4F\u5B85\u5E94\u4E89\u53D6\u53CC\u4FA7/\u591A\u4FA7\u91C7\u5149\u5F62\u6210\u901A\u98CE\u8DEF\u5F84\uFF0C\u8FDB\u6DF1\u5927\u7684\u5E73\u9762\u5355\u4FA7\u91C7\u5149\u4F1A\u8BA9\u5185\u533A\u660F\u6697\uFF1B\u53A8\u536B\u7B49\u8F85\u52A9\u7A7A\u95F4\u53EF\u5E03\u7F6E\u5728\u975E\u4E3B\u671D\u5411\u9762", fix: "\u8C03\u6574\u5E03\u5C40\u4F7F\u623F\u95F4\u83B7\u5F97\u4E24\u4E2A\u4EE5\u4E0A\u671D\u5411\u7684\u91C7\u5149\u9762\uFF08\u5982\u7AEF\u5934\u623F\u95F4\u5F00\u4FA7\u7A97\u3001\u4EA4\u901A\u6838\u5317\u79FB\u91CA\u653E\u5357\u5411\u4EE5\u5916\u7684\u9762\uFF09\uFF0C\u8FDB\u6DF1\u8FC7\u5927\u65F6\u8003\u8651\u5185\u5929\u4E95\u6216\u7F29\u51CF\u8FDB\u6DF1" }, { id: "uniform-openings", category: "slop", severity: "advisory", name: "\u7A97\u5C3A\u5BF8\u4E00\u5200\u5207", description: "\u6240\u6709\u7A97\u540C\u5BBD\u540C\u9AD8\u2014\u2014\u771F\u5B9E\u8BBE\u8BA1\u4E2D\u7A97\u5C3A\u5BF8\u968F\u623F\u95F4\u529F\u80FD\u4E0E\u9762\u5BBD\u53D8\u5316\uFF08\u5BA2\u5385\u5927\u7A97\u3001\u5367\u5BA4\u4E2D\u7B49\u3001\u53A8\u536B\u9AD8\u7A97\u5C0F\u7A97\uFF09\uFF0C\u5168\u540C\u5C3A\u5BF8\u662F\u6279\u91CF\u9ED8\u8BA4\u751F\u6210\u7684\u7279\u5F81\u3002", prevention: "\u7981\u6B62\u6240\u6709\u7A97\u540C\u5BBD\u540C\u9AD8\u4E00\u5200\u5207\u2014\u2014\u7A97\u5C3A\u5BF8\u5E94\u968F\u623F\u95F4\u529F\u80FD\u4E0E\u9762\u5BBD\u53D8\u5316\uFF08\u5BA2\u5385\u5927\u7A97/\u843D\u5730\u3001\u5367\u5BA4\u4E2D\u7B49\u3001\u53A8\u536B\u9AD8\u7A97\u5C0F\u7A97\uFF09\uFF0C\u7A97\u5730\u6BD4\u6309\u623F\u95F4\u91C7\u5149\u9700\u6C42\u5DEE\u5F02\u5316", fix: "\u6309\u623F\u95F4\u529F\u80FD\u5DEE\u5F02\u5316\u7A97\u5C3A\u5BF8\uFF1A\u5BA2\u5385/\u4E3B\u671D\u5411\u52A0\u5927\u7A97\u5BBD\uFF0C\u53A8\u536B\u6539\u9AD8\u7A97\u5C0F\u7A97\uFF0C\u5FC5\u8981\u65F6\u7528 wwr \u6309\u623F\u95F4\u5206\u522B\u58F0\u660E" }, { id: "uniform-room-sizes", category: "slop", severity: "advisory", name: "\u623F\u95F4\u9762\u79EF\u96F6\u68AF\u5EA6", description: "\u540C\u7C7B\u623F\u95F4\u9762\u79EF\u5B8C\u5168\u4E00\u81F4\uFF08\u5982\u6240\u6709\u6B21\u5367\u90FD\u662F 12.0\u33A1\uFF09\u2014\u2014\u771F\u5B9E\u8BBE\u8BA1\u4E2D\u540C\u7C7B\u623F\u95F4\u4E5F\u6709\u4E3B\u6B21\u68AF\u5EA6\uFF08\u5927\u5C0F\u6B21\u5367\u3001\u5927\u5C0F\u529E\u516C\u5BA4\uFF09\uFF0C\u96F6\u65B9\u5DEE\u662F\u6A21\u677F\u590D\u5236\u7684\u7ED3\u679C\u3002", prevention: "\u7981\u6B62\u540C\u7C7B\u623F\u95F4\u9762\u79EF\u5B8C\u5168\u4E00\u81F4\u2014\u2014\u591A\u4E2A\u6B21\u5367/\u529E\u516C\u5BA4\u7B49\u540C\u7C7B\u578B\u623F\u95F4\u4E5F\u5E94\u6709\u4E3B\u6B21\u68AF\u5EA6\uFF0C\u6309\u4F7F\u7528\u9700\u6C42\u5206\u51FA\u5927\u5C0F\uFF0C\u4E0D\u8981\u590D\u5236\u540C\u4E00\u5C3A\u5BF8", fix: "\u6309\u4F7F\u7528\u9700\u6C42\u4E3A\u540C\u7C7B\u623F\u95F4\u5206\u51FA\u4E3B\u6B21\u68AF\u5EA6\uFF08\u5982\u4E3B\u5367 > \u5927\u6B21\u5367 > \u5C0F\u6B21\u5367\uFF09\uFF0C\u8C03\u6574 dote-bounds \u504F\u79FB\u8868\u8FBE\u5F0F\u7CBE\u786E\u8868\u8FBE\u5404\u81EA\u9762\u79EF" } ]; var HABITABLE_TYPES = /* @__PURE__ */ new Set(["master_bedroom", "bedroom", "living", "living_dining", "study", "office"]); function layoutTells(params) { const hits = []; const checked = []; const skipped = []; const tell = (id) => LAYOUT_TELLS.find((t4) => t4.id === id); const hit = (id, evidence) => { const t4 = tell(id); hits.push({ id, name: t4.name, severity: t4.severity, evidence, fix: t4.fix }); }; const dims = params.dote?.dote_dims ?? []; const dx = dims.find((d2) => /x/i.test(d2.id)); const dy = dims.find((d2) => /y/i.test(d2.id)); if (dx && dy && dx.spacings.length >= 2 && dy.spacings.length >= 2) { checked.push("uniform-grid-module"); const all = [...dx.spacings, ...dy.spacings]; const base = all[0]; if (all.length >= 5 && all.every((v2) => Math.abs(v2 - base) < 0.01)) { hit("uniform-grid-module", `\u8F74\u7F51 X \u5411 ${dx.spacings.length} \u8DE8\u3001Y \u5411 ${dy.spacings.length} \u8DE8\u5168\u90E8 ${base}m \u7B49\u8DE8`); } } else { skipped.push({ tell: "uniform-grid-module", reason: "\u65E0\u8F74\u7F51\u6570\u636E\uFF08dote \u7F3A\u5931\u6216 X/Y \u7EF4\u8DE8\u6570\u4E0D\u8DB3\uFF09" }); } const rooms = params.building?.rooms ?? []; const apertures = params.building?.apertures ?? []; if (rooms.length === 0) { for (const id of ["south-squeeze", "mono-orientation", "uniform-openings", "uniform-room-sizes"]) { skipped.push({ tell: id, reason: "\u65E0 building \u7F16\u8BD1\u7F13\u5B58\uFF08\u5148 apply_design \u7F16\u8BD1\uFF09" }); } } else { const northAngle = params.north_angle ?? (Number(params.building?.north_angle) || 0); const apsByRoom = /* @__PURE__ */ new Map(); for (const ap of apertures) { for (const rid of ap.rooms || []) { if (!apsByRoom.has(rid)) apsByRoom.set(rid, []); apsByRoom.get(rid).push(ap); } } const infos = rooms.map((room) => ({ room, rtype: detectRoomType(room), m: computeMetrics(room, apsByRoom.get(room.identifier) || [], northAngle, []) })); { checked.push("south-squeeze"); const habitable = infos.filter((i4) => HABITABLE_TYPES.has(i4.rtype) && i4.m.validWindowCount > 0); const southOnes = habitable.filter((i4) => i4.m.hasSouthWindow); if (habitable.length >= 2 && southOnes.length === habitable.length) { const squeezed = habitable.filter((i4) => { const crit = DEFAULT_CRITERIA[i4.rtype]; if (!crit) return false; return crit.minWidth && i4.m.minWidth > 0 && i4.m.minWidth < crit.minWidth || crit.maxRatio && i4.m.ratio > 0 && i4.m.ratio > crit.maxRatio; }); if (squeezed.length > 0) { const s2 = squeezed[0]; const crit = DEFAULT_CRITERIA[s2.rtype]; const why = crit.minWidth && s2.m.minWidth > 0 && s2.m.minWidth < crit.minWidth ? `\u9762\u5BBD ${s2.m.minWidth}m < ${crit.minWidth}m` : `\u957F\u5BBD\u6BD4 ${s2.m.ratio}:1 > ${crit.maxRatio}:1`; hit("south-squeeze", `${habitable.length} \u4E2A\u5C45\u5BA4\u5168\u90E8\u671D\u5357\uFF0C\u5176\u4E2D\u300C${s2.room.display_name ?? s2.room.identifier}\u300D${why}\u2014\u2014\u7591\u4F3C\u4E3A\u5168\u671D\u5357\u786C\u6324`); } } } { checked.push("mono-orientation"); const DIR_CN2 = { north: "\u5317", east: "\u4E1C", south: "\u5357", west: "\u897F" }; const dirSet = /* @__PURE__ */ new Set(); let windowedRooms = 0; for (const i4 of infos) { const wins = (apsByRoom.get(i4.room.identifier) || []).filter((a3) => a3.geometry_type === "window" && a3.hosting?.on_exterior_wall !== false); if (wins.length === 0) continue; windowedRooms++; const cx = i4.room.point?.[0] ?? (i4.m.minX + i4.m.maxX) / 2; const cy = i4.room.point?.[1] ?? (i4.m.minY + i4.m.maxY) / 2; for (const w3 of wins) { const d2 = windowOrientation(w3, cx, cy, northAngle); if (d2) dirSet.add(d2); } } if (windowedRooms >= 4 && dirSet.size === 1) { const d2 = [...dirSet][0]; hit("mono-orientation", `${windowedRooms} \u4E2A\u6709\u7A97\u623F\u95F4\u5168\u90E8\u671D${DIR_CN2[d2] ?? d2}\u5F00\u7A97`); } } { checked.push("uniform-openings"); const wins = apertures.filter((a3) => a3.geometry_type === "window"); const sized = wins.filter((w3) => Number.isFinite(w3.width) && Number.isFinite(w3.height)); if (sized.length >= 3 && sized.length === wins.length) { const w0 = sized[0].width, h0 = sized[0].height; if (sized.every((w3) => Math.abs(w3.width - w0) < 0.05 && Math.abs(w3.height - h0) < 0.05)) { hit("uniform-openings", `${sized.length} \u4E2A\u7A97\u5168\u90E8 ${w0}m\xD7${h0}m`); } } } { checked.push("uniform-room-sizes"); const byType = /* @__PURE__ */ new Map(); for (const i4 of infos) { if (i4.rtype === "circulation" || i4.rtype === "void" || i4.m.area <= 0) continue; if (!byType.has(i4.rtype)) byType.set(i4.rtype, []); byType.get(i4.rtype).push(i4); } for (const [rtype, group] of byType) { if (group.length < 3) continue; const areas = group.map((i4) => i4.m.area); const lo = Math.min(...areas), hi2 = Math.max(...areas); if (hi2 - lo < 0.3) { hit("uniform-room-sizes", `${group.length} \u95F4 ${rtype} \u9762\u79EF\u5168\u90E8 ${areas[0]}\u33A1\uFF0C\u96F6\u4E3B\u6B21\u68AF\u5EA6`); break; } } } } const summary = hits.length > 0 ? `\u68C0\u6D4B\u5230 ${hits.length} \u6761\u751F\u6210\u4FD7\u5957\u63D0\u793A\uFF08advisory\uFF0C\u4E0D\u8BA1\u5206\uFF09\uFF1A${hits.map((h2) => h2.name).join("\u3001")}` : "\u672A\u68C0\u6D4B\u5230\u751F\u6210\u4FD7\u5957"; return { tells: hits, checked, skipped, summary }; } function formatTellPreventions() { return [ "## \u5E38\u89C1\u751F\u6210\u4FD7\u5957\uFF08\u7981\u6B62\u2014\u2014AI \u751F\u6210\u5E73\u9762\u7684\u5178\u578B\u5957\u8DEF\uFF0C\u8BBE\u8BA1\u65F6\u5FC5\u987B\u4E3B\u52A8\u89C4\u907F\uFF09", "", ...LAYOUT_TELLS.map((t4, i4) => `${i4 + 1}. **${t4.name}**\uFF1A${t4.prevention}`) ].join("\n"); } // skills/design-arch/scripts/design-review.js var ALL_CHECKS = ["rooms", "areas", "daylight", "adjacency", "flows", "indicators", "tells"]; var CHECK_SEVERITY = { rooms: "P2", areas: "P1", daylight: "P2", adjacency: "P0", flows: "P0", indicators: "P1", tells: "P3" }; function ratingBand(score) { return score >= 85 ? "\u826F\u597D" : score >= 70 ? "\u4E2D\u7B49" : "\u8F83\u5DEE"; } function designReview(params) { const p2 = params ?? {}; const checks = Array.isArray(p2.checks) && p2.checks.length > 0 ? p2.checks.filter((c2) => ALL_CHECKS.includes(c2)) : [...ALL_CHECKS]; const aml = typeof p2.aml === "string" && p2.aml.trim() ? p2.aml : void 0; const lite = parseAmlLite(aml); const building = p2.building; const rooms = p2.rooms ?? (lite.rooms.length > 0 ? lite.rooms : void 0); const dote = p2.dote ?? lite.dote; const northAngle = p2.north_angle ?? lite.north_angle; const floorHeight = p2.floor_height ?? lite.levels.find((l13) => l13.height !== void 0)?.height; const stageUsed = building ? "compiled" : "precompile"; const needCompileNote = aml ? "\u8BF7\u5148\u7528 apply_design \u7F16\u8BD1\u5F53\u524D AML" : "\u65E0 building \u4E14\u65E0 AML\uFF08\u8BF7\u5148\u7F16\u5199 AML \u5E76 apply_design \u7F16\u8BD1\uFF09"; const checksRun = []; const checksSkipped = []; const results = {}; const failures = []; const topFixes = []; const tells = []; let score; let compiledBasis = false; const run = (check2, impl, fn2, args) => { let r4; try { r4 = fn2(args); } catch (err2) { checksSkipped.push({ check: check2, reason: `${impl} \u6267\u884C\u5F02\u5E38\uFF1A${err2?.message ?? err2}` }); return null; } if (r4?.error) { checksSkipped.push({ check: check2, reason: `${impl}\uFF1A${r4.error}` }); return null; } checksRun.push(check2); return r4; }; const skip = (check2, reason) => checksSkipped.push({ check: check2, reason }); if (checks.includes("rooms")) { if (building) { const r4 = run("rooms", "layout-eval", layoutEval, { building, criteria: p2.criteria, north_angle: northAngle, building_type: p2.building_type, party_walls: p2.party_walls }); if (r4) { compiledBasis = true; results.rooms = r4; score = r4.aggregate_score; for (const rs2 of r4.room_scores ?? []) { for (const f2 of rs2.failures ?? []) { failures.push({ check: "rooms", room: rs2.name, issue: f2 }); } } for (const f2 of r4.top_fixes ?? []) topFixes.push(f2.action ?? String(f2)); } } else if (rooms && dote) { const r4 = run("rooms", "dote-room-check", doteRoomCheck, { rooms, dote, criteria: p2.criteria, building_type: p2.building_type }); if (r4) { results.rooms = r4; for (const rc2 of r4.room_checks ?? []) { for (const f2 of rc2.failures ?? []) { const fix = (rc2.fixes ?? []).find((x4) => x4.code === f2)?.action; failures.push({ check: "rooms", room: rc2.name, issue: f2, fix }); } } for (const v2 of r4.violations ?? []) topFixes.push(v2.action ?? String(v2)); } } else { skip("rooms", aml ? `rooms\uFF08layout-eval\uFF09\u8DF3\u8FC7\uFF1A${needCompileNote}` : "\u65E0 building \u4E14 AML \u4E2D\u672A\u89E3\u6790\u5230 rooms/dote"); } } if (checks.includes("areas")) { if (building) { const r4 = run("areas", "post-check", postCheck, { building, stage: p2.stage ?? "full", planned: p2.planned }); if (r4) { compiledBasis = true; results.areas = r4; for (const c2 of r4.verification ?? []) { if (c2.status && c2.status !== "ok") { failures.push({ check: "areas", issue: `${c2.item}\uFF1A\u89C4\u5212 ${c2.planned}\uFF0C\u5B9E\u9645 ${c2.actual}\uFF08${c2.status} ${c2.deviation_pct}%\uFF09` }); } } } } else { const derived = amlZonesForDoteVerify(lite, p2.sub_module); const zones = p2.zones ?? derived?.zones; if (zones) { const r4 = run("areas", "dote-verify", doteVerify, { sub_module: p2.sub_module ?? (derived ? { x: derived.smx, y: derived.smy } : void 0), zones, dote_bounds: p2.dote_bounds ?? dote }); if (r4) { results.areas = r4; for (const v2 of r4.verification ?? []) { if (v2.status && v2.status !== "ok") { failures.push({ check: "areas", room: v2.name ?? v2.id, issue: `\u89C4\u5212 ${v2.planned_area}\u33A1\uFF0C\u5B9E\u9645 ${v2.actual_area}\u33A1\uFF08${v2.status}\uFF09` }); } } } } else { skip("areas", aml ? `areas\uFF08post-check\uFF09\u8DF3\u8FC7\uFF1A${needCompileNote}\uFF08\u514D\u7F16\u8BD1\u9762\u79EF\u6821\u6838\u9700 AML \u542B\u53EF\u89E3\u6790\u7684 dote-bounds\uFF09` : "\u65E0 building \u4E14 AML \u4E2D\u672A\u89E3\u6790\u5230 zones"); } } } if (checks.includes("daylight")) { if (rooms && dote) { const r4 = run("daylight", "daylight-depth", daylightDepth, { rooms, dote, floor_height: floorHeight, dsf_ratio: p2.dsf_ratio }); if (r4) { results.daylight = r4; for (const w3 of r4.warnings ?? []) failures.push({ check: "daylight", issue: w3 }); } } else { skip("daylight", "AML \u4E2D\u672A\u89E3\u6790\u5230 rooms + dote\uFF08\u91C7\u5149\u8FDB\u6DF1\u6821\u9A8C\u9700\u8981\u623F\u95F4 dote-bounds \u4E0E\u8F74\u7F51\u5B9A\u4E49\uFF09"); } } if (checks.includes("adjacency")) { if (p2.adjacency_pairs) { const r4 = run("adjacency", "adjacency-check", adjacencyCheck, { mode: "adjacencies", adjacency_pairs: p2.adjacency_pairs, rooms, building }); if (r4) { results.adjacency = r4; for (const id of r4.orphan_ids ?? []) failures.push({ check: "adjacency", room: id, issue: "\u5B64\u7ACB\u7A7A\u95F4\uFF08\u65E0\u4EFB\u4F55\u90BB\u63A5\uFF09" }); } } else { skip("adjacency", `\u65E0 adjacency_pairs\uFF1A${needCompileNote}\uFF08\u90BB\u63A5\u6821\u9A8C\u8D70 query_spatial_graph / validate_model\uFF0C\u672C\u5730\u63A8\u5BFC\u5DF2\u4E0B\u7EBF\uFF09`); } } if (checks.includes("flows")) { skip("flows", "\u6D41\u7EBF/\u8FDE\u901A\u6027\u6821\u9A8C\u8D70 validate_model\uFF08GSA AuditEngine\uFF09\uFF1A\u672C\u5730 flow-verify \u5DF2\u4E0B\u7EBF"); } if (checks.includes("indicators")) { const ind = {}; const indSkipped = []; if (p2.site_area !== void 0 && p2.total_area !== void 0 && p2.floors !== void 0) { const r4 = run("indicators", "tech-indicators", techIndicators, { site_area: p2.site_area, total_area: p2.total_area, floors: p2.floors, floor_area: p2.floor_area, core_area: p2.core_area, height_limit: p2.height_limit, floor_height: floorHeight, green_ratio: p2.green_ratio }); if (r4) { ind.tech_indicators = r4; for (const c2 of r4.compliance ?? []) { if (c2.status && c2.status !== "ok") failures.push({ check: "indicators", issue: `${c2.item}\uFF1A${c2.value}\uFF08\u9650\u5236 ${c2.limit}\uFF0C${c2.status}\uFF09` }); } } } else { indSkipped.push("tech-indicators\uFF08\u7F3A site_area/total_area/floors\uFF09"); } if (["floor_area", "elevator_count", "stair_count", "corridor_width", "lobby_area"].every((k) => p2[k] !== void 0)) { const r4 = run("indicators", "core-efficiency", coreEfficiency, { floor_area: p2.floor_area, elevator_count: p2.elevator_count, stair_count: p2.stair_count, corridor_width: p2.corridor_width, lobby_area: p2.lobby_area, ...p2.vestibule_area !== void 0 ? { vestibule_area: p2.vestibule_area } : {}, ...p2.shaft_ratio !== void 0 ? { shaft_ratio: p2.shaft_ratio } : {}, ...p2.mechanical_ratio !== void 0 ? { mechanical_ratio: p2.mechanical_ratio } : {} }); if (r4) ind.core_efficiency = r4; } else { indSkipped.push("core-efficiency\uFF08\u7F3A floor_area/elevator_count/stair_count/corridor_width/lobby_area\uFF09"); } if (Object.keys(ind).length > 0) { if (indSkipped.length > 0) ind.skipped = indSkipped; results.indicators = ind; if (!checksRun.includes("indicators")) checksRun.push("indicators"); } else { skip("indicators", `\u6307\u6807\u53C2\u6570\u4E0D\u8DB3\uFF1A${indSkipped.join("\uFF1B")}`); } } if (checks.includes("tells")) { if (building || dote) { const r4 = run("tells", "layout-tells", layoutTells, { building, dote, north_angle: northAngle, building_type: p2.building_type }); if (r4) { results.tells = r4; for (const t4 of r4.tells ?? []) tells.push({ check: "tells", ...t4 }); } } else { skip("tells", "\u65E0 building \u7F16\u8BD1\u7F13\u5B58\u4E14 AML \u4E2D\u672A\u89E3\u6790\u5230\u8F74\u7F51\uFF08\u4FD7\u5957\u68C0\u6D4B\u9700\u8981\u4E8C\u8005\u4E4B\u4E00\uFF09"); } } for (const f2 of failures) f2.severity = CHECK_SEVERITY[f2.check] ?? "P2"; for (const t4 of tells) t4.severity = "P3"; const band = score !== void 0 ? ratingBand(score) : void 0; const prevScore = typeof p2.prev_result?.score === "number" ? p2.prev_result.score : void 0; const trend = score !== void 0 && prevScore !== void 0 ? { prev_score: prevScore, score, delta: score - prevScore } : void 0; const dedupedFixes = [...new Set(topFixes)].slice(0, 10); const parts = [ `\u9636\u6BB5=${stageUsed === "compiled" ? "\u7F16\u8BD1\u540E" : "\u514D\u7F16\u8BD1"}`, `\u5DF2\u8DD1 ${checksRun.length} \u9879\uFF08${checksRun.join("\u3001") || "\u65E0"}\uFF09` ]; if (checksSkipped.length > 0) parts.push(`\u8DF3\u8FC7 ${checksSkipped.length} \u9879`); if (score !== void 0) parts.push(`\u54C1\u8D28\u5206 ${score}/100\uFF08${band}\uFF09`); if (trend) parts.push(`\u8F83\u4E0A\u8F6E ${trend.delta >= 0 ? "+" : ""}${trend.delta} \u5206`); parts.push(failures.length > 0 ? `\u274C ${failures.length} \u6761\u5931\u8D25\u9879` : "\u2705 \u65E0\u5931\u8D25\u9879"); if (tells.length > 0) parts.push(`\u{1F4A1} ${tells.length} \u6761\u4FD7\u5957\u63D0\u793A\uFF08advisory\uFF0C\u4E0D\u8BA1\u5206\uFF09`); if (compiledBasis && aml) parts.push("\u6CE8\uFF1A\u7F16\u8BD1\u540E\u68C0\u67E5\u9879\u57FA\u4E8E\u6700\u8FD1\u4E00\u6B21 apply_design \u7F16\u8BD1\u7ED3\u679C\uFF0CAML \u4E3A\u5F53\u524D\u771F\u503C"); const summary = parts.join("\uFF0C"); return { stage_used: stageUsed, checks_run: checksRun, checks_skipped: checksSkipped, results, failures, ...score !== void 0 ? { score, rating_band: band } : {}, ...trend ? { trend } : {}, ...tells.length > 0 ? { tells } : {}, top_fixes: dedupedFixes, summary, _display: summary.slice(0, 80) }; } var designReviewMeta = { params: { aml: { type: "string", desc: "\u3010\u552F\u4E00\u771F\u503C\u3011\u5F53\u524D\u8BBE\u8BA1\u7684 AML XML \u5B57\u7B26\u4E32\u3002\u7F3A\u7701\u81EA\u52A8\u6CE8\u5165\u5BBF\u4E3B\u5F53\u524D\u7F16\u8F91\u5668 AML\uFF0C\u901A\u5E38\u65E0\u9700\u663E\u5F0F\u4F20\uFF1B\u514D\u7F16\u8BD1\u68C0\u67E5\u9879\uFF08rooms/areas/daylight\uFF09\u7684\u8F93\u5165\u5168\u90E8\u7531\u5B83\u6D3E\u751F" }, checks: { type: "array", desc: "\u8981\u8DD1\u7684\u68C0\u67E5\u9879\u5B50\u96C6\uFF1Arooms(\u623F\u95F4\u5C3A\u5BF8\u54C1\u8D28)/areas(\u9762\u79EF\u8FBE\u6210)/daylight(\u91C7\u5149\u8FDB\u6DF1)/adjacency(\u90BB\u63A5)/flows(\u6D41\u7EBF)/indicators(\u6307\u6807\u7EDF\u8BA1)/tells(\u751F\u6210\u4FD7\u5957\u63D0\u793A,advisory \u4E0D\u8BA1\u5206)\u3002\u7F3A\u7701\u5168\u8DD1\uFF1B\u6570\u636E\u4E0D\u8DB3\u7684\u9879\u81EA\u52A8\u8DF3\u8FC7\u5E76\u7ED9 note\u3002flows \u6052\u8DF3\u8FC7\u2014\u2014\u6D41\u7EBF/\u8FDE\u901A\u6027\u6821\u9A8C\u8D70 validate_model\uFF08GSA AuditEngine\uFF09\u3002\u5176\u4F59\u8F93\u5165\uFF08rooms/dote/\u5C42\u9AD8/\u90BB\u63A5\u5BF9/\u6307\u6807\u53C2\u6570\u7B49\uFF09\u81EA\u52A8\u4ECE AML \u6D3E\u751F\u6216\u7F16\u8BD1\u7F13\u5B58\u6CE8\u5165\uFF0C\u65E0\u9700\u4F20\u53C2" }, criteria: { type: "object", desc: '\u81EA\u5B9A\u4E49\u623F\u95F4\u7528\u9014\u6807\u51C6\uFF0C\u8986\u76D6\u9ED8\u8BA4\u503C\u3002\u5982 {"bedroom":{"area":[10,15],"minWidth":3.3}}\uFF08\u900F\u4F20 layout-eval/dote-room-check\uFF09' }, building_type: { type: "string", desc: "\u5EFA\u7B51\u7C7B\u578B\uFF1Aresidential(\u4F4F\u5B85,\u9ED8\u8BA4)/office(\u529E\u516C)/commercial(\u5546\u4E1A)\u3002\u5F71\u54CD\u623F\u95F4\u9762\u79EF/\u9762\u5BBD\u9608\u503C\u4E0E\u4EA4\u901A\u5360\u6BD4\u4E0A\u9650\uFF08AML \u65E0\u6B64\u8F7D\u4F53\uFF0C\u9700\u663E\u5F0F\u6307\u5B9A\uFF09", default: "residential" }, party_walls: { type: "array", desc: "\u3010\u515C\u5E95\u3011\u5206\u6237\u5899\u671D\u5411\u6570\u7EC4\uFF08north/south/east/west\uFF09\u3002\u65E0 GSA \u5185\u5916\u5899\u6807\u6CE8\u65F6\u6309\u671D\u5411\u8FC7\u6EE4\u5206\u6237\u5899\u7A97\uFF08layout-eval \u900F\u4F20\uFF09", default: [] }, prev_result: { type: "object", desc: "\u3010\u81EA\u52A8\u6CE8\u5165\uFF0C\u52FF\u663E\u5F0F\u4F20\u3011\u4E0A\u4E00\u6B21 design-review \u7684\u5B8C\u6574\u7ED3\u679C\uFF08\u5DE5\u5177\u5C42\u4ECE lastResults \u6CE8\u5165\uFF09\uFF0C\u7528\u4E8E\u8BA1\u7B97\u8BC4\u5206\u8DE8\u8F6E\u8D8B\u52BF trend" } }, returns: { stage_used: { type: "string", desc: "\u5B9E\u9645\u5206\u53D1\u9636\u6BB5\uFF1Acompiled\uFF08\u6709 building \u7F13\u5B58\uFF09| precompile" }, checks_run: { type: "array", desc: "\u5B9E\u9645\u6267\u884C\u7684\u68C0\u67E5\u9879" }, checks_skipped: { type: "array", desc: "\u8DF3\u8FC7\u7684\u68C0\u67E5\u9879\u53CA\u539F\u56E0 [{check, reason}]\uFF08\u6570\u636E\u7F3A\u5931\u4E0D\u4E2D\u65AD\u5176\u4ED6\u9879\uFF09" }, results: { type: "object", desc: "\u5404\u68C0\u67E5\u9879\u539F\u59CB\u7ED3\u679C {rooms, areas, daylight, adjacency, flows, indicators, tells}" }, failures: { type: "array", desc: "\u805A\u5408\u5404\u68C0\u67E5\u9879\u5931\u8D25\u9879 [{check, room?, issue, fix?, severity}]\uFF0C\u5E26\u6765\u6E90 check \u540D\u4E0E\u4E25\u91CD\u7EA7\uFF08P0 \u963B\u65AD/P1 \u4E3B\u8981/P2 \u6B21\u8981\uFF09" }, tells: { type: "array", desc: "\u751F\u6210\u4FD7\u5957\u63D0\u793A [{check, id, name, severity, evidence, fix}]\uFF08layout-tells \u68C0\u6D4B\uFF0C\u5168\u90E8 advisory/P3\u2014\u2014\u4E0D\u8BA1\u5206\u3001\u4E0D\u8FDB failures\uFF1B\u4EC5\u547D\u4E2D\u65F6\u8FD4\u56DE\uFF09" }, score: { type: "number", desc: "layout-eval aggregate_score\uFF08\u4EC5\u8DD1\u4E86\u7F16\u8BD1\u540E rooms \u65F6\u5B58\u5728\uFF09" }, rating_band: { type: "string", desc: "\u8BC4\u5206\u5E26\uFF1A\u826F\u597D(\u226585)/\u4E2D\u7B49(70-84)/\u8F83\u5DEE(<70)\uFF08\u4EC5\u6709 score \u65F6\u8FD4\u56DE\uFF09" }, trend: { type: "object", desc: "\u8BC4\u5206\u8DE8\u8F6E\u8D8B\u52BF {prev_score, score, delta}\uFF08\u4E0A\u8F6E\u6709 design-review \u7ED3\u679C\u4E14\u672C\u8F6E\u6709 score \u65F6\u8FD4\u56DE\uFF09" }, top_fixes: { type: "array", desc: "\u6309\u6760\u6746\u4F18\u5148\u7EA7\u805A\u5408\u7684\u4FEE\u590D\u5EFA\u8BAE\uFF08\u6700\u591A 10 \u6761\uFF09" }, summary: { type: "string", desc: "\u603B\u4F53\u8BC4\u4EF7\uFF08\u9636\u6BB5/\u5DF2\u8DD1/\u8DF3\u8FC7/\u8BC4\u5206/\u5931\u8D25\u9879\u6570\uFF1BAML \u4E0E\u7F16\u8BD1\u7F13\u5B58\u5E76\u5B58\u65F6\u6CE8\u660E\u57FA\u51C6\uFF09" } } }; // src/tools/design-verification.ts var CAP = 5; function clip(text2, maxLen = 120) { const s2 = String(text2 ?? ""); return s2.length > maxLen ? `${s2.slice(0, maxLen)}\u2026` : s2; } function runDesignVerification(input) { const { aml, building, adjacencyPairs, compileLevel, errorIssues, warnIssues } = input; const checks = compileLevel === "full" ? ["rooms", "areas", "daylight", "adjacency", "tells"] : ["areas", "daylight", "adjacency", "tells"]; const review = designReview({ aml, building, // 空数组视为无数据(单房间户型天然无邻接对,传入会被 adjacency-check 误判全员孤立) ...adjacencyPairs?.length ? { adjacency_pairs: adjacencyPairs } : {}, checks, // post-check 按真实编译级别校核:massing 不跑 structure/full 级检查项(如核心筒占比) stage: compileLevel }); const p0 = [ ...errorIssues.slice(0, CAP).map((i4) => ({ code: i4.code, issue: clip(i4.message), ...i4.suggested_fix ? { fix: clip(i4.suggested_fix, 100) } : {} })), ...(review.failures ?? []).filter((f2) => f2.severity === "P0").map((f2) => ({ check: f2.check, room: f2.room, issue: clip(f2.issue), ...f2.fix ? { fix: clip(f2.fix, 100) } : {} })) ].slice(0, CAP); const p1 = (review.failures ?? []).filter((f2) => f2.severity === "P1").slice(0, CAP).map((f2) => ({ check: f2.check, room: f2.room, issue: clip(f2.issue), ...f2.fix ? { fix: clip(f2.fix, 100) } : {} })); const advisories = [ ...warnIssues.slice(0, 3).map((i4) => ({ code: i4.code, issue: clip(i4.message), ...i4.suggested_fix ? { fix: clip(i4.suggested_fix, 100) } : {} })), ...(review.failures ?? []).filter((f2) => f2.severity === "P2").map((f2) => ({ check: f2.check, room: f2.room, issue: clip(f2.issue), ...f2.fix ? { fix: clip(f2.fix, 100) } : {} })), ...(review.tells ?? []).map((t4) => ({ check: "tells", issue: clip(t4.evidence ?? t4.name ?? t4.id), ...t4.fix ? { fix: clip(t4.fix, 100) } : {} })) ].slice(0, CAP); const topFixes = [.../* @__PURE__ */ new Set([ ...errorIssues.map((i4) => i4.suggested_fix).filter((s2) => typeof s2 === "string" && !!s2), ...review.top_fixes ?? [] ])].slice(0, CAP).map((s2) => clip(s2, 120)); const run = review.checks_run ?? []; const skipped = review.checks_skipped ?? []; const checksNote = [ `${compileLevel} \u6863\u6821\u9A8C\uFF1A\u5DF2\u8DD1 ${run.length} \u9879\uFF08${run.join("\u3001") || "\u65E0"}\uFF09`, skipped.length ? `\u8DF3\u8FC7 ${skipped.length} \u9879` : "", compileLevel !== "full" ? "rooms \u8BC4\u5206\u5F85 full \u6863\uFF08\u95E8\u7A97\u5C31\u7EEA\u540E\uFF09" : "" ].filter(Boolean).join("\uFF0C"); return { verdict: p0.length > 0 || p1.length > 0 ? "fix_required" : "pass", ...p0.length ? { p0 } : {}, ...p1.length ? { p1 } : {}, ...advisories.length ? { advisories } : {}, ...typeof review.score === "number" ? { score: review.score, rating_band: review.rating_band } : {}, top_fixes: topFixes, checks_note: checksNote }; } // src/tools/door-targets.ts function parseAttrs(tag) { const out = {}; const re2 = /([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g; let m3; while (m3 = re2.exec(tag)) out[m3[1].toLowerCase()] = m3[2] ?? m3[3] ?? ""; return out; } function sharedEdgeLength(a3, b5) { const eps = 1e-6; if (Math.abs(a3.x0 - b5.x1) < eps || Math.abs(a3.x1 - b5.x0) < eps) { return Math.max(0, Math.min(a3.y1, b5.y1) - Math.max(a3.y0, b5.y0)); } if (Math.abs(a3.y0 - b5.y1) < eps || Math.abs(a3.y1 - b5.y0) < eps) { return Math.max(0, Math.min(a3.x1, b5.x1) - Math.max(a3.x0, b5.x0)); } return 0; } function normalizeDoorTargets(aml) { if (!aml || typeof aml !== "string" || !aml.includes(" d2.id === "X"); const yDim = lite.dote?.dote_dims.find((d2) => d2.id === "Y"); const rects = []; if (xDim && yDim) { for (const r4 of lite.rooms) { const gb = r4.dote_bounds; if (!gb || gb.length !== 4) continue; const [y1, y2, x1, x22] = gb; const py1 = amlLabelPosition(y1, yDim.spacings, yDim.labels); const py2 = amlLabelPosition(y2, yDim.spacings, yDim.labels); const px1 = amlLabelPosition(x1, xDim.spacings, xDim.labels); const px2 = amlLabelPosition(x22, xDim.spacings, xDim.labels); if (py1 === null || py2 === null || px1 === null || px2 === null) continue; rects.push({ id: r4.id, level: r4.level, x0: Math.min(px1, px2), x1: Math.max(px1, px2), y0: Math.min(py1, py2), y1: Math.max(py1, py2) }); } } const flowsPartners = /* @__PURE__ */ new Map(); const flowRe = /]*?)\/?>/gi; let fm; while (fm = flowRe.exec(aml)) { const a3 = parseAttrs(fm[1]); const from = (a3.from ?? "").trim(); const to = (a3.to ?? "").trim(); if (!from || !to) continue; if (!flowsPartners.has(from)) flowsPartners.set(from, /* @__PURE__ */ new Set()); if (!flowsPartners.has(to)) flowsPartners.set(to, /* @__PURE__ */ new Set()); flowsPartners.get(from).add(to); flowsPartners.get(to).add(from); } const hits = []; const spaceStack = []; const tokenRe = /<(\/?)\s*([A-Za-z][\w-]*)([^>]*)>/g; let tm; while (tm = tokenRe.exec(aml)) { const closing = tm[1] === "/"; const tag = tm[2].toLowerCase(); const rest = tm[3]; if (closing) { if (tag === "space") spaceStack.pop(); continue; } const selfClosing = /\/\s*$/.test(rest); if (tag === "space" && !selfClosing) { const a3 = parseAttrs(rest); spaceStack.push(a3.id ?? ""); } else if (tag === "aperture") { hits.push({ tag: tm[0], start: tm.index, end: tm.index + tm[0].length, hostSpace: spaceStack.length ? spaceStack[spaceStack.length - 1] : void 0, attrs: parseAttrs(rest) }); } } const filled = []; const unresolved = []; const targetByHit = /* @__PURE__ */ new Map(); for (const hit of hits) { const type = (hit.attrs.type ?? "").trim().toLowerCase(); if (type !== "door") continue; const existing = (hit.attrs.to ?? "").trim(); if (existing) continue; if (hit.attrs["boundary-ref"]) continue; if (hit.attrs["to_outside"] && hit.attrs["to_outside"].trim() !== "false") continue; const host2 = hit.hostSpace; const apertureLabel = hit.attrs.id || hit.tag.slice(0, 60); if (!host2) { unresolved.push({ aperture: apertureLabel, host_space: "(\u65E0\u5BBF\u4E3B\u7A7A\u95F4)", reason: "aperture \u65E0\u5BBF\u4E3B\u7A7A\u95F4\uFF08\u4E0D\u5728 \u5185\uFF09\uFF0C\u65E0\u6CD5\u63A8\u65AD\u76EE\u6807\u7A7A\u95F4" }); continue; } const partners = flowsPartners.get(host2); if (partners && partners.size === 1) { const to = [...partners][0]; targetByHit.set(hit, to); filled.push({ aperture: apertureLabel, host_space: host2, to, source: "flows" }); continue; } const hostRect = rects.find((r4) => r4.id === host2); if (!hostRect) { unresolved.push({ aperture: apertureLabel, host_space: host2, reason: "\u65E0\u6CD5\u89E3\u6790\u5BBF\u4E3B\u7A7A\u95F4\u51E0\u4F55\uFF08\u7F3A dote-bounds \u6216\u975E\u77E9\u5F62\uFF09\uFF0C\u8BF7\u663E\u5F0F\u5199 to" }); continue; } const doorWidth = parseFloat(hit.attrs.width ?? "0.9"); const neighbors = rects.filter((r4) => r4.id !== host2 && r4.level === hostRect.level && sharedEdgeLength(hostRect, r4) > 1e-6); const fitNeighbors = neighbors.filter((r4) => sharedEdgeLength(hostRect, r4) >= doorWidth - 1e-6); if (fitNeighbors.length === 1) { const to = fitNeighbors[0].id; targetByHit.set(hit, to); filled.push({ aperture: apertureLabel, host_space: host2, to, source: "geometry" }); continue; } if (fitNeighbors.length > 1) { unresolved.push({ aperture: apertureLabel, host_space: host2, reason: `\u6709 ${fitNeighbors.length} \u4E2A\u76F8\u90BB\u7A7A\u95F4\uFF08${fitNeighbors.map((r4) => r4.id).join("\u3001")}\uFF09\u65E0\u6CD5\u552F\u4E00\u786E\u5B9A\uFF0C\u8BF7\u663E\u5F0F\u5199 to` }); } else if (neighbors.length === 0) { unresolved.push({ aperture: apertureLabel, host_space: host2, reason: '\u65E0\u5171\u4EAB\u8FB9\u76F8\u90BB\u7A7A\u95F4\uFF08\u53EF\u80FD\u662F\u5916\u95E8/\u95E8\u4F4D\u60AC\u7A7A\uFF09\u2014\u2014\u76F4\u901A\u5BA4\u5916\u7684\u95E8\u8BF7\u663E\u5F0F\u5199 to_outside="true"\uFF0C\u4E0D\u8981\u5199 to' }); } else { unresolved.push({ aperture: apertureLabel, host_space: host2, reason: "\u76F8\u90BB\u7A7A\u95F4\u5171\u4EAB\u8FB9\u4E0D\u8DB3\u95E8\u5BBD\uFF0C\u8BF7\u68C0\u67E5\u95E8\u4F4D\u5E76\u663E\u5F0F\u5199 to" }); } } let out = aml; if (targetByHit.size > 0) { for (const hit of [...hits].sort((a3, b5) => b5.start - a3.start)) { const to = targetByHit.get(hit); if (!to) continue; const newTag = hit.tag.replace(/^ ({ from: l13.from ?? l13.source, to: l13.to ?? l13.target, type: l13.type, shared_length_m: l13.shared_length_m })).filter((l13) => typeof l13.from === "string" && typeof l13.to === "string").filter((l13) => !(excludeSight && l13.type === "sight")); } function fixAml(raw) { let aml = raw.trim(); aml = aml.replace(/^```(?:xml|aml)?\s*\n?/i, "").replace(/\n?```\s*$/i, ""); aml = aml.replace(/<\/?aml[^>]*>/gi, ""); const fixes = { "]*\bid\s*=\s*["']([^"']+)["']/i); const projId = projMatch?.[1] || "P"; let apN = 0; aml = aml.replace(/]*\bid\s*=)([^>]*\/?}>)/gi, (_2, attrs) => { apN++; const nid = `AP-${projId}-${String(apN).padStart(3, "0")}`; return attrs.endsWith("/>") ? `` : `]*>/gi, (tag) => { if (!/\sdote-bounds\s*=/i.test(tag)) return tag; return tag.replace(/\s+profile\s*=\s*"[^"]*"/gi, ""); }); aml = fixDoteBounds(aml); return aml; function fixDoteBounds(aml2) { return aml2.replace(/dote-bounds="([^"]*)"/g, (_match, value) => { const parts = value.trim().split(/\s+/); if (parts.length < 1 || parts.length === 1 && parts[0] === "") return _match; if (parts.length === 2) { const m1 = parts[0].match(/^([A-Za-z]+)(\d+)$/); const m22 = parts[1].match(/^([A-Za-z]+)(\d+)$/); if (m1 && m22) { return `dote-bounds="${m1[1]} ${m22[1]} ${m1[2]} ${m22[2]}"`; } } if (parts.length >= 4) { const firstIsNum = /^\d+$/.test(parts[0]); const firstIsLetter = /^[A-Za-z]+$/.test(parts[0]); const thirdIsNum = parts.length > 2 && /^\d+$/.test(parts[2]); if (firstIsNum && thirdIsNum) { return `dote-bounds="${parts[2]} ${parts[3]} ${parts[0]} ${parts[1]}"`; } if (firstIsLetter) { return `dote-bounds="${parts.slice(0, 4).join(" ")}"`; } } return _match; }); } } var applyDesign = tool({ description: [ "\u3010\u7F16\u8BD1 AML \u2192 GSA \u7F16\u8BD1 \u2192 \u4FDD\u5B58\u3011", "\u26A0\uFE0F \u5F53\u524D AML \u4E2D\u7684 ID \u5FC5\u987B\u662F 6 \u4F4D hex\u3002\u5982\u679C\u7528 AI \u81EA\u7F16\u7684\u5355\u5B57\u6BCD ID\uFF08\u5982 R1\u3001S1\uFF09\uFF0C\u8BF7\u5148\u8C03 generate_aml \u83B7\u53D6\u751F\u6210\u4E0A\u4E0B\u6587\uFF0C\u6309\u623F\u95F4\u6E05\u5355\u56FA\u5B9A ID \u91CD\u5199 Aopt-inML\u3002", "\u26A0\uFE0F aml \u53C2\u6570\u53EF\u9009\uFF1A\u7F3A\u7701\u65F6\u8BFB\u53D6\u5BBF\u4E3B\u5F53\u524D AML\uFF08edit_source \u5DF2\u81EA\u52A8\u4FDD\u5B58\uFF09\uFF0C\u76F4\u63A5\u8C03 apply_design() \u5373\u53EF\uFF0C\u65E0\u9700\u518D\u4F20 aml\u3002", "\u26A0\uFE0F \u4F7F\u7528\u9650\u5236\uFF1A\u4EC5\u9650\u4EE5\u4E0B\u573A\u666F\u4F7F\u7528\uFF1A", " 1. edit_source \u4FEE\u6539\u540E\u8C03 apply_design() \u589E\u91CF\u7F16\u8BD1", " 2. Stage 2/3 \u5199 flows/windows \u540E\u8C03 apply_design \u5168\u91CF\u7F16\u8BD1", " \u274C Stage 1 \u7981\u6B62\uFF1Agenerate_aml \u7EC4\u88C5\u4E0A\u4E0B\u6587\u5E76\u7F16\u5199 AML \u540E\u5FC5\u987B\u8C03 apply_design \u7F16\u8BD1\u3002", "\u5173\u952E\u89C4\u5219\uFF1A\u5168\u90E8\u5C0F\u5199 kebab-case\uFF08\u3001\uFF09\uFF0C\u7981\u6B62 CamelCase\u3002\u8F74\u7F51\u843D\u4F4D\u5199\u6CD5\uFF08origin \u5C5E\u6027 / SITE_BASE_POINT / NORTH_ANGLE param\uFF09\u89C1 generate_aml \u89C4\u5219\u3002", "\u7F16\u8BD1\u7EA7\u522B\u7531\u5F53\u524D\u8BBE\u8BA1\u6B65\u9AA4\u81EA\u52A8\u63A7\u5236\uFF0CAI \u65E0\u9700\u624B\u52A8\u6307\u5B9A level \u53C2\u6570\u3002\u5DF2\u652F\u6301: \u6807\u7B7E", "\u652F\u6301\u56DB\u4EF6\u5957\u6E90\u7801\uFF1A\u53EF\u9009 bss / rules / behaviors \u53C2\u6570\u4E0E AML \u4E00\u8D77\u63D0\u4EA4 GSA \u7F16\u8BD1\uFF08\u5982\u7528 PlaceAperture \u6309\u671D\u5411+\u5899\u579B\u7CBE\u786E\u5B9A\u4F4D\u95E8\u7A97\uFF09\uFF0C\u7F3A\u7701\u4F9D\u6B21\u4E3A\u5BBF\u4E3B\u5F53\u524D\u503C\u3001skill \u9ED8\u8BA4\u6587\u6863\u3002", "\u7F16\u8BD1\u4EA7\u7269\u843D\u5728\u670D\u52A1\u7AEF\u5DE5\u4F5C\u533A\uFF1B\u8981\u8BA9\u5B83\u51FA\u73B0\u5728\u4E91\u9879\u76EE/Studio\uFF0C\u7528 build_model \u6216\u5728\u7F16\u8BD1\u540E\u505A\u4E91\u540C\u6B65\u3002" ].join(" | "), inputSchema: external_exports2.object({ aml: external_exports2.string().optional().describe(["\u53EF\u9009\u3002\u7F3A\u7701\u65F6\u8BFB\u53D6\u5BBF\u4E3B\u5F53\u524D AML\uFF08edit_source \u5DF2\u81EA\u52A8\u4FDD\u5B58\uFF09\u3002", "Stage 1\uFF08massing\uFF09\u9636\u6BB5\u6309 generate_aml \u4E0A\u4E0B\u6587\u7F16\u5199 AML \u540E\u76F4\u63A5\u8C03 apply_design \u7F16\u8BD1\u3002"].join(" ")), bss: external_exports2.string().optional().describe("GSA BSS \u6837\u5F0F\u6587\u6863\uFF08\u53EF\u9009\uFF09\uFF0C\u7F3A\u7701\u4F9D\u6B21\u4E3A\u5BBF\u4E3B\u5F53\u524D\u503C\u3001skill \u9ED8\u8BA4\u6587\u6863"), rules: external_exports2.string().optional().describe("GSA rules \u6821\u9A8C\u89C4\u5219\u6587\u6863\uFF08\u53EF\u9009\uFF09\uFF0C\u7F3A\u7701\u4F9D\u6B21\u4E3A\u5BBF\u4E3B\u5F53\u524D\u503C\u3001skill \u9ED8\u8BA4\u6587\u6863"), behaviors: external_exports2.string().optional().describe("GSA behaviors YAML\uFF0C\u58F0\u660E\u5F0F\u884C\u4E3A\u89C4\u5219\uFF08\u5982 PlaceAperture \u6309\u671D\u5411+\u5899\u579B\u7CBE\u786E\u5B9A\u4F4D\u95E8\u7A97\uFF09\uFF0C\u7F3A\u7701\u4F9D\u6B21\u4E3A\u5BBF\u4E3B\u5F53\u524D\u503C\u3001skill \u9ED8\u8BA4\u6587\u6863"), level: external_exports2.enum(["massing", "structure", "full"]).optional().describe("\u7F16\u8BD1\u7EA7\u522B\uFF1Amassing=\u4F53\u5757, structure=\u4F53\u91CF+\u6D41\u7EBF\uFF08\u8FDE\u901A\u6309\u5171\u4EAB\u8FB9\u9608\u503C\u5224\u5B9A\uFF0C\u7981\u6B62\u95E8\u7A97\uFF09, full=\u5B8C\u6574\uFF08\u95E8\u7A97\u4EC5\u5728\u6B64\u6863\u63D2\u5165\uFF09\u3002\u672A\u4F20\u65F6\u81EA\u52A8\u89E3\u6790\uFF1A\u6D41\u7A0B\u72B6\u6001 vars.stage\uFF08\u524D\u6863\u7F16\u8BD1 pass \u540E\u81EA\u52A8\u63A8\u8FDB\uFF09> designStep \u63A8\u5BFC"), outputPath: external_exports2.string().optional().describe("\u8F93\u51FA\u8DEF\u5F84\uFF08JSON \u6587\u4EF6\u4FDD\u5B58\u8DEF\u5F84\uFF09"), gsaUrl: external_exports2.string().optional().describe("GSA \u670D\u52A1\u5730\u5740\uFF08\u9ED8\u8BA4 http://localhost:8000\uFF09"), merge_traffic_spaces: external_exports2.boolean().optional().describe('\u4EA4\u901A\u8FDE\u901A\u5408\u5E76\uFF08\u9ED8\u8BA4\u5F00\u542F\uFF0C\u4F20 false \u5173\u95ED\uFF09\uFF1A\u4EC5\u5BF9\u65E0\u663E\u5F0F\u58F0\u660E\u7684\u7A7A\u95F4\u751F\u6548\u3002\u663E\u5F0F \uFF08\u901A\u7528\u62FC\u5408\u5BB9\u5668\uFF0C\u4EFB\u610F\u7C7B\u578B\uFF09\u4E0E \uFF08\u62C6\u5206\u5BB9\u5668\uFF0Cchildren \u5E26 parent_id\uFF09\u4F18\u5148\u4E8E\u672C\u63A8\u65AD\uFF0C\u767D\u540D\u5355\u53EA\u505A\u517C\u5BB9\u515C\u5E95\u3002\u63A8\u65AD\u53E3\u5F84\uFF1A\u53EF\u901A\u884C\u8FDE\u901A\u7684\u6237\u5185\u8D70\u5ECA/\u95E8\u5385/\u5F00\u653E\u5BA2\u9910\u5385\u7B49\u5408\u5E76\u4E3A\u5355\u4E2A\u623F\u95F4\uFF08N space \u2192 1 room\uFF09\uFF1B\u6237\u8FB9\u754C\u6309\u6A21\u677F\u6EAF\u6E90\u5224\u5B9A\uFF0C\u540C\u4E00 \u5B9E\u4F8B\u514B\u9686\u7684\u7A7A\u95F4\u624D\u53EF\u5408\u5E76\uFF1BAML opt-in / merge="never" \u6392\u9664\u3002\u7EC4\u6210\u8BB0\u5F55\u5B58\u5165 room.metadata.merged_spaces'), min_passage_width: external_exports2.number().positive().optional().describe("massing/structure \u9636\u6BB5\u8FDE\u901A\u6027\u5224\u5B9A\u7684\u6700\u5C0F\u5171\u4EAB\u8FB9\u5BBD\u5EA6\uFF08\u7C73\uFF09\uFF0C\u9ED8\u8BA4 0.9\uFF1B\u4E24\u7A7A\u95F4\u5171\u4EAB\u8FB9 \u2265 \u8BE5\u503C\u5373\u89C6\u4E3A\u53EF\u901A\u884C") }), execute: (async (params, execOpts) => { console.log("[applyDesign.execute] ENTER", { amlLen: params.aml?.length, gsaUrl: params.gsaUrl }); if (!params.aml) { return { status: "error", message: "\u7F3A\u5C11 aml\uFF1A\u8BF7\u4F20 aml \u53C2\u6570\uFF0C\u6216\u7531\u5BBF\u4E3B\u6CE8\u5165 getCurrentAml \u56DE\u8C03" }; } const gsaUrl = params.gsaUrl || DEFAULT_GSA_URL2; let aml = fixAml(params.aml); aml = aml.replace(/[\s\S]*?<\/info>/gi, ""); aml = aml.replace(/dote_bounds=/gi, "dote-bounds="); const amlBeforeDoorFix = aml; const doorFix = normalizeDoorTargets(aml); aml = doorFix.aml; const localErrors = []; const ids = [...aml.matchAll(/id="([^"]+)"/g)].map((m3) => m3[1]); const dupIds = ids.filter((id, i4) => ids.indexOf(id) !== i4); if (dupIds.length) localErrors.push(`\u91CD\u590D\u7684 id: ${[...new Set(dupIds)].join(", ")}`); for (const gb of aml.matchAll(/dote[-_]bounds="([^"]+)"/g)) { const parts = gb[1].split(/\s+/); if (parts.length < 4) { localErrors.push(`dote-bounds \u81F3\u5C11\u9700\u8981 4 \u4E2A\u6807\u7B7E\uFF0C\u5B9E\u9645 ${parts.length}: "${gb[1]}"`); } } const axesX = /* @__PURE__ */ new Set(); const axesY = /* @__PURE__ */ new Set(); for (const m3 of aml.matchAll(/([^<]*)<\/axis-x>/gi)) { m3[1].trim().split(/\s+/).filter(Boolean).forEach((l13) => axesX.add(l13)); } for (const m3 of aml.matchAll(/([^<]*)<\/axis-y>/gi)) { m3[1].trim().split(/\s+/).filter(Boolean).forEach((l13) => axesY.add(l13)); } if (axesX.size > 0 && axesY.size > 0) { for (const gb of aml.matchAll(/dote[-_]bounds="([^"]+)"/g)) { const parts = gb[1].split(/\s+/).filter(Boolean); if (parts.length < 4) continue; const [y1, y2, x1, x22] = parts; const problems = []; if (!axesY.has(y1) || !axesY.has(y2)) { problems.push(`Y \u8F74\u65E0\u6807\u7B7E "${!axesY.has(y1) ? y1 : y2}"\uFF08\u73B0\u6709: ${[...axesY].join(" ")}\uFF09`); } if (!axesX.has(x1) || !axesX.has(x22)) { problems.push(`X \u8F74\u65E0\u6807\u7B7E "${!axesX.has(x1) ? x1 : x22}"\uFF08\u73B0\u6709: ${[...axesX].join(" ")}\uFF09`); } if (y1 === y2) problems.push(`Y \u5411\u96F6\u8DE8\u5EA6\uFF08\u8D77\u6B62\u90FD\u662F ${y1}\uFF09`); if (x1 === x22) problems.push(`X \u5411\u96F6\u8DE8\u5EA6\uFF08\u8D77\u6B62\u90FD\u662F ${x1}\uFF09`); if (problems.length > 0) { localErrors.push(`dote-bounds "${gb[1]}" \u975E\u6CD5\uFF1A${problems.join("\uFF1B")}\u3002\u6CE8\u610F\uFF1AN \u8DE8\u9700\u8981 N+1 \u6839\u8F74\u7EBF`); } } } for (const sg of aml.matchAll(/]*>/gi)) { const attrs = sg[0]; const bounds = attrs.match(/dote[-_]bounds\s*=\s*"([^"]+)"/); if (!bounds) localErrors.push(`space-group \u7F3A\u5C11 dote-bounds \u5C5E\u6027: ${sg[0].slice(0, 80)}`); const cols = parseInt(attrs.match(/cols\s*=\s*"(\d+)"/)?.[1] || "1", 10); const rows = parseInt(attrs.match(/rows\s*=\s*"(\d+)"/)?.[1] || "1", 10); if (cols < 1) localErrors.push(`space-group cols \u5FC5\u987B >= 1\uFF0C\u5B9E\u9645: ${cols}`); if (rows < 1) localErrors.push(`space-group rows \u5FC5\u987B >= 1\uFF0C\u5B9E\u9645: ${rows}`); } const amlWithoutTemplates = aml.replace(//gi, ""); const inlineLevelIds = new Set([...amlWithoutTemplates.matchAll(/]*\bid\s*=\s*"([^"]+)"/gi)].map((m3) => m3[1])); for (const u2 of amlWithoutTemplates.matchAll(/]*>/gi)) { for (const [, k, v2] of u2[0].matchAll(/([A-Za-z]+)\s*=\s*"([^"]+)"/g)) { if (k.toLowerCase() === "template") continue; if (inlineLevelIds.has(v2)) { localErrors.push( `\u697C\u5C42 "${v2}" \u88AB\u91CD\u590D\u5B9A\u4E49\uFF1A\u65E2\u6709\u5185\u8054 \u53C8\u6709 \u6309\u6A21\u677F\u5C55\u5F00\uFF08${u2[0].slice(0, 80)}\uFF09\u3002\u4E8C\u8005\u5FC5\u987B\u4E8C\u9009\u4E00\u2014\u2014\u7528\u6A21\u677F\u590D\u7528\u5C31\u5220\u6389\u5185\u8054 \uFF1B\u8981\u5185\u8054\u4E66\u5199\u5C31\u5220\u6389\u8BE5 ` ); break; } } } if (inlineLevelIds.size > 0) { const levelTemplateIds = /* @__PURE__ */ new Set(); for (const t4 of aml.matchAll(/]*\bid\s*=\s*"([^"]+)"[^>]*>([\s\S]*?)<\/template>/gi)) { if (/]/i.test(t4[2])) levelTemplateIds.add(t4[1]); } if (levelTemplateIds.size > 0) { for (const u2 of amlWithoutTemplates.matchAll(/]*\btemplate\s*=\s*"([^"]+)"[^>]*>/gi)) { if (levelTemplateIds.has(u2[1])) { localErrors.push( `\u697C\u5C42\u6A21\u677F\u4E0E\u5185\u8054 \u6DF7\u7528\uFF1Aproject \u5DF2\u542B\u5185\u8054 \uFF0C \u53C8\u6309\u697C\u5C42\u6A21\u677F\u5C55\u5F00\u6574\u5C42\uFF08${u2[0].slice(0, 80)}\uFF09\u3002\u4E8C\u8005\u5FC5\u987B\u4E8C\u9009\u4E00\u2014\u2014\u6807\u51C6\u5C42\u7528