freellmapi / server.js
StXh
after restore the db file, reopen it
e6ba285
Raw
History Blame Contribute Delete
121 kB
// @bun
var BJ=Object.defineProperty;var OJ=($)=>$;function VJ($,J){this[$]=OJ.bind(null,J)}var zJ=($,J)=>{for(var Q in J)BJ($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:VJ.bind(J,Q)})};var z0=import.meta.require;import Z from"crypto";import $1 from"fs";import N0 from"path";import{fileURLToPath as UJ}from"url";import J0 from"crypto";var{Database:z6}=global.bun?.sqlite||z0("bun:sqlite"),n0="aes-256-gcm",F$=null,p0=32,c0=p0*2;function u0($,J){if($.length!==c0||!/^[0-9a-fA-F]+$/.test($))throw Error(`Invalid ENCRYPTION_KEY (${J}): expected ${c0} hex chars (32 bytes), got ${$.length} chars. Generate one with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"`);return Buffer.from($,"hex")}function i0($){let J=process.env.ENCRYPTION_KEY;if(J&&J!=="your-64-char-hex-key-here"){F$=u0(J,"env");return}let Q=$.prepare("SELECT value FROM settings WHERE key = 'encryption_key'").get();if(Q){F$=u0(Q.value,"db");return}F$=J0.randomBytes(p0),$.prepare("INSERT INTO settings (key, value) VALUES ('encryption_key', ?)").run(F$.toString("hex"))}function E0(){if(!F$)throw Error("Encryption key not initialized. Call initEncryptionKey() first.");return F$}function d0(){return E0().toString("hex")}function o0($){let J=E0(),Q=J0.randomBytes(16),W=J0.createCipheriv(n0,J,Q),G=W.update($,"utf8","hex");G+=W.final("hex");let Y=W.getAuthTag().toString("hex");return{encrypted:G,iv:Q.toString("hex"),authTag:Y}}function w$($,J,Q){let W=E0(),G=J0.createDecipheriv(n0,W,Buffer.from(J,"hex"));G.setAuthTag(Buffer.from(Q,"hex"));let Y=G.update($,"hex","utf8");return Y+=G.final("utf8"),Y}function r0($){if($.length<=8)return"****"+$.slice(-4);return $.slice(0,4)+"..."+$.slice(-4)}async function a0(){let $=await fetch("https://raw.githubusercontent.com/anomalyco/models.dev/dev/models.json");if(!$.ok)throw Error(`Failed to fetch models.dev: ${$.status}`);return(await $.json()).data}function t0($){return $.filter((J)=>J.pricing?.prompt==="0"&&J.pricing?.completion==="0")}var EJ=new Set(["google","groq","cerebras","sambanova","nvidia","mistral","github","cohere","cloudflare","zhipu"]);function s0($){let J=$.id,Q=J.indexOf("/"),W=Q>0?J.slice(0,Q):J,G=Q>0?J.slice(Q+1):J;if(J.includes(":free")||!EJ.has(W))return{platform:"openrouter",modelId:J,displayName:$.name,contextWindow:$.context_length??0};return{platform:W,modelId:G,displayName:$.name,contextWindow:$.context_length??0}}function NJ($){let J=$.match(/(\d+)\s*b\b/i);if(J)return parseInt(J[1],10);let Q=$.match(/(\d+)\s*t\b/i);if(Q)return parseInt(Q[1],10)*1000;return null}function e0($){let J=$.name.toLowerCase(),Q=NJ(J),W=15,G=8,Y=["opus","o1","o3","claude-3.5","claude-4","gpt-4","gemini-pro","deepseek-v4","deepseek-r1","qwen3-235b","qwen3-coder"],X=["flash","lite","nano","mini","xs","small"];if(Y.some((H)=>J.includes(H)))W-=8;if(X.some((H)=>J.includes(H)))W+=5;if(J.includes("maverick")||J.includes("scout"))W+=2;if(Q!==null)if(Q<=2)W+=8,G=2;else if(Q<=9)W+=5,G=3;else if(Q<=32)W+=2,G=6;else if(Q<=70)W+=0,G=8;else if(Q<=120)W-=2,G=9;else if(Q<=250)W-=4,G=10;else if(Q<=500)W-=5,G=11;else W-=6,G=12;if($.context_length>500000)W-=1;return W=Math.max(1,Math.min(30,W)),G=Math.max(1,Math.min(15,G)),{intelligence:W,speed:G}}var{Database:LJ}=global.bun?.sqlite||z0("bun:sqlite"),SJ=typeof import.meta.url==="string"?UJ(import.meta.url):import.meta.url,jJ=N0.dirname(SJ),RJ=N0.join(jJ,"data","freeapi.db"),x;function A(){if(!x)throw Error("Database not initialized. Call initDb() first.");return x}async function J1($){let J=$??RJ,Q=J===":memory:";if(!Q){let G=N0.dirname(J);if(!$1.existsSync(G))$1.mkdirSync(G,{recursive:!0})}if(x=new LJ(J),!Q)x.exec("PRAGMA journal_mode = WAL");if(x.exec("PRAGMA foreign_keys = ON"),qJ(x),i0(x),x.prepare("SELECT COUNT(*) as cnt FROM models").get().cnt===0)try{await AJ(x)}catch(G){console.error("[DB] Failed to seed models from models.dev:",G)}return vJ(x),wJ(x),console.log(`Database initialized at ${J}`),x}function qJ($){$.exec(`
CREATE TABLE IF NOT EXISTS models (
id INTEGER PRIMARY KEY AUTOINCREMENT,
platform TEXT NOT NULL,
model_id TEXT NOT NULL,
display_name TEXT NOT NULL,
intelligence_rank INTEGER NOT NULL,
speed_rank INTEGER NOT NULL,
size_label TEXT NOT NULL DEFAULT '',
rpm_limit INTEGER,
rpd_limit INTEGER,
tpm_limit INTEGER,
tpd_limit INTEGER,
monthly_token_budget TEXT NOT NULL DEFAULT '',
context_window INTEGER,
enabled INTEGER NOT NULL DEFAULT 1,
UNIQUE(platform, model_id)
);
CREATE TABLE IF NOT EXISTS api_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
platform TEXT NOT NULL,
label TEXT NOT NULL DEFAULT '',
encrypted_key TEXT NOT NULL,
iv TEXT NOT NULL,
auth_tag TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'unknown',
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
last_checked_at TEXT
);
CREATE TABLE IF NOT EXISTS requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
platform TEXT NOT NULL,
model_id TEXT NOT NULL,
status TEXT NOT NULL,
input_tokens INTEGER NOT NULL DEFAULT 0,
output_tokens INTEGER NOT NULL DEFAULT 0,
latency_ms INTEGER NOT NULL DEFAULT 0,
error TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS fallback_config (
id INTEGER PRIMARY KEY AUTOINCREMENT,
model_db_id INTEGER NOT NULL REFERENCES models(id),
priority INTEGER NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
UNIQUE(model_db_id)
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
salt TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id),
token TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_requests_created_at ON requests(created_at);
CREATE INDEX IF NOT EXISTS idx_requests_platform ON requests(platform);
CREATE INDEX IF NOT EXISTS idx_api_keys_platform ON api_keys(platform);
CREATE INDEX IF NOT EXISTS idx_sessions_token ON sessions(token);
`)}async function AJ($){console.log("[DB] Fetching free models from models.dev...");let J=await a0(),Q=t0(J);if(Q.length===0){console.warn("[DB] No free models found from models.dev");return}let W=$.prepare(`
INSERT INTO models (
platform, model_id, display_name, intelligence_rank, speed_rank,
size_label, rpm_limit, rpd_limit, tpm_limit, tpd_limit,
monthly_token_budget, context_window, enabled
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
`),G=$.prepare("INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)"),Y=Q.map((M)=>{let O=s0(M),R=e0(M),D=FJ(M.name);return{...O,intelligenceRank:R.intelligence,speedRank:R.speed,sizeLabel:D}});Y.sort((M,O)=>M.intelligenceRank-O.intelligenceRank),$.transaction(()=>{for(let M of Y)W.run(M.platform,M.modelId,M.displayName,M.intelligenceRank,M.speedRank,M.sizeLabel,null,null,null,null,"",M.contextWindow)})();let H=$.prepare("SELECT id FROM models ORDER BY intelligence_rank ASC").all();$.transaction(()=>{for(let M=0;M<H.length;M++)G.run(H[M].id,M+1)})(),console.log(`[DB] Seeded ${Y.length} free models from models.dev`)}function FJ($){let J=$.toLowerCase();if(J.includes("opus")||J.includes("o1")||J.includes("o3")||J.includes("claude-3.5")||J.includes("claude-4")||J.includes("gpt-4")||J.includes("gemini-pro")||J.includes("deepseek-v4")||J.includes("deepseek-r1"))return"Frontier";if(J.includes("flash")||J.includes("lite")||J.includes("nano")||J.includes("mini")||J.includes("xs")||J.includes("small")||J.includes("8b")||J.includes("1.2b"))return"Small";return"Large"}function wJ($){let Q=$.prepare("SELECT COUNT(*) as cnt FROM users").get().cnt>0,W;if(!Q){W=process.env.ADMIN_PASSWORD||`${Z.randomBytes(3).toString("hex")}-${Z.randomBytes(3).toString("hex")}`;let Y=Z.randomBytes(16).toString("hex"),X=Z.pbkdf2Sync(W,Y,1e5,64,"sha512").toString("hex");$.prepare("INSERT INTO users (username, password_hash, salt) VALUES (?, ?, ?)").run("admin",X,Y),$.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('admin_password', ?)").run(W),console.log(`
Admin user created:`)}else{let G=$.prepare("SELECT value FROM settings WHERE key = 'admin_password'").get();if(G?.value)W=G.value;else{W=`${Z.randomBytes(4).toString("hex")}-${Z.randomBytes(4).toString("hex")}-${Z.randomBytes(4).toString("hex")}`;let Y=Z.randomBytes(16).toString("hex"),X=Z.pbkdf2Sync(W,Y,1e5,64,"sha512").toString("hex");$.prepare("UPDATE users SET password_hash = ?, salt = ? WHERE username = ?").run(X,Y,"admin"),$.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('admin_password', ?)").run(W),console.log(`
Admin password regenerated:`)}}console.log(" Username: admin"),console.log(` Password: ${W}`),console.log(` (set ADMIN_PASSWORD env var on first run to use a custom password)
`)}function vJ($){if(!$.prepare("SELECT value FROM settings WHERE key = 'unified_api_key'").get()){let Q=`freellmapi-${Z.randomBytes(24).toString("hex")}`;$.prepare("INSERT INTO settings (key, value) VALUES ('unified_api_key', ?)").run(Q),console.log(`
Your unified API key: ${Q}
`)}}function Q0(){return A().prepare("SELECT value FROM settings WHERE key = 'unified_api_key'").get().value}function Q1(){let $=A(),J=`freellmapi-${Z.randomBytes(24).toString("hex")}`;return $.prepare("UPDATE settings SET value = ? WHERE key = 'unified_api_key'").run(J),J}class s{async fetchWithTimeout($,J,Q=15000){let W=new AbortController,G=setTimeout(()=>W.abort(),Q);try{return await fetch($,{...J,signal:W.signal})}finally{clearTimeout(G)}}makeId(){return`chatcmpl-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}}var U0="https://generativelanguage.googleapis.com/v1beta";function W1($){try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J;return{value:J}}catch{return{value:$}}}function DJ($){if(typeof $==="string")return $;return JSON.stringify($??{})}function G1($){let J=($??"").toUpperCase();if(!J)return"stop";if(J==="MAX_TOKENS")return"length";if(J==="SAFETY"||J==="RECITATION"||J==="BLOCKLIST"||J==="PROHIBITED_CONTENT"||J==="SPII")return"content_filter";return"stop"}function X1($){if(!$||$.length===0)return;return[{functionDeclarations:$.map((J)=>({name:J.function.name,description:J.function.description,parameters:J.function.parameters}))}]}function Y1($){if(!$)return;if(typeof $==="string")return{functionCallingConfig:{mode:$==="none"?"NONE":$==="required"?"ANY":"AUTO"}};return{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[$.function.name]}}}function H1($){let J=$.filter((G)=>G.role==="system"&&typeof G.content==="string"&&G.content.length>0).map((G)=>G.content),Q=new Map;for(let G of $)for(let Y of G.tool_calls??[])Q.set(Y.id,Y.function.name);return{contents:$.filter((G)=>G.role!=="system").map((G)=>{if(G.role==="assistant"){let Y=[];if(typeof G.content==="string"&&G.content.length>0)Y.push({text:G.content});for(let X of G.tool_calls??[])Y.push({thoughtSignature:X.thought_signature,functionCall:{id:X.id,name:X.function.name,args:W1(X.function.arguments)}});if(Y.length===0)return null;return{role:"model",parts:Y}}if(G.role==="tool"){let Y=G.tool_call_id;if(!Y)return null;let X=G.name??Q.get(Y)??"tool",H=W1(typeof G.content==="string"?G.content:"");return{role:"user",parts:[{functionResponse:{id:Y,name:X,response:H}}]}}return{role:"user",parts:[{text:typeof G.content==="string"?G.content:""}]}}).filter((G)=>G!==null),systemInstruction:J.length>0?{parts:[{text:J.join(`
`)}]}:void 0}}function _1($){let J=[];if(!$)return J;let Q=0;for(let W of $){if(!W.functionCall?.name)continue;let G=W.functionCall.id??`call_${Date.now()}_${Q++}`;J.push({id:G,type:"function",function:{name:W.functionCall.name,arguments:DJ(W.functionCall.args)},thought_signature:W.thoughtSignature})}return J}function M1($){if(!$)return null;let J=$.map((Q)=>Q.text??"").join("");return J.length>0?J:null}class L0 extends s{platform="google";name="Google AI Studio";async chatCompletion($,J,Q,W){let{contents:G,systemInstruction:Y}=H1(J),X={contents:G,generationConfig:{temperature:W?.temperature,maxOutputTokens:W?.max_tokens,topP:W?.top_p},tools:X1(W?.tools),toolConfig:Y1(W?.tool_choice)};if(Y)X.systemInstruction=Y;let H=`${U0}/models/${Q}:generateContent?key=${$}`,_=await this.fetchWithTimeout(H,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)});if(!_.ok){let g=await _.json().catch(()=>({}));throw Error(`Google API error ${_.status}: ${g.error?.message??_.statusText}`)}let M=await _.json(),O=M.candidates?.[0],R=O?.content?.parts,D=_1(R),f=M1(R),K={prompt_tokens:M.usageMetadata?.promptTokenCount??0,completion_tokens:M.usageMetadata?.candidatesTokenCount??0,total_tokens:M.usageMetadata?.totalTokenCount??0};return{id:this.makeId(),object:"chat.completion",created:Math.floor(Date.now()/1000),model:Q,choices:[{index:0,message:{role:"assistant",content:f,...D.length>0?{tool_calls:D}:{}},finish_reason:D.length>0?"tool_calls":G1(O?.finishReason)}],usage:K,_routed_via:{platform:"google",model:Q}}}async*streamChatCompletion($,J,Q,W){let{contents:G,systemInstruction:Y}=H1(J),X={contents:G,generationConfig:{temperature:W?.temperature,maxOutputTokens:W?.max_tokens,topP:W?.top_p},tools:X1(W?.tools),toolConfig:Y1(W?.tool_choice)};if(Y)X.systemInstruction=Y;let H=`${U0}/models/${Q}:streamGenerateContent?alt=sse&key=${$}`,_=await this.fetchWithTimeout(H,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)});if(!_.ok){let T=await _.json().catch(()=>({}));throw Error(`Google API error ${_.status}: ${T.error?.message??_.statusText}`)}let M=_.body?.getReader();if(!M)throw Error("No response body");let O=new TextDecoder,R=this.makeId(),D="",f=!1,K=!1,g=new Set;while(!0){let{done:T,value:A$}=await M.read();if(T)break;D+=O.decode(A$,{stream:!0});let s$=D.split(`
`);D=s$.pop()??"";for(let W$ of s$){let G$=W$.trim();if(!G$||!G$.startsWith("data: "))continue;let e$=G$.slice(6);if(e$==="[DONE]"){if(!f)f=!0,yield{id:R,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:Q,choices:[{index:0,delta:{},finish_reason:K?"tool_calls":"stop"}]};return}let O$=JSON.parse(e$).candidates?.[0],V$=O$?.content?.parts??[],w=M1(V$),L=_1(V$).filter((b)=>{let i=`${b.id}:${b.function.name}:${b.function.arguments}`;if(g.has(i))return!1;return g.add(i),!0});if(w&&w.length>0||L.length>0)K=K||L.length>0,yield{id:R,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:Q,choices:[{index:0,delta:{...w?{content:w}:{},...L.length>0?{tool_calls:L}:{}},finish_reason:null}]};if(O$?.finishReason&&!f){f=!0,yield{id:R,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:Q,choices:[{index:0,delta:{},finish_reason:K?"tool_calls":G1(O$.finishReason)}]};return}}}if(!f)yield{id:R,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:Q,choices:[{index:0,delta:{},finish_reason:K?"tool_calls":"stop"}]}}async validateKey($){let J=await this.fetchWithTimeout(`${U0}/models?key=${$}`,{method:"GET"},1e4);return J.status!==401&&J.status!==403}}class d extends s{platform;name;baseUrl;extraHeaders;validateUrl;timeoutMs;constructor($){super();this.platform=$.platform,this.name=$.name,this.baseUrl=$.baseUrl,this.extraHeaders=$.extraHeaders??{},this.validateUrl=$.validateUrl,this.timeoutMs=$.timeoutMs??15000}async chatCompletion($,J,Q,W){let G=await this.fetchWithTimeout(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json",...this.extraHeaders},body:JSON.stringify({model:Q,messages:J,temperature:W?.temperature,max_tokens:W?.max_tokens,top_p:W?.top_p,tools:W?.tools,tool_choice:W?.tool_choice,parallel_tool_calls:W?.parallel_tool_calls})},this.timeoutMs);if(!G.ok){let X=await G.json().catch(()=>({}));throw Error(`${this.name} API error ${G.status}: ${X.error?.message??G.statusText}`)}let Y=await G.json();return fJ(Y),Y._routed_via={platform:this.platform,model:Q},Y}async*streamChatCompletion($,J,Q,W){let G=await this.fetchWithTimeout(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json",...this.extraHeaders},body:JSON.stringify({model:Q,messages:J,temperature:W?.temperature,max_tokens:W?.max_tokens,top_p:W?.top_p,tools:W?.tools,tool_choice:W?.tool_choice,parallel_tool_calls:W?.parallel_tool_calls,stream:!0})},this.timeoutMs);if(!G.ok){let _=await G.json().catch(()=>({}));throw Error(`${this.name} API error ${G.status}: ${_.error?.message??G.statusText}`)}let Y=G.body?.getReader();if(!Y)throw Error("No response body");let X=new TextDecoder,H="";while(!0){let{done:_,value:M}=await Y.read();if(_)break;H+=X.decode(M,{stream:!0});let O=H.split(`
`);H=O.pop()??"";for(let R of O){let D=R.trim();if(!D||!D.startsWith("data: "))continue;let f=D.slice(6);if(f==="[DONE]")return;try{yield JSON.parse(f)}catch{}}}}async validateKey($){let J=this.validateUrl??`${this.baseUrl}/models`,Q=await this.fetchWithTimeout(J,{method:"GET",headers:{Authorization:`Bearer ${$}`,...this.extraHeaders}},1e4);return Q.status!==401&&Q.status!==403}}function fJ($){for(let J of $.choices??[]){let Q=J.message;if(Array.isArray(Q.content))Q.content=Q.content.map((G)=>typeof G==="string"?G:G.text??"").join("");if(!(Array.isArray(Q.tool_calls)&&Q.tool_calls.length>0)&&(Q.content===""||Q.content==null)&&typeof Q.reasoning_content==="string"&&Q.reasoning_content.length>0)Q.content=Q.reasoning_content}}var S0="https://api.cohere.ai/compatibility/v1";class j0 extends s{platform="cohere";name="Cohere";async chatCompletion($,J,Q,W){let G={model:Q,messages:J,temperature:W?.temperature,max_tokens:W?.max_tokens,top_p:W?.top_p,tools:W?.tools,tool_choice:W?.tool_choice},Y=await this.fetchWithTimeout(`${S0}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json"},body:JSON.stringify(G)});if(!Y.ok){let H=await Y.json().catch(()=>({}));throw Error(`Cohere API error ${Y.status}: ${H.error?.message??Y.statusText}`)}let X=await Y.json();return X._routed_via={platform:"cohere",model:Q},X}async*streamChatCompletion($,J,Q,W){let G={model:Q,messages:J,temperature:W?.temperature,max_tokens:W?.max_tokens,top_p:W?.top_p,tools:W?.tools,tool_choice:W?.tool_choice,stream:!0},Y=await this.fetchWithTimeout(`${S0}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json"},body:JSON.stringify(G)});if(!Y.ok){let M=await Y.json().catch(()=>({}));throw Error(`Cohere API error ${Y.status}: ${M.error?.message??Y.statusText}`)}let X=Y.body?.getReader();if(!X)throw Error("No response body");let H=new TextDecoder,_="";while(!0){let{done:M,value:O}=await X.read();if(M)break;_+=H.decode(O,{stream:!0});let R=_.split(`
`);_=R.pop()??"";for(let D of R){let f=D.trim();if(!f||!f.startsWith("data: "))continue;let K=f.slice(6);if(K==="[DONE]")return;try{yield JSON.parse(K)}catch{}}}}async validateKey($){let J=await this.fetchWithTimeout(`${S0}/models`,{method:"GET",headers:{Authorization:`Bearer ${$}`}},1e4);return J.status!==401&&J.status!==403}}class R0 extends s{platform="cloudflare";name="Cloudflare Workers AI";parseKey($){let J=$.indexOf(":");if(J===-1)throw Error('Cloudflare key must be in format "account_id:api_token"');return{accountId:$.slice(0,J),token:$.slice(J+1)}}normalizeMessages($){return $.map((J)=>J.content===null?{...J,content:""}:J)}async chatCompletion($,J,Q,W){let{accountId:G,token:Y}=this.parseKey($),X=`https://api.cloudflare.com/client/v4/accounts/${G}/ai/v1/chat/completions`,H=await this.fetchWithTimeout(X,{method:"POST",headers:{Authorization:`Bearer ${Y}`,"Content-Type":"application/json"},body:JSON.stringify({model:Q,messages:this.normalizeMessages(J),temperature:W?.temperature,max_tokens:W?.max_tokens,top_p:W?.top_p,tools:W?.tools,tool_choice:W?.tool_choice,parallel_tool_calls:W?.parallel_tool_calls})});if(!H.ok){let M=await H.json().catch(()=>({}));throw Error(`Cloudflare API error ${H.status}: ${M.error?.message??M.errors?.[0]?.message??H.statusText}`)}let _=await H.json();return _._routed_via={platform:"cloudflare",model:Q},_}async*streamChatCompletion($,J,Q,W){let{accountId:G,token:Y}=this.parseKey($),X=`https://api.cloudflare.com/client/v4/accounts/${G}/ai/v1/chat/completions`,H=await this.fetchWithTimeout(X,{method:"POST",headers:{Authorization:`Bearer ${Y}`,"Content-Type":"application/json"},body:JSON.stringify({model:Q,messages:this.normalizeMessages(J),temperature:W?.temperature,max_tokens:W?.max_tokens,top_p:W?.top_p,tools:W?.tools,tool_choice:W?.tool_choice,parallel_tool_calls:W?.parallel_tool_calls,stream:!0})});if(!H.ok){let R=await H.json().catch(()=>({}));throw Error(`Cloudflare API error ${H.status}: ${R.error?.message??R.errors?.[0]?.message??H.statusText}`)}let _=H.body?.getReader();if(!_)throw Error("No response body");let M=new TextDecoder,O="";while(!0){let{done:R,value:D}=await _.read();if(R)break;O+=M.decode(D,{stream:!0});let f=O.split(`
`);O=f.pop()??"";for(let K of f){let g=K.trim();if(!g||!g.startsWith("data: "))continue;let T=g.slice(6);if(T==="[DONE]")return;try{yield JSON.parse(T)}catch{}}}}async validateKey($){let{token:J}=this.parseKey($),Q=await this.fetchWithTimeout("https://api.cloudflare.com/client/v4/user/tokens/verify",{method:"GET",headers:{Authorization:`Bearer ${J}`}},1e4);if(Q.status===401||Q.status===403)return!1;if(!Q.ok)return!0;let W=await Q.json();return W.success===!0&&W.result?.status==="active"}}var q0=new Map;function y($){q0.set($.platform,$)}y(new L0);y(new d({platform:"groq",name:"Groq",baseUrl:"https://api.groq.com/openai/v1"}));y(new d({platform:"cerebras",name:"Cerebras",baseUrl:"https://api.cerebras.ai/v1"}));y(new d({platform:"sambanova",name:"SambaNova",baseUrl:"https://api.sambanova.ai/v1"}));y(new d({platform:"nvidia",name:"NVIDIA NIM",baseUrl:"https://integrate.api.nvidia.com/v1"}));y(new d({platform:"mistral",name:"Mistral",baseUrl:"https://api.mistral.ai/v1"}));y(new d({platform:"openrouter",name:"OpenRouter",baseUrl:"https://openrouter.ai/api/v1",extraHeaders:{"HTTP-Referer":"http://localhost:3001","X-Title":"FreeLLMAPI"}}));y(new d({platform:"github",name:"GitHub Models",baseUrl:"https://models.github.ai/inference"}));y(new j0);y(new R0);y(new d({platform:"zhipu",name:"Zhipu AI",baseUrl:"https://open.bigmodel.cn/api/paas/v4"}));function W0($){return q0.get($)}function G0($){return q0.has($)}var B1=300000,KJ=3,A0=new Map;async function F0($){let J=A(),Q=J.prepare("SELECT * FROM api_keys WHERE id = ?").get($);if(!Q)return"error";let W=W0(Q.platform);if(!W)return"error";try{let G=w$(Q.encrypted_key,Q.iv,Q.auth_tag),Y=await W.validateKey(G),X=Y?"healthy":"invalid";if(J.prepare("UPDATE api_keys SET status = ?, last_checked_at = datetime('now') WHERE id = ?").run(X,$),Y)A0.delete($);else{let H=(A0.get($)??0)+1;if(A0.set($,H),H>=KJ)J.prepare("UPDATE api_keys SET enabled = 0 WHERE id = ?").run($),console.log(`[Health] Auto-disabled key ${$} after ${H} consecutive failures`)}return X}catch(G){return console.error(`[Health] Key ${$} transport error:`,G.message),J.prepare("UPDATE api_keys SET status = ?, last_checked_at = datetime('now') WHERE id = ?").run("error",$),"error"}}async function w0(){let J=A().prepare("SELECT id, platform FROM api_keys WHERE enabled = 1").all();console.log(`[Health] Checking ${J.length} keys...`);for(let Q of J)await F0(Q.id);console.log("[Health] Check complete.")}var O1=null;function V1(){if(O1)return;console.log(`[Health] Starting health checker (every ${B1/1000}s)`),O1=setInterval(()=>{w0().catch(($)=>console.error("[Health] Check failed:",$))},B1)}import e from"fs";import v$ from"path";import{fileURLToPath as CJ}from"url";var bJ=v$.dirname(CJ(import.meta.url)),u$=v$.resolve(bJ,"../../data/freeapi.db"),z$=process.env.HF_TOKEN,E$=process.env.HF_DATASET_ID,D0=process.env.BACKUP_ENABLED==="true",v0=Number(process.env.BACKUP_INTERVAL_MS??86400000),E1="backup_",N1=".db";function h($){console.log(`[Backup] ${$}`)}function U1($){return $.filter((J)=>J.type==="file"&&J.path.startsWith(E1)&&J.path.endsWith(N1)).map((J)=>J.path).sort()}function kJ($){let J=$.match(/backup_(\d{8})_(\d{6})\.db/);if(!J)return 0;let[,Q,W]=J;return new Date(`${Q.slice(0,4)}-${Q.slice(4,6)}-${Q.slice(6,8)}T${W.slice(0,2)}:${W.slice(2,4)}:${W.slice(4,6)}`).getTime()}async function L1($){if(!D0||!z$||!E$)return h("Backup not configured, skipping restore."),!1;let J=$??u$;try{h("Checking for remote backups...");let Q=`https://huggingface.co/api/datasets/${E$}/tree/main`,W=await fetch(Q,{headers:{Authorization:`Bearer ${z$}`}});if(!W.ok){if(W.status===404)return h("Dataset not found. Skipping restore."),!1;throw Error(`Failed to list dataset files: ${W.status} ${W.statusText}`)}let G=await W.json(),Y=U1(G);if(Y.length===0)return h("No backups found in dataset."),!1;let X=Y[Y.length-1];h(`Found latest backup: ${X}`);let H=v$.dirname(J);if(!e.existsSync(H))e.mkdirSync(H,{recursive:!0});if(e.existsSync(J)){let R=v$.join(H,`local_before_restore_${Date.now()}.db`);e.copyFileSync(J,R),h(`Local DB backed up to ${R}`)}let _=`https://huggingface.co/datasets/${E$}/resolve/main/${X}`,M=await fetch(_,{headers:{Authorization:`Bearer ${z$}`}});if(!M.ok)throw Error(`Failed to download backup: ${M.status}`);let O=Buffer.from(await M.arrayBuffer());return e.writeFileSync(J,O),h(`Restored ${X} to ${J} (${O.length} bytes)`),!0}catch(Q){return console.error("[Backup] Restore failed:",Q),!1}}async function z1(){if(!D0||!z$||!E$)return h("Backup not configured, skipping backup."),!1;if(!e.existsSync(u$))return h("Local DB not found, skipping backup."),!1;try{let{Database:$}=z0("bun:sqlite"),J=new $(u$);J.exec("PRAGMA wal_checkpoint(FULL)"),J.close();let Q=new Date,W=Q.toISOString().slice(0,10).replace(/-/g,""),G=Q.toTimeString().slice(0,8).replace(/:/g,""),Y=`${E1}${W}_${G}${N1}`;h(`Creating backup: ${Y}`);let X=v$.join(v$.dirname(u$),`.tmp_backup_${Date.now()}.db`);e.copyFileSync(u$,X);let H=e.readFileSync(X),_=`https://huggingface.co/api/datasets/${E$}/upload/main/${Y}`,M=await fetch(_,{method:"POST",headers:{Authorization:`Bearer ${z$}`,"Content-Type":"application/octet-stream"},body:H});try{e.unlinkSync(X)}catch{}if(!M.ok){let O=await M.text();throw Error(`Upload failed: ${M.status} ${M.statusText} - ${O}`)}return h(`Uploaded ${Y} successfully.`),await PJ(),!0}catch($){return console.error("[Backup] Backup creation failed:",$),!1}}async function PJ(){try{let $=`https://huggingface.co/api/datasets/${E$}/tree/main`,J=await fetch($,{headers:{Authorization:`Bearer ${z$}`}});if(!J.ok)return;let Q=await J.json(),W=U1(Q);if(W.length<=3)return;let G=W.map((_)=>({path:_,ts:kJ(_)})).sort((_,M)=>_.ts-M.ts),Y=G.slice(0,G.length-3).map((_)=>_.path),X=`https://huggingface.co/api/datasets/${E$}/commit/main`,H=await fetch(X,{method:"POST",headers:{Authorization:`Bearer ${z$}`,"Content-Type":"application/json"},body:JSON.stringify({summary:"Cleanup old backups (keep last 3)",deletedFiles:Y})});if(H.ok)h(`Deleted ${Y.length} old backups: ${Y.join(", ")}`);else{let _=await H.text();h(`Failed to delete old backups: ${H.status} ${_}`)}}catch($){console.error("[Backup] Cleanup failed:",$)}}function S1(){if(!D0){h("Backup scheduler disabled.");return}h(`Backup scheduler started (interval: ${v0}ms)`),setTimeout(()=>{z1().catch(console.error),setInterval(()=>z1().catch(console.error),v0)},v0)}async function f0($){try{let J=await $.text();if(!J)return{};return JSON.parse(J)}catch(J){throw Error("Invalid JSON")}}function j($,J=200){return new Response(JSON.stringify($),{status:J,headers:{"Content-Type":"application/json"}})}var N={};zJ(N,{void:()=>U4,util:()=>v,unknown:()=>E4,union:()=>R4,undefined:()=>O4,tuple:()=>F4,transformer:()=>h4,symbol:()=>B4,string:()=>f1,strictObject:()=>j4,setErrorMap:()=>gJ,set:()=>D4,record:()=>w4,quotelessJson:()=>hJ,promise:()=>P4,preprocess:()=>T4,pipeline:()=>x4,ostring:()=>Z4,optional:()=>I4,onumber:()=>y4,oboolean:()=>l4,objectUtil:()=>K0,object:()=>S4,number:()=>K1,nullable:()=>g4,null:()=>V4,never:()=>N4,nativeEnum:()=>k4,nan:()=>H4,map:()=>v4,makeIssue:()=>n$,literal:()=>C4,lazy:()=>K4,late:()=>X4,isValid:()=>X$,isDirty:()=>Y0,isAsync:()=>f$,isAborted:()=>X0,intersection:()=>A4,instanceof:()=>Y4,getParsedType:()=>o,getErrorMap:()=>D$,function:()=>f4,enum:()=>b4,effect:()=>h4,discriminatedUnion:()=>q4,defaultErrorMap:()=>$$,datetimeRegex:()=>w1,date:()=>M4,custom:()=>D1,coerce:()=>m4,boolean:()=>C1,bigint:()=>_4,array:()=>L4,any:()=>z4,addIssueToContext:()=>z,ZodVoid:()=>i$,ZodUnknown:()=>Y$,ZodUnion:()=>h$,ZodUndefined:()=>k$,ZodType:()=>F,ZodTuple:()=>a,ZodTransformer:()=>n,ZodSymbol:()=>p$,ZodString:()=>l,ZodSet:()=>S$,ZodSchema:()=>F,ZodRecord:()=>d$,ZodReadonly:()=>l$,ZodPromise:()=>j$,ZodPipeline:()=>a$,ZodParsedType:()=>V,ZodOptional:()=>c,ZodObject:()=>C,ZodNumber:()=>H$,ZodNullable:()=>Q$,ZodNull:()=>P$,ZodNever:()=>r,ZodNativeEnum:()=>x$,ZodNaN:()=>r$,ZodMap:()=>o$,ZodLiteral:()=>T$,ZodLazy:()=>g$,ZodIssueCode:()=>B,ZodIntersection:()=>I$,ZodFunction:()=>C$,ZodFirstPartyTypeKind:()=>S,ZodError:()=>I,ZodEnum:()=>M$,ZodEffects:()=>n,ZodDiscriminatedUnion:()=>H0,ZodDefault:()=>Z$,ZodDate:()=>U$,ZodCatch:()=>y$,ZodBranded:()=>_0,ZodBoolean:()=>b$,ZodBigInt:()=>_$,ZodArray:()=>m,ZodAny:()=>L$,Schema:()=>F,ParseStatus:()=>k,OK:()=>P,NEVER:()=>c4,INVALID:()=>U,EMPTY_PATH:()=>TJ,DIRTY:()=>N$,BRAND:()=>G4});var v;(function($){$.assertEqual=(G)=>{};function J(G){}$.assertIs=J;function Q(G){throw Error()}$.assertNever=Q,$.arrayToEnum=(G)=>{let Y={};for(let X of G)Y[X]=X;return Y},$.getValidEnumValues=(G)=>{let Y=$.objectKeys(G).filter((H)=>typeof G[G[H]]!=="number"),X={};for(let H of Y)X[H]=G[H];return $.objectValues(X)},$.objectValues=(G)=>{return $.objectKeys(G).map(function(Y){return G[Y]})},$.objectKeys=typeof Object.keys==="function"?(G)=>Object.keys(G):(G)=>{let Y=[];for(let X in G)if(Object.prototype.hasOwnProperty.call(G,X))Y.push(X);return Y},$.find=(G,Y)=>{for(let X of G)if(Y(X))return X;return},$.isInteger=typeof Number.isInteger==="function"?(G)=>Number.isInteger(G):(G)=>typeof G==="number"&&Number.isFinite(G)&&Math.floor(G)===G;function W(G,Y=" | "){return G.map((X)=>typeof X==="string"?`'${X}'`:X).join(Y)}$.joinValues=W,$.jsonStringifyReplacer=(G,Y)=>{if(typeof Y==="bigint")return Y.toString();return Y}})(v||(v={}));var K0;(function($){$.mergeShapes=(J,Q)=>{return{...J,...Q}}})(K0||(K0={}));var V=v.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),o=($)=>{switch(typeof $){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN($)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":if(Array.isArray($))return V.array;if($===null)return V.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return V.promise;if(typeof Map<"u"&&$ instanceof Map)return V.map;if(typeof Set<"u"&&$ instanceof Set)return V.set;if(typeof Date<"u"&&$ instanceof Date)return V.date;return V.object;default:return V.unknown}};var B=v.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"]),hJ=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class I extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(Q)=>{this.issues=[...this.issues,Q]},this.addIssues=(Q=[])=>{this.issues=[...this.issues,...Q]};let J=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,J);else this.__proto__=J;this.name="ZodError",this.issues=$}format($){let J=$||function(G){return G.message},Q={_errors:[]},W=(G)=>{for(let Y of G.issues)if(Y.code==="invalid_union")Y.unionErrors.map(W);else if(Y.code==="invalid_return_type")W(Y.returnTypeError);else if(Y.code==="invalid_arguments")W(Y.argumentsError);else if(Y.path.length===0)Q._errors.push(J(Y));else{let X=Q,H=0;while(H<Y.path.length){let _=Y.path[H];if(H!==Y.path.length-1)X[_]=X[_]||{_errors:[]};else X[_]=X[_]||{_errors:[]},X[_]._errors.push(J(Y));X=X[_],H++}}};return W(this),Q}static assert($){if(!($ instanceof I))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(J)=>J.message){let J={},Q=[];for(let W of this.issues)if(W.path.length>0){let G=W.path[0];J[G]=J[G]||[],J[G].push($(W))}else Q.push($(W));return{formErrors:Q,fieldErrors:J}}get formErrors(){return this.flatten()}}I.create=($)=>{return new I($)};var IJ=($,J)=>{let Q;switch($.code){case B.invalid_type:if($.received===V.undefined)Q="Required";else Q=`Expected ${$.expected}, received ${$.received}`;break;case B.invalid_literal:Q=`Invalid literal value, expected ${JSON.stringify($.expected,v.jsonStringifyReplacer)}`;break;case B.unrecognized_keys:Q=`Unrecognized key(s) in object: ${v.joinValues($.keys,", ")}`;break;case B.invalid_union:Q="Invalid input";break;case B.invalid_union_discriminator:Q=`Invalid discriminator value. Expected ${v.joinValues($.options)}`;break;case B.invalid_enum_value:Q=`Invalid enum value. Expected ${v.joinValues($.options)}, received '${$.received}'`;break;case B.invalid_arguments:Q="Invalid function arguments";break;case B.invalid_return_type:Q="Invalid function return type";break;case B.invalid_date:Q="Invalid date";break;case B.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(Q=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")Q=`${Q} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)Q=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)Q=`Invalid input: must end with "${$.validation.endsWith}"`;else v.assertNever($.validation);else if($.validation!=="regex")Q=`Invalid ${$.validation}`;else Q="Invalid";break;case B.too_small:if($.type==="array")Q=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")Q=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")Q=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")Q=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")Q=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else Q="Invalid input";break;case B.too_big:if($.type==="array")Q=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")Q=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")Q=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")Q=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")Q=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else Q="Invalid input";break;case B.custom:Q="Invalid input";break;case B.invalid_intersection_types:Q="Intersection results could not be merged";break;case B.not_multiple_of:Q=`Number must be a multiple of ${$.multipleOf}`;break;case B.not_finite:Q="Number must be finite";break;default:Q=J.defaultError,v.assertNever($)}return{message:Q}},$$=IJ;var j1=$$;function gJ($){j1=$}function D$(){return j1}var n$=($)=>{let{data:J,path:Q,errorMaps:W,issueData:G}=$,Y=[...Q,...G.path||[]],X={...G,path:Y};if(G.message!==void 0)return{...G,path:Y,message:G.message};let H="",_=W.filter((M)=>!!M).slice().reverse();for(let M of _)H=M(X,{data:J,defaultError:H}).message;return{...G,path:Y,message:H}},TJ=[];function z($,J){let Q=D$(),W=n$({issueData:J,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,Q,Q===$$?void 0:$$].filter((G)=>!!G)});$.common.issues.push(W)}class k{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,J){let Q=[];for(let W of J){if(W.status==="aborted")return U;if(W.status==="dirty")$.dirty();Q.push(W.value)}return{status:$.value,value:Q}}static async mergeObjectAsync($,J){let Q=[];for(let W of J){let G=await W.key,Y=await W.value;Q.push({key:G,value:Y})}return k.mergeObjectSync($,Q)}static mergeObjectSync($,J){let Q={};for(let W of J){let{key:G,value:Y}=W;if(G.status==="aborted")return U;if(Y.status==="aborted")return U;if(G.status==="dirty")$.dirty();if(Y.status==="dirty")$.dirty();if(G.value!=="__proto__"&&(typeof Y.value<"u"||W.alwaysSet))Q[G.value]=Y.value}return{status:$.value,value:Q}}}var U=Object.freeze({status:"aborted"}),N$=($)=>({status:"dirty",value:$}),P=($)=>({status:"valid",value:$}),X0=($)=>$.status==="aborted",Y0=($)=>$.status==="dirty",X$=($)=>$.status==="valid",f$=($)=>typeof Promise<"u"&&$ instanceof Promise;var E;(function($){$.errToObj=(J)=>typeof J==="string"?{message:J}:J||{},$.toString=(J)=>typeof J==="string"?J:J?.message})(E||(E={}));class u{constructor($,J,Q,W){this._cachedPath=[],this.parent=$,this.data=J,this._path=Q,this._key=W}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 R1=($,J)=>{if(X$(J))return{success:!0,data:J.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let Q=new I($.common.issues);return this._error=Q,this._error}}}};function q($){if(!$)return{};let{errorMap:J,invalid_type_error:Q,required_error:W,description:G}=$;if(J&&(Q||W))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(J)return{errorMap:J,description:G};return{errorMap:(X,H)=>{let{message:_}=$;if(X.code==="invalid_enum_value")return{message:_??H.defaultError};if(typeof H.data>"u")return{message:_??W??H.defaultError};if(X.code!=="invalid_type")return{message:H.defaultError};return{message:_??Q??H.defaultError}},description:G}}class F{get description(){return this._def.description}_getType($){return o($.data)}_getOrReturnCtx($,J){return J||{common:$.parent.common,data:$.data,parsedType:o($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new k,ctx:{common:$.parent.common,data:$.data,parsedType:o($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let J=this._parse($);if(f$(J))throw Error("Synchronous parse encountered promise.");return J}_parseAsync($){let J=this._parse($);return Promise.resolve(J)}parse($,J){let Q=this.safeParse($,J);if(Q.success)return Q.data;throw Q.error}safeParse($,J){let Q={common:{issues:[],async:J?.async??!1,contextualErrorMap:J?.errorMap},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:o($)},W=this._parseSync({data:$,path:Q.path,parent:Q});return R1(Q,W)}"~validate"($){let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:o($)};if(!this["~standard"].async)try{let Q=this._parseSync({data:$,path:[],parent:J});return X$(Q)?{value:Q.value}:{issues:J.common.issues}}catch(Q){if(Q?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;J.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:J}).then((Q)=>X$(Q)?{value:Q.value}:{issues:J.common.issues})}async parseAsync($,J){let Q=await this.safeParseAsync($,J);if(Q.success)return Q.data;throw Q.error}async safeParseAsync($,J){let Q={common:{issues:[],contextualErrorMap:J?.errorMap,async:!0},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:o($)},W=this._parse({data:$,path:Q.path,parent:Q}),G=await(f$(W)?W:Promise.resolve(W));return R1(Q,G)}refine($,J){let Q=(W)=>{if(typeof J==="string"||typeof J>"u")return{message:J};else if(typeof J==="function")return J(W);else return J};return this._refinement((W,G)=>{let Y=$(W),X=()=>G.addIssue({code:B.custom,...Q(W)});if(typeof Promise<"u"&&Y instanceof Promise)return Y.then((H)=>{if(!H)return X(),!1;else return!0});if(!Y)return X(),!1;else return!0})}refinement($,J){return this._refinement((Q,W)=>{if(!$(Q))return W.addIssue(typeof J==="function"?J(Q,W):J),!1;else return!0})}_refinement($){return new n({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._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:(J)=>this["~validate"](J)}}optional(){return c.create(this,this._def)}nullable(){return Q$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return m.create(this)}promise(){return j$.create(this,this._def)}or($){return h$.create([this,$],this._def)}and($){return I$.create(this,$,this._def)}transform($){return new n({...q(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:$}})}default($){let J=typeof $==="function"?$:()=>$;return new Z$({...q(this._def),innerType:this,defaultValue:J,typeName:S.ZodDefault})}brand(){return new _0({typeName:S.ZodBranded,type:this,...q(this._def)})}catch($){let J=typeof $==="function"?$:()=>$;return new y$({...q(this._def),innerType:this,catchValue:J,typeName:S.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return a$.create(this,$)}readonly(){return l$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var xJ=/^c[^\s-]{8,}$/i,ZJ=/^[0-9a-z]+$/,yJ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,lJ=/^[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,mJ=/^[a-z0-9_-]{21}$/i,cJ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,uJ=/^[-+]?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)?)??$/,nJ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,pJ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",C0,iJ=/^(?:(?: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])$/,dJ=/^(?:(?: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])$/,oJ=/^(([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]))$/,rJ=/^(([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])$/,aJ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tJ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,A1="((\\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])))",sJ=new RegExp(`^${A1}$`);function F1($){let J="[0-5]\\d";if($.precision)J=`${J}\\.\\d{${$.precision}}`;else if($.precision==null)J=`${J}(\\.\\d+)?`;let Q=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${J})${Q}`}function eJ($){return new RegExp(`^${F1($)}$`)}function w1($){let J=`${A1}T${F1($)}`,Q=[];if(Q.push($.local?"Z?":"Z"),$.offset)Q.push("([+-]\\d{2}:?\\d{2})");return J=`${J}(${Q.join("|")})`,new RegExp(`^${J}$`)}function $4($,J){if((J==="v4"||!J)&&iJ.test($))return!0;if((J==="v6"||!J)&&oJ.test($))return!0;return!1}function J4($,J){if(!cJ.test($))return!1;try{let[Q]=$.split(".");if(!Q)return!1;let W=Q.replace(/-/g,"+").replace(/_/g,"/").padEnd(Q.length+(4-Q.length%4)%4,"="),G=JSON.parse(atob(W));if(typeof G!=="object"||G===null)return!1;if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(J&&G.alg!==J)return!1;return!0}catch{return!1}}function Q4($,J){if((J==="v4"||!J)&&dJ.test($))return!0;if((J==="v6"||!J)&&rJ.test($))return!0;return!1}class l extends F{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==V.string){let G=this._getOrReturnCtx($);return z(G,{code:B.invalid_type,expected:V.string,received:G.parsedType}),U}let Q=new k,W=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.length<G.value)W=this._getOrReturnCtx($,W),z(W,{code:B.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),Q.dirty()}else if(G.kind==="max"){if($.data.length>G.value)W=this._getOrReturnCtx($,W),z(W,{code:B.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),Q.dirty()}else if(G.kind==="length"){let Y=$.data.length>G.value,X=$.data.length<G.value;if(Y||X){if(W=this._getOrReturnCtx($,W),Y)z(W,{code:B.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});else if(X)z(W,{code:B.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});Q.dirty()}}else if(G.kind==="email"){if(!nJ.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"email",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="emoji"){if(!C0)C0=new RegExp(pJ,"u");if(!C0.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"emoji",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="uuid"){if(!lJ.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"uuid",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="nanoid"){if(!mJ.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"nanoid",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="cuid"){if(!xJ.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"cuid",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="cuid2"){if(!ZJ.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"cuid2",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="ulid"){if(!yJ.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"ulid",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="url")try{new URL($.data)}catch{W=this._getOrReturnCtx($,W),z(W,{validation:"url",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="regex"){if(G.regex.lastIndex=0,!G.regex.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"regex",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="trim")$.data=$.data.trim();else if(G.kind==="includes"){if(!$.data.includes(G.value,G.position))W=this._getOrReturnCtx($,W),z(W,{code:B.invalid_string,validation:{includes:G.value,position:G.position},message:G.message}),Q.dirty()}else if(G.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(G.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(G.kind==="startsWith"){if(!$.data.startsWith(G.value))W=this._getOrReturnCtx($,W),z(W,{code:B.invalid_string,validation:{startsWith:G.value},message:G.message}),Q.dirty()}else if(G.kind==="endsWith"){if(!$.data.endsWith(G.value))W=this._getOrReturnCtx($,W),z(W,{code:B.invalid_string,validation:{endsWith:G.value},message:G.message}),Q.dirty()}else if(G.kind==="datetime"){if(!w1(G).test($.data))W=this._getOrReturnCtx($,W),z(W,{code:B.invalid_string,validation:"datetime",message:G.message}),Q.dirty()}else if(G.kind==="date"){if(!sJ.test($.data))W=this._getOrReturnCtx($,W),z(W,{code:B.invalid_string,validation:"date",message:G.message}),Q.dirty()}else if(G.kind==="time"){if(!eJ(G).test($.data))W=this._getOrReturnCtx($,W),z(W,{code:B.invalid_string,validation:"time",message:G.message}),Q.dirty()}else if(G.kind==="duration"){if(!uJ.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"duration",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="ip"){if(!$4($.data,G.version))W=this._getOrReturnCtx($,W),z(W,{validation:"ip",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="jwt"){if(!J4($.data,G.alg))W=this._getOrReturnCtx($,W),z(W,{validation:"jwt",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="cidr"){if(!Q4($.data,G.version))W=this._getOrReturnCtx($,W),z(W,{validation:"cidr",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="base64"){if(!aJ.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"base64",code:B.invalid_string,message:G.message}),Q.dirty()}else if(G.kind==="base64url"){if(!tJ.test($.data))W=this._getOrReturnCtx($,W),z(W,{validation:"base64url",code:B.invalid_string,message:G.message}),Q.dirty()}else v.assertNever(G);return{status:Q.value,value:$.data}}_regex($,J,Q){return this.refinement((W)=>$.test(W),{validation:J,code:B.invalid_string,...E.errToObj(Q)})}_addCheck($){return new l({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...E.errToObj($)})}url($){return this._addCheck({kind:"url",...E.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...E.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...E.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...E.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...E.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...E.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...E.errToObj($)})}base64($){return this._addCheck({kind:"base64",...E.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...E.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...E.errToObj($)})}ip($){return this._addCheck({kind:"ip",...E.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...E.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...E.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...E.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...E.errToObj($)})}regex($,J){return this._addCheck({kind:"regex",regex:$,...E.errToObj(J)})}includes($,J){return this._addCheck({kind:"includes",value:$,position:J?.position,...E.errToObj(J?.message)})}startsWith($,J){return this._addCheck({kind:"startsWith",value:$,...E.errToObj(J)})}endsWith($,J){return this._addCheck({kind:"endsWith",value:$,...E.errToObj(J)})}min($,J){return this._addCheck({kind:"min",value:$,...E.errToObj(J)})}max($,J){return this._addCheck({kind:"max",value:$,...E.errToObj(J)})}length($,J){return this._addCheck({kind:"length",value:$,...E.errToObj(J)})}nonempty($){return this.min(1,E.errToObj($))}trim(){return new l({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new l({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new l({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxLength(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}}l.create=($)=>{return new l({checks:[],typeName:S.ZodString,coerce:$?.coerce??!1,...q($)})};function W4($,J){let Q=($.toString().split(".")[1]||"").length,W=(J.toString().split(".")[1]||"").length,G=Q>W?Q:W,Y=Number.parseInt($.toFixed(G).replace(".","")),X=Number.parseInt(J.toFixed(G).replace(".",""));return Y%X/10**G}class H$ extends F{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==V.number){let G=this._getOrReturnCtx($);return z(G,{code:B.invalid_type,expected:V.number,received:G.parsedType}),U}let Q=void 0,W=new k;for(let G of this._def.checks)if(G.kind==="int"){if(!v.isInteger($.data))Q=this._getOrReturnCtx($,Q),z(Q,{code:B.invalid_type,expected:"integer",received:"float",message:G.message}),W.dirty()}else if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)Q=this._getOrReturnCtx($,Q),z(Q,{code:B.too_small,minimum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),W.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)Q=this._getOrReturnCtx($,Q),z(Q,{code:B.too_big,maximum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),W.dirty()}else if(G.kind==="multipleOf"){if(W4($.data,G.value)!==0)Q=this._getOrReturnCtx($,Q),z(Q,{code:B.not_multiple_of,multipleOf:G.value,message:G.message}),W.dirty()}else if(G.kind==="finite"){if(!Number.isFinite($.data))Q=this._getOrReturnCtx($,Q),z(Q,{code:B.not_finite,message:G.message}),W.dirty()}else v.assertNever(G);return{status:W.value,value:$.data}}gte($,J){return this.setLimit("min",$,!0,E.toString(J))}gt($,J){return this.setLimit("min",$,!1,E.toString(J))}lte($,J){return this.setLimit("max",$,!0,E.toString(J))}lt($,J){return this.setLimit("max",$,!1,E.toString(J))}setLimit($,J,Q,W){return new H$({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:E.toString(W)}]})}_addCheck($){return new H$({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:E.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:E.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:E.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:E.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:E.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:E.toString(J)})}finite($){return this._addCheck({kind:"finite",message:E.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:E.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:E.toString($)})}get minValue(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxValue(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&v.isInteger($.value))}get isFinite(){let $=null,J=null;for(let Q of this._def.checks)if(Q.kind==="finite"||Q.kind==="int"||Q.kind==="multipleOf")return!0;else if(Q.kind==="min"){if(J===null||Q.value>J)J=Q.value}else if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return Number.isFinite(J)&&Number.isFinite($)}}H$.create=($)=>{return new H$({checks:[],typeName:S.ZodNumber,coerce:$?.coerce||!1,...q($)})};class _$ extends F{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==V.bigint)return this._getInvalidInput($);let Q=void 0,W=new k;for(let G of this._def.checks)if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)Q=this._getOrReturnCtx($,Q),z(Q,{code:B.too_small,type:"bigint",minimum:G.value,inclusive:G.inclusive,message:G.message}),W.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)Q=this._getOrReturnCtx($,Q),z(Q,{code:B.too_big,type:"bigint",maximum:G.value,inclusive:G.inclusive,message:G.message}),W.dirty()}else if(G.kind==="multipleOf"){if($.data%G.value!==BigInt(0))Q=this._getOrReturnCtx($,Q),z(Q,{code:B.not_multiple_of,multipleOf:G.value,message:G.message}),W.dirty()}else v.assertNever(G);return{status:W.value,value:$.data}}_getInvalidInput($){let J=this._getOrReturnCtx($);return z(J,{code:B.invalid_type,expected:V.bigint,received:J.parsedType}),U}gte($,J){return this.setLimit("min",$,!0,E.toString(J))}gt($,J){return this.setLimit("min",$,!1,E.toString(J))}lte($,J){return this.setLimit("max",$,!0,E.toString(J))}lt($,J){return this.setLimit("max",$,!1,E.toString(J))}setLimit($,J,Q,W){return new _$({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:E.toString(W)}]})}_addCheck($){return new _$({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:E.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:E.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:E.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:E.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:E.toString(J)})}get minValue(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxValue(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}}_$.create=($)=>{return new _$({checks:[],typeName:S.ZodBigInt,coerce:$?.coerce??!1,...q($)})};class b$ extends F{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==V.boolean){let Q=this._getOrReturnCtx($);return z(Q,{code:B.invalid_type,expected:V.boolean,received:Q.parsedType}),U}return P($.data)}}b$.create=($)=>{return new b$({typeName:S.ZodBoolean,coerce:$?.coerce||!1,...q($)})};class U$ extends F{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==V.date){let G=this._getOrReturnCtx($);return z(G,{code:B.invalid_type,expected:V.date,received:G.parsedType}),U}if(Number.isNaN($.data.getTime())){let G=this._getOrReturnCtx($);return z(G,{code:B.invalid_date}),U}let Q=new k,W=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.getTime()<G.value)W=this._getOrReturnCtx($,W),z(W,{code:B.too_small,message:G.message,inclusive:!0,exact:!1,minimum:G.value,type:"date"}),Q.dirty()}else if(G.kind==="max"){if($.data.getTime()>G.value)W=this._getOrReturnCtx($,W),z(W,{code:B.too_big,message:G.message,inclusive:!0,exact:!1,maximum:G.value,type:"date"}),Q.dirty()}else v.assertNever(G);return{status:Q.value,value:new Date($.data.getTime())}}_addCheck($){return new U$({...this._def,checks:[...this._def.checks,$]})}min($,J){return this._addCheck({kind:"min",value:$.getTime(),message:E.toString(J)})}max($,J){return this._addCheck({kind:"max",value:$.getTime(),message:E.toString(J)})}get minDate(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $!=null?new Date($):null}}U$.create=($)=>{return new U$({checks:[],coerce:$?.coerce||!1,typeName:S.ZodDate,...q($)})};class p$ extends F{_parse($){if(this._getType($)!==V.symbol){let Q=this._getOrReturnCtx($);return z(Q,{code:B.invalid_type,expected:V.symbol,received:Q.parsedType}),U}return P($.data)}}p$.create=($)=>{return new p$({typeName:S.ZodSymbol,...q($)})};class k$ extends F{_parse($){if(this._getType($)!==V.undefined){let Q=this._getOrReturnCtx($);return z(Q,{code:B.invalid_type,expected:V.undefined,received:Q.parsedType}),U}return P($.data)}}k$.create=($)=>{return new k$({typeName:S.ZodUndefined,...q($)})};class P$ extends F{_parse($){if(this._getType($)!==V.null){let Q=this._getOrReturnCtx($);return z(Q,{code:B.invalid_type,expected:V.null,received:Q.parsedType}),U}return P($.data)}}P$.create=($)=>{return new P$({typeName:S.ZodNull,...q($)})};class L$ extends F{constructor(){super(...arguments);this._any=!0}_parse($){return P($.data)}}L$.create=($)=>{return new L$({typeName:S.ZodAny,...q($)})};class Y$ extends F{constructor(){super(...arguments);this._unknown=!0}_parse($){return P($.data)}}Y$.create=($)=>{return new Y$({typeName:S.ZodUnknown,...q($)})};class r extends F{_parse($){let J=this._getOrReturnCtx($);return z(J,{code:B.invalid_type,expected:V.never,received:J.parsedType}),U}}r.create=($)=>{return new r({typeName:S.ZodNever,...q($)})};class i$ extends F{_parse($){if(this._getType($)!==V.undefined){let Q=this._getOrReturnCtx($);return z(Q,{code:B.invalid_type,expected:V.void,received:Q.parsedType}),U}return P($.data)}}i$.create=($)=>{return new i$({typeName:S.ZodVoid,...q($)})};class m extends F{_parse($){let{ctx:J,status:Q}=this._processInputParams($),W=this._def;if(J.parsedType!==V.array)return z(J,{code:B.invalid_type,expected:V.array,received:J.parsedType}),U;if(W.exactLength!==null){let Y=J.data.length>W.exactLength.value,X=J.data.length<W.exactLength.value;if(Y||X)z(J,{code:Y?B.too_big:B.too_small,minimum:X?W.exactLength.value:void 0,maximum:Y?W.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:W.exactLength.message}),Q.dirty()}if(W.minLength!==null){if(J.data.length<W.minLength.value)z(J,{code:B.too_small,minimum:W.minLength.value,type:"array",inclusive:!0,exact:!1,message:W.minLength.message}),Q.dirty()}if(W.maxLength!==null){if(J.data.length>W.maxLength.value)z(J,{code:B.too_big,maximum:W.maxLength.value,type:"array",inclusive:!0,exact:!1,message:W.maxLength.message}),Q.dirty()}if(J.common.async)return Promise.all([...J.data].map((Y,X)=>{return W.type._parseAsync(new u(J,Y,J.path,X))})).then((Y)=>{return k.mergeArray(Q,Y)});let G=[...J.data].map((Y,X)=>{return W.type._parseSync(new u(J,Y,J.path,X))});return k.mergeArray(Q,G)}get element(){return this._def.type}min($,J){return new m({...this._def,minLength:{value:$,message:E.toString(J)}})}max($,J){return new m({...this._def,maxLength:{value:$,message:E.toString(J)}})}length($,J){return new m({...this._def,exactLength:{value:$,message:E.toString(J)}})}nonempty($){return this.min(1,$)}}m.create=($,J)=>{return new m({type:$,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...q(J)})};function K$($){if($ instanceof C){let J={};for(let Q in $.shape){let W=$.shape[Q];J[Q]=c.create(K$(W))}return new C({...$._def,shape:()=>J})}else if($ instanceof m)return new m({...$._def,type:K$($.element)});else if($ instanceof c)return c.create(K$($.unwrap()));else if($ instanceof Q$)return Q$.create(K$($.unwrap()));else if($ instanceof a)return a.create($.items.map((J)=>K$(J)));else return $}class C extends F{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),J=v.objectKeys($);return this._cached={shape:$,keys:J},this._cached}_parse($){if(this._getType($)!==V.object){let _=this._getOrReturnCtx($);return z(_,{code:B.invalid_type,expected:V.object,received:_.parsedType}),U}let{status:Q,ctx:W}=this._processInputParams($),{shape:G,keys:Y}=this._getCached(),X=[];if(!(this._def.catchall instanceof r&&this._def.unknownKeys==="strip")){for(let _ in W.data)if(!Y.includes(_))X.push(_)}let H=[];for(let _ of Y){let M=G[_],O=W.data[_];H.push({key:{status:"valid",value:_},value:M._parse(new u(W,O,W.path,_)),alwaysSet:_ in W.data})}if(this._def.catchall instanceof r){let _=this._def.unknownKeys;if(_==="passthrough")for(let M of X)H.push({key:{status:"valid",value:M},value:{status:"valid",value:W.data[M]}});else if(_==="strict"){if(X.length>0)z(W,{code:B.unrecognized_keys,keys:X}),Q.dirty()}else if(_==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let _=this._def.catchall;for(let M of X){let O=W.data[M];H.push({key:{status:"valid",value:M},value:_._parse(new u(W,O,W.path,M)),alwaysSet:M in W.data})}}if(W.common.async)return Promise.resolve().then(async()=>{let _=[];for(let M of H){let O=await M.key,R=await M.value;_.push({key:O,value:R,alwaysSet:M.alwaysSet})}return _}).then((_)=>{return k.mergeObjectSync(Q,_)});else return k.mergeObjectSync(Q,H)}get shape(){return this._def.shape()}strict($){return E.errToObj,new C({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(J,Q)=>{let W=this._def.errorMap?.(J,Q).message??Q.defaultError;if(J.code==="unrecognized_keys")return{message:E.errToObj($).message??W};return{message:W}}}:{}})}strip(){return new C({...this._def,unknownKeys:"strip"})}passthrough(){return new C({...this._def,unknownKeys:"passthrough"})}extend($){return new C({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new C({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:S.ZodObject})}setKey($,J){return this.augment({[$]:J})}catchall($){return new C({...this._def,catchall:$})}pick($){let J={};for(let Q of v.objectKeys($))if($[Q]&&this.shape[Q])J[Q]=this.shape[Q];return new C({...this._def,shape:()=>J})}omit($){let J={};for(let Q of v.objectKeys(this.shape))if(!$[Q])J[Q]=this.shape[Q];return new C({...this._def,shape:()=>J})}deepPartial(){return K$(this)}partial($){let J={};for(let Q of v.objectKeys(this.shape)){let W=this.shape[Q];if($&&!$[Q])J[Q]=W;else J[Q]=W.optional()}return new C({...this._def,shape:()=>J})}required($){let J={};for(let Q of v.objectKeys(this.shape))if($&&!$[Q])J[Q]=this.shape[Q];else{let G=this.shape[Q];while(G instanceof c)G=G._def.innerType;J[Q]=G}return new C({...this._def,shape:()=>J})}keyof(){return v1(v.objectKeys(this.shape))}}C.create=($,J)=>{return new C({shape:()=>$,unknownKeys:"strip",catchall:r.create(),typeName:S.ZodObject,...q(J)})};C.strictCreate=($,J)=>{return new C({shape:()=>$,unknownKeys:"strict",catchall:r.create(),typeName:S.ZodObject,...q(J)})};C.lazycreate=($,J)=>{return new C({shape:$,unknownKeys:"strip",catchall:r.create(),typeName:S.ZodObject,...q(J)})};class h$ extends F{_parse($){let{ctx:J}=this._processInputParams($),Q=this._def.options;function W(G){for(let X of G)if(X.result.status==="valid")return X.result;for(let X of G)if(X.result.status==="dirty")return J.common.issues.push(...X.ctx.common.issues),X.result;let Y=G.map((X)=>new I(X.ctx.common.issues));return z(J,{code:B.invalid_union,unionErrors:Y}),U}if(J.common.async)return Promise.all(Q.map(async(G)=>{let Y={...J,common:{...J.common,issues:[]},parent:null};return{result:await G._parseAsync({data:J.data,path:J.path,parent:Y}),ctx:Y}})).then(W);else{let G=void 0,Y=[];for(let H of Q){let _={...J,common:{...J.common,issues:[]},parent:null},M=H._parseSync({data:J.data,path:J.path,parent:_});if(M.status==="valid")return M;else if(M.status==="dirty"&&!G)G={result:M,ctx:_};if(_.common.issues.length)Y.push(_.common.issues)}if(G)return J.common.issues.push(...G.ctx.common.issues),G.result;let X=Y.map((H)=>new I(H));return z(J,{code:B.invalid_union,unionErrors:X}),U}}get options(){return this._def.options}}h$.create=($,J)=>{return new h$({options:$,typeName:S.ZodUnion,...q(J)})};var J$=($)=>{if($ instanceof g$)return J$($.schema);else if($ instanceof n)return J$($.innerType());else if($ instanceof T$)return[$.value];else if($ instanceof M$)return $.options;else if($ instanceof x$)return v.objectValues($.enum);else if($ instanceof Z$)return J$($._def.innerType);else if($ instanceof k$)return[void 0];else if($ instanceof P$)return[null];else if($ instanceof c)return[void 0,...J$($.unwrap())];else if($ instanceof Q$)return[null,...J$($.unwrap())];else if($ instanceof _0)return J$($.unwrap());else if($ instanceof l$)return J$($.unwrap());else if($ instanceof y$)return J$($._def.innerType);else return[]};class H0 extends F{_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==V.object)return z(J,{code:B.invalid_type,expected:V.object,received:J.parsedType}),U;let Q=this.discriminator,W=J.data[Q],G=this.optionsMap.get(W);if(!G)return z(J,{code:B.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[Q]}),U;if(J.common.async)return G._parseAsync({data:J.data,path:J.path,parent:J});else return G._parseSync({data:J.data,path:J.path,parent:J})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,J,Q){let W=new Map;for(let G of J){let Y=J$(G.shape[$]);if(!Y.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let X of Y){if(W.has(X))throw Error(`Discriminator property ${String($)} has duplicate value ${String(X)}`);W.set(X,G)}}return new H0({typeName:S.ZodDiscriminatedUnion,discriminator:$,options:J,optionsMap:W,...q(Q)})}}function b0($,J){let Q=o($),W=o(J);if($===J)return{valid:!0,data:$};else if(Q===V.object&&W===V.object){let G=v.objectKeys(J),Y=v.objectKeys($).filter((H)=>G.indexOf(H)!==-1),X={...$,...J};for(let H of Y){let _=b0($[H],J[H]);if(!_.valid)return{valid:!1};X[H]=_.data}return{valid:!0,data:X}}else if(Q===V.array&&W===V.array){if($.length!==J.length)return{valid:!1};let G=[];for(let Y=0;Y<$.length;Y++){let X=$[Y],H=J[Y],_=b0(X,H);if(!_.valid)return{valid:!1};G.push(_.data)}return{valid:!0,data:G}}else if(Q===V.date&&W===V.date&&+$===+J)return{valid:!0,data:$};else return{valid:!1}}class I$ extends F{_parse($){let{status:J,ctx:Q}=this._processInputParams($),W=(G,Y)=>{if(X0(G)||X0(Y))return U;let X=b0(G.value,Y.value);if(!X.valid)return z(Q,{code:B.invalid_intersection_types}),U;if(Y0(G)||Y0(Y))J.dirty();return{status:J.value,value:X.data}};if(Q.common.async)return Promise.all([this._def.left._parseAsync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseAsync({data:Q.data,path:Q.path,parent:Q})]).then(([G,Y])=>W(G,Y));else return W(this._def.left._parseSync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseSync({data:Q.data,path:Q.path,parent:Q}))}}I$.create=($,J,Q)=>{return new I$({left:$,right:J,typeName:S.ZodIntersection,...q(Q)})};class a extends F{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==V.array)return z(Q,{code:B.invalid_type,expected:V.array,received:Q.parsedType}),U;if(Q.data.length<this._def.items.length)return z(Q,{code:B.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;if(!this._def.rest&&Q.data.length>this._def.items.length)z(Q,{code:B.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J.dirty();let G=[...Q.data].map((Y,X)=>{let H=this._def.items[X]||this._def.rest;if(!H)return null;return H._parse(new u(Q,Y,Q.path,X))}).filter((Y)=>!!Y);if(Q.common.async)return Promise.all(G).then((Y)=>{return k.mergeArray(J,Y)});else return k.mergeArray(J,G)}get items(){return this._def.items}rest($){return new a({...this._def,rest:$})}}a.create=($,J)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new a({items:$,typeName:S.ZodTuple,rest:null,...q(J)})};class d$ extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==V.object)return z(Q,{code:B.invalid_type,expected:V.object,received:Q.parsedType}),U;let W=[],G=this._def.keyType,Y=this._def.valueType;for(let X in Q.data)W.push({key:G._parse(new u(Q,X,Q.path,X)),value:Y._parse(new u(Q,Q.data[X],Q.path,X)),alwaysSet:X in Q.data});if(Q.common.async)return k.mergeObjectAsync(J,W);else return k.mergeObjectSync(J,W)}get element(){return this._def.valueType}static create($,J,Q){if(J instanceof F)return new d$({keyType:$,valueType:J,typeName:S.ZodRecord,...q(Q)});return new d$({keyType:l.create(),valueType:$,typeName:S.ZodRecord,...q(J)})}}class o$ extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==V.map)return z(Q,{code:B.invalid_type,expected:V.map,received:Q.parsedType}),U;let W=this._def.keyType,G=this._def.valueType,Y=[...Q.data.entries()].map(([X,H],_)=>{return{key:W._parse(new u(Q,X,Q.path,[_,"key"])),value:G._parse(new u(Q,H,Q.path,[_,"value"]))}});if(Q.common.async){let X=new Map;return Promise.resolve().then(async()=>{for(let H of Y){let _=await H.key,M=await H.value;if(_.status==="aborted"||M.status==="aborted")return U;if(_.status==="dirty"||M.status==="dirty")J.dirty();X.set(_.value,M.value)}return{status:J.value,value:X}})}else{let X=new Map;for(let H of Y){let{key:_,value:M}=H;if(_.status==="aborted"||M.status==="aborted")return U;if(_.status==="dirty"||M.status==="dirty")J.dirty();X.set(_.value,M.value)}return{status:J.value,value:X}}}}o$.create=($,J,Q)=>{return new o$({valueType:J,keyType:$,typeName:S.ZodMap,...q(Q)})};class S$ extends F{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==V.set)return z(Q,{code:B.invalid_type,expected:V.set,received:Q.parsedType}),U;let W=this._def;if(W.minSize!==null){if(Q.data.size<W.minSize.value)z(Q,{code:B.too_small,minimum:W.minSize.value,type:"set",inclusive:!0,exact:!1,message:W.minSize.message}),J.dirty()}if(W.maxSize!==null){if(Q.data.size>W.maxSize.value)z(Q,{code:B.too_big,maximum:W.maxSize.value,type:"set",inclusive:!0,exact:!1,message:W.maxSize.message}),J.dirty()}let G=this._def.valueType;function Y(H){let _=new Set;for(let M of H){if(M.status==="aborted")return U;if(M.status==="dirty")J.dirty();_.add(M.value)}return{status:J.value,value:_}}let X=[...Q.data.values()].map((H,_)=>G._parse(new u(Q,H,Q.path,_)));if(Q.common.async)return Promise.all(X).then((H)=>Y(H));else return Y(X)}min($,J){return new S$({...this._def,minSize:{value:$,message:E.toString(J)}})}max($,J){return new S$({...this._def,maxSize:{value:$,message:E.toString(J)}})}size($,J){return this.min($,J).max($,J)}nonempty($){return this.min(1,$)}}S$.create=($,J)=>{return new S$({valueType:$,minSize:null,maxSize:null,typeName:S.ZodSet,...q(J)})};class C$ extends F{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==V.function)return z(J,{code:B.invalid_type,expected:V.function,received:J.parsedType}),U;function Q(X,H){return n$({data:X,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,D$(),$$].filter((_)=>!!_),issueData:{code:B.invalid_arguments,argumentsError:H}})}function W(X,H){return n$({data:X,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,D$(),$$].filter((_)=>!!_),issueData:{code:B.invalid_return_type,returnTypeError:H}})}let G={errorMap:J.common.contextualErrorMap},Y=J.data;if(this._def.returns instanceof j$){let X=this;return P(async function(...H){let _=new I([]),M=await X._def.args.parseAsync(H,G).catch((D)=>{throw _.addIssue(Q(H,D)),_}),O=await Reflect.apply(Y,this,M);return await X._def.returns._def.type.parseAsync(O,G).catch((D)=>{throw _.addIssue(W(O,D)),_})})}else{let X=this;return P(function(...H){let _=X._def.args.safeParse(H,G);if(!_.success)throw new I([Q(H,_.error)]);let M=Reflect.apply(Y,this,_.data),O=X._def.returns.safeParse(M,G);if(!O.success)throw new I([W(M,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new C$({...this._def,args:a.create($).rest(Y$.create())})}returns($){return new C$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,J,Q){return new C$({args:$?$:a.create([]).rest(Y$.create()),returns:J||Y$.create(),typeName:S.ZodFunction,...q(Q)})}}class g$ extends F{get schema(){return this._def.getter()}_parse($){let{ctx:J}=this._processInputParams($);return this._def.getter()._parse({data:J.data,path:J.path,parent:J})}}g$.create=($,J)=>{return new g$({getter:$,typeName:S.ZodLazy,...q(J)})};class T$ extends F{_parse($){if($.data!==this._def.value){let J=this._getOrReturnCtx($);return z(J,{received:J.data,code:B.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:$.data}}get value(){return this._def.value}}T$.create=($,J)=>{return new T$({value:$,typeName:S.ZodLiteral,...q(J)})};function v1($,J){return new M$({values:$,typeName:S.ZodEnum,...q(J)})}class M$ extends F{_parse($){if(typeof $.data!=="string"){let J=this._getOrReturnCtx($),Q=this._def.values;return z(J,{expected:v.joinValues(Q),received:J.parsedType,code:B.invalid_type}),U}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let J=this._getOrReturnCtx($),Q=this._def.values;return z(J,{received:J.data,code:B.invalid_enum_value,options:Q}),U}return P($.data)}get options(){return this._def.values}get enum(){let $={};for(let J of this._def.values)$[J]=J;return $}get Values(){let $={};for(let J of this._def.values)$[J]=J;return $}get Enum(){let $={};for(let J of this._def.values)$[J]=J;return $}extract($,J=this._def){return M$.create($,{...this._def,...J})}exclude($,J=this._def){return M$.create(this.options.filter((Q)=>!$.includes(Q)),{...this._def,...J})}}M$.create=v1;class x$ extends F{_parse($){let J=v.getValidEnumValues(this._def.values),Q=this._getOrReturnCtx($);if(Q.parsedType!==V.string&&Q.parsedType!==V.number){let W=v.objectValues(J);return z(Q,{expected:v.joinValues(W),received:Q.parsedType,code:B.invalid_type}),U}if(!this._cache)this._cache=new Set(v.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let W=v.objectValues(J);return z(Q,{received:Q.data,code:B.invalid_enum_value,options:W}),U}return P($.data)}get enum(){return this._def.values}}x$.create=($,J)=>{return new x$({values:$,typeName:S.ZodNativeEnum,...q(J)})};class j$ extends F{unwrap(){return this._def.type}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==V.promise&&J.common.async===!1)return z(J,{code:B.invalid_type,expected:V.promise,received:J.parsedType}),U;let Q=J.parsedType===V.promise?J.data:Promise.resolve(J.data);return P(Q.then((W)=>{return this._def.type.parseAsync(W,{path:J.path,errorMap:J.common.contextualErrorMap})}))}}j$.create=($,J)=>{return new j$({type:$,typeName:S.ZodPromise,...q(J)})};class n extends F{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:J,ctx:Q}=this._processInputParams($),W=this._def.effect||null,G={addIssue:(Y)=>{if(z(Q,Y),Y.fatal)J.abort();else J.dirty()},get path(){return Q.path}};if(G.addIssue=G.addIssue.bind(G),W.type==="preprocess"){let Y=W.transform(Q.data,G);if(Q.common.async)return Promise.resolve(Y).then(async(X)=>{if(J.value==="aborted")return U;let H=await this._def.schema._parseAsync({data:X,path:Q.path,parent:Q});if(H.status==="aborted")return U;if(H.status==="dirty")return N$(H.value);if(J.value==="dirty")return N$(H.value);return H});else{if(J.value==="aborted")return U;let X=this._def.schema._parseSync({data:Y,path:Q.path,parent:Q});if(X.status==="aborted")return U;if(X.status==="dirty")return N$(X.value);if(J.value==="dirty")return N$(X.value);return X}}if(W.type==="refinement"){let Y=(X)=>{let H=W.refinement(X,G);if(Q.common.async)return Promise.resolve(H);if(H instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return X};if(Q.common.async===!1){let X=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(X.status==="aborted")return U;if(X.status==="dirty")J.dirty();return Y(X.value),{status:J.value,value:X.value}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((X)=>{if(X.status==="aborted")return U;if(X.status==="dirty")J.dirty();return Y(X.value).then(()=>{return{status:J.value,value:X.value}})})}if(W.type==="transform")if(Q.common.async===!1){let Y=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(!X$(Y))return U;let X=W.transform(Y.value,G);if(X instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:J.value,value:X}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((Y)=>{if(!X$(Y))return U;return Promise.resolve(W.transform(Y.value,G)).then((X)=>({status:J.value,value:X}))});v.assertNever(W)}}n.create=($,J,Q)=>{return new n({schema:$,typeName:S.ZodEffects,effect:J,...q(Q)})};n.createWithPreprocess=($,J,Q)=>{return new n({schema:J,effect:{type:"preprocess",transform:$},typeName:S.ZodEffects,...q(Q)})};class c extends F{_parse($){if(this._getType($)===V.undefined)return P(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}c.create=($,J)=>{return new c({innerType:$,typeName:S.ZodOptional,...q(J)})};class Q$ extends F{_parse($){if(this._getType($)===V.null)return P(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}Q$.create=($,J)=>{return new Q$({innerType:$,typeName:S.ZodNullable,...q(J)})};class Z$ extends F{_parse($){let{ctx:J}=this._processInputParams($),Q=J.data;if(J.parsedType===V.undefined)Q=this._def.defaultValue();return this._def.innerType._parse({data:Q,path:J.path,parent:J})}removeDefault(){return this._def.innerType}}Z$.create=($,J)=>{return new Z$({innerType:$,typeName:S.ZodDefault,defaultValue:typeof J.default==="function"?J.default:()=>J.default,...q(J)})};class y$ extends F{_parse($){let{ctx:J}=this._processInputParams($),Q={...J,common:{...J.common,issues:[]}},W=this._def.innerType._parse({data:Q.data,path:Q.path,parent:{...Q}});if(f$(W))return W.then((G)=>{return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new I(Q.common.issues)},input:Q.data})}});else return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new I(Q.common.issues)},input:Q.data})}}removeCatch(){return this._def.innerType}}y$.create=($,J)=>{return new y$({innerType:$,typeName:S.ZodCatch,catchValue:typeof J.catch==="function"?J.catch:()=>J.catch,...q(J)})};class r$ extends F{_parse($){if(this._getType($)!==V.nan){let Q=this._getOrReturnCtx($);return z(Q,{code:B.invalid_type,expected:V.nan,received:Q.parsedType}),U}return{status:"valid",value:$.data}}}r$.create=($)=>{return new r$({typeName:S.ZodNaN,...q($)})};var G4=Symbol("zod_brand");class _0 extends F{_parse($){let{ctx:J}=this._processInputParams($),Q=J.data;return this._def.type._parse({data:Q,path:J.path,parent:J})}unwrap(){return this._def.type}}class a$ extends F{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.common.async)return(async()=>{let G=await this._def.in._parseAsync({data:Q.data,path:Q.path,parent:Q});if(G.status==="aborted")return U;if(G.status==="dirty")return J.dirty(),N$(G.value);else return this._def.out._parseAsync({data:G.value,path:Q.path,parent:Q})})();else{let W=this._def.in._parseSync({data:Q.data,path:Q.path,parent:Q});if(W.status==="aborted")return U;if(W.status==="dirty")return J.dirty(),{status:"dirty",value:W.value};else return this._def.out._parseSync({data:W.value,path:Q.path,parent:Q})}}static create($,J){return new a$({in:$,out:J,typeName:S.ZodPipeline})}}class l$ extends F{_parse($){let J=this._def.innerType._parse($),Q=(W)=>{if(X$(W))W.value=Object.freeze(W.value);return W};return f$(J)?J.then((W)=>Q(W)):Q(J)}unwrap(){return this._def.innerType}}l$.create=($,J)=>{return new l$({innerType:$,typeName:S.ZodReadonly,...q(J)})};function q1($,J){let Q=typeof $==="function"?$(J):typeof $==="string"?{message:$}:$;return typeof Q==="string"?{message:Q}:Q}function D1($,J={},Q){if($)return L$.create().superRefine((W,G)=>{let Y=$(W);if(Y instanceof Promise)return Y.then((X)=>{if(!X){let H=q1(J,W),_=H.fatal??Q??!0;G.addIssue({code:"custom",...H,fatal:_})}});if(!Y){let X=q1(J,W),H=X.fatal??Q??!0;G.addIssue({code:"custom",...X,fatal:H})}return});return L$.create()}var X4={object:C.lazycreate},S;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(S||(S={}));var Y4=($,J={message:`Input not instance of ${$.name}`})=>D1((Q)=>Q instanceof $,J),f1=l.create,K1=H$.create,H4=r$.create,_4=_$.create,C1=b$.create,M4=U$.create,B4=p$.create,O4=k$.create,V4=P$.create,z4=L$.create,E4=Y$.create,N4=r.create,U4=i$.create,L4=m.create,S4=C.create,j4=C.strictCreate,R4=h$.create,q4=H0.create,A4=I$.create,F4=a.create,w4=d$.create,v4=o$.create,D4=S$.create,f4=C$.create,K4=g$.create,C4=T$.create,b4=M$.create,k4=x$.create,P4=j$.create,h4=n.create,I4=c.create,g4=Q$.create,T4=n.createWithPreprocess,x4=a$.create,Z4=()=>f1().optional(),y4=()=>K1().optional(),l4=()=>C1().optional(),m4={string:($)=>l.create({...$,coerce:!0}),number:($)=>H$.create({...$,coerce:!0}),boolean:($)=>b$.create({...$,coerce:!0}),bigint:($)=>_$.create({...$,coerce:!0}),date:($)=>U$.create({...$,coerce:!0})};var c4=U;var u4=["google","groq","cerebras","sambanova","nvidia","mistral","openrouter","github","cohere","cloudflare","zhipu"],n4=N.object({platform:N.enum(u4),key:N.string().min(1),label:N.string().optional()});async function b1($,J){let W=new URL($.url).pathname;if(W==="/api/keys"&&$.method==="GET"){let X=A().prepare("SELECT * FROM api_keys ORDER BY created_at DESC").all().map((H)=>{let _="****";try{let M=w$(H.encrypted_key,H.iv,H.auth_tag);_=r0(M)}catch{_="[decrypt failed]"}return{id:H.id,platform:H.platform,label:H.label,maskedKey:_,status:H.status,enabled:H.enabled===1,createdAt:H.created_at,lastCheckedAt:H.last_checked_at}});return j(X)}if(W==="/api/keys"&&$.method==="POST")try{let G=await $.json(),Y=n4.parse(G),{platform:X,key:H,label:_}=Y,M=A(),O=M.prepare("SELECT COUNT(*) as cnt FROM api_keys WHERE platform = ? AND enabled = 1").get(X).cnt,{encrypted:R,iv:D,authTag:f}=o0(H);if(M.prepare(`
INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status)
VALUES (?, ?, ?, ?, ?, 'unknown')
`).run(X,_??"",R,D,f),O===0)M.prepare("UPDATE models SET enabled = 1 WHERE platform = ?").run(X);return j({success:!0},201)}catch(G){return j({error:{message:G.message}},400)}if(W.startsWith("/api/keys/")&&$.method==="DELETE"){let G=W.split("/"),Y=parseInt(G[G.length-1]);if(isNaN(Y))return new Response("Invalid ID",{status:400});let X=A(),H=X.prepare("SELECT platform FROM api_keys WHERE id = ?").get(Y);if(!H)return new Response("Not Found",{status:404});if(X.prepare("DELETE FROM api_keys WHERE id = ?").run(Y),X.prepare("SELECT COUNT(*) as cnt FROM api_keys WHERE platform = ? AND enabled = 1").get(H.platform).cnt===0)X.prepare("UPDATE models SET enabled = 0 WHERE platform = ?").run(H.platform);return j({success:!0})}if(W.startsWith("/api/keys/")&&W.endsWith("/toggle")&&$.method==="POST"){let G=W.split("/"),Y=parseInt(G[G.length-2]);if(isNaN(Y))return new Response("Invalid ID",{status:400});let X=A(),H=X.prepare("SELECT enabled FROM api_keys WHERE id = ?").get(Y);if(!H)return new Response("Not Found",{status:404});let _=H.enabled===1?0:1;return X.prepare("UPDATE api_keys SET enabled = ? WHERE id = ?").run(_,Y),j({success:!0,enabled:_===1})}return new Response("Not Found",{status:404})}async function k1($,J){let W=new URL($.url).pathname;if(W==="/api/models"&&$.method==="GET"){let G=A(),Y=G.prepare(`
SELECT m.*, fc.priority, fc.enabled as fallback_enabled
FROM models m
LEFT JOIN fallback_config fc ON fc.model_db_id = m.id
ORDER BY COALESCE(fc.priority, m.intelligence_rank) ASC
`).all(),X=G.prepare(`
SELECT platform, COUNT(*) as count
FROM api_keys
WHERE enabled = 1
GROUP BY platform
`).all(),H=new Map(X.map((M)=>[M.platform,M.count])),_=Y.map((M)=>({id:M.id,platform:M.platform,modelId:M.model_id,displayName:M.display_name,intelligenceRank:M.intelligence_rank,speedRank:M.speed_rank,sizeLabel:M.size_label,rpmLimit:M.rpm_limit,rpdLimit:M.rpd_limit,tpmLimit:M.tpm_limit,tpdLimit:M.tpd_limit,monthlyTokenBudget:M.monthly_token_budget,contextWindow:M.context_window,enabled:M.enabled===1,fallbackEnabled:M.fallback_enabled===1,hasProvider:G0(M.platform),keyCount:H.get(M.platform)??0}));return j(_)}if(W.startsWith("/api/models/")&&W.endsWith("/toggle")&&$.method==="POST"){let G=W.split("/"),Y=parseInt(G[G.length-2]);if(isNaN(Y))return new Response("Invalid ID",{status:400});let X=A(),H=X.prepare("SELECT enabled FROM models WHERE id = ?").get(Y);if(!H)return new Response("Not Found",{status:404});let _=H.enabled===1?0:1;return X.prepare("UPDATE models SET enabled = ? WHERE id = ?").run(_,Y),j({success:!0,enabled:_===1})}return new Response("Not Found",{status:404})}var P1=new Map;function B$($){let J=P1.get($);if(!J)J={timestamps:[],tokenCount:0,tokenTimestamps:[]},P1.set($,J);return J}function h1($,J,Q){let W=Q-J;return $.filter((G)=>G>W)}var P0=60000,I1=1440*P0;function g1($,J,Q,W){let G=Date.now();if(W.rpm!==null){let Y=`${$}:${J}:${Q}:rpm`,X=B$(Y);if(X.timestamps=h1(X.timestamps,P0,G),X.timestamps.length>=W.rpm)return!1}if(W.rpd!==null){let Y=`${$}:${J}:${Q}:rpd`,X=B$(Y);if(X.timestamps=h1(X.timestamps,I1,G),X.timestamps.length>=W.rpd)return!1}return!0}function T1($,J,Q,W,G){let Y=Date.now();if(G.tpm!==null){let X=`${$}:${J}:${Q}:tpm`,H=B$(X);if(H.tokenTimestamps=H.tokenTimestamps.filter((M)=>M.ts>Y-P0),H.tokenTimestamps.reduce((M,O)=>M+O.tokens,0)+W>G.tpm)return!1}if(G.tpd!==null){let X=`${$}:${J}:${Q}:tpd`,H=B$(X);if(H.tokenTimestamps=H.tokenTimestamps.filter((M)=>M.ts>Y-I1),H.tokenTimestamps.reduce((M,O)=>M+O.tokens,0)+W>G.tpd)return!1}return!0}function x1($,J,Q){let W=Date.now(),G=`${$}:${J}:${Q}:rpm`;B$(G).timestamps.push(W);let Y=`${$}:${J}:${Q}:rpd`;B$(Y).timestamps.push(W)}function h0($,J,Q,W){let G=Date.now(),Y=`${$}:${J}:${Q}:tpm`;B$(Y).tokenTimestamps.push({ts:G,tokens:W});let X=`${$}:${J}:${Q}:tpd`;B$(X).tokenTimestamps.push({ts:G,tokens:W})}var k0=new Map;function Z1($,J,Q,W=60000){let G=`${$}:${J}:${Q}:cooldown`;k0.set(G,Date.now()+W)}function y1($,J,Q){let W=`${$}:${J}:${Q}:cooldown`,G=k0.get(W);if(!G)return!1;if(Date.now()>G)return k0.delete(W),!1;return!0}var I0=new Map,R$=new Map,l1=3,p4=10,i4=120000,d4=1;function m1($){let J=R$.get($),Q=Date.now();if(J)J.count++,J.lastHit=Q,J.penalty=Math.min(J.penalty+l1,p4);else R$.set($,{count:1,lastHit:Q,penalty:l1})}function g0($){let J=R$.get($);if(J){if(J.penalty=Math.max(0,J.penalty-1),J.penalty===0)R$.delete($)}}function c1($){let J=R$.get($);if(!J)return 0;let Q=Date.now(),W=Q-J.lastHit,G=Math.floor(W/i4);if(G>0){if(J.penalty=Math.max(0,J.penalty-G*d4),J.lastHit=Q,J.penalty===0)return R$.delete($),0}return J.penalty}function u1(){let $=[];for(let[J,Q]of R$){let W=c1(J);if(W>0)$.push({modelDbId:J,count:Q.count,penalty:W})}return $.sort((J,Q)=>Q.penalty-J.penalty)}function n1($=1000,J,Q){let W=A(),Y=W.prepare(`
SELECT fc.model_db_id, fc.priority, fc.enabled
FROM fallback_config fc
ORDER BY fc.priority ASC
`).all().map((H)=>({...H,effectivePriority:H.priority+c1(H.model_db_id)})).sort((H,_)=>H.effectivePriority-_.effectivePriority);if(Q){let H=Y.findIndex((_)=>_.model_db_id===Q);if(H>0){let[_]=Y.splice(H,1);Y.unshift(_)}}for(let H of Y){if(!H.enabled)continue;let _=W.prepare("SELECT * FROM models WHERE id = ? AND enabled = 1").get(H.model_db_id);if(!_)continue;let M=W0(_.platform);if(!M)continue;let O=W.prepare("SELECT * FROM api_keys WHERE platform = ? AND enabled = 1 AND status != ?").all(_.platform,"invalid");if(O.length===0)continue;let R=`${_.platform}:${_.model_id}`,D=I0.get(R)??0;for(let f=0;f<O.length;f++){let K=O[D%O.length];D++;let g=`${_.platform}:${_.model_id}:${K.id}`;if(J?.has(g))continue;if(y1(_.platform,_.model_id,K.id))continue;let T={rpm:_.rpm_limit,rpd:_.rpd_limit,tpm:_.tpm_limit,tpd:_.tpd_limit};if(!g1(_.platform,_.model_id,K.id,T))continue;if(!T1(_.platform,_.model_id,K.id,$,T))continue;I0.set(R,D);let A$=w$(K.encrypted_key,K.iv,K.auth_tag);return{provider:M,modelId:_.model_id,modelDbId:_.id,apiKey:A$,keyId:K.id,platform:_.platform,displayName:_.display_name}}I0.set(R,D)}let X=Error("All models exhausted. Add more API keys or wait for rate limits to reset.");throw X.status=429,X}async function p1($,J){let Q=J.pathname;if(Q==="/api/fallback"&&$.method==="GET"){let W=A(),G=W.prepare(`
SELECT fc.model_db_id, fc.priority, fc.enabled,
m.platform, m.model_id, m.display_name, m.intelligence_rank,
m.speed_rank, m.size_label, m.rpm_limit, m.rpd_limit,
m.monthly_token_budget
FROM fallback_config fc
JOIN models m ON m.id = fc.model_db_id
ORDER BY fc.priority ASC
`).all(),Y=W.prepare(`
SELECT platform, COUNT(*) as count
FROM api_keys WHERE enabled = 1
GROUP BY platform
`).all(),X=new Map(Y.map((O)=>[O.platform,O.count])),H=u1(),_=new Map(H.map((O)=>[O.modelDbId,O])),M=G.map((O)=>{let R=_.get(O.model_db_id);return{modelDbId:O.model_db_id,priority:O.priority,effectivePriority:O.priority+(R?.penalty??0),penalty:R?.penalty??0,rateLimitHits:R?.count??0,enabled:O.enabled===1,platform:O.platform,modelId:O.model_id,displayName:O.display_name,intelligenceRank:O.intelligence_rank,speedRank:O.speed_rank,sizeLabel:O.size_label,rpmLimit:O.rpm_limit,rpdLimit:O.rpd_limit,monthlyTokenBudget:O.monthly_token_budget,keyCount:X.get(O.platform)??0}});return j(M)}if(Q==="/api/fallback"&&$.method==="PUT")try{let W=await $.json(),G=A();G.prepare("BEGIN TRANSACTION").run();try{for(let Y of W)G.prepare(`
UPDATE fallback_config SET priority = ?, enabled = ?
WHERE model_db_id = ?
`).run(Y.priority,Y.enabled?1:0,Y.modelDbId);G.prepare("COMMIT").run()}catch(Y){throw G.prepare("ROLLBACK").run(),Y}return j({success:!0})}catch(W){return j({error:{message:W.message}},400)}if(Q.startsWith("/api/fallback/sort/")&&$.method==="POST"){let W=Q.split("/").pop(),G=A(),Y=G.prepare(`
SELECT fc.model_db_id, m.intelligence_rank, m.speed_rank, m.monthly_token_budget
FROM fallback_config fc
JOIN models m ON m.id = fc.model_db_id
ORDER BY fc.priority ASC
`).all(),X;switch(W){case"intelligence":X=[...Y].sort((H,_)=>H.intelligence_rank-_.intelligence_rank);break;case"speed":X=[...Y].sort((H,_)=>H.speed_rank-_.speed_rank);break;case"budget":X=[...Y].sort((H,_)=>{let M=parseFloat((H.monthly_token_budget||"0").replace(/[^0-9.]/g,""))||0;return(parseFloat((_.monthly_token_budget||"0").replace(/[^0-9.]/g,""))||0)-M});break;default:return new Response("Invalid preset",{status:400})}G.prepare("BEGIN TRANSACTION").run();try{for(let H=0;H<X.length;H++)G.prepare("UPDATE fallback_config SET priority = ? WHERE model_db_id = ?").run(H+1,X[H].model_db_id);G.prepare("COMMIT").run()}catch(H){throw G.prepare("ROLLBACK").run(),H}return j({success:!0})}if(Q==="/api/fallback/token-usage"&&$.method==="GET"){let W=A(),G=new Date,Y=new Date(G.getFullYear(),G.getMonth(),1).toISOString(),X=W.prepare(`
SELECT
m.display_name, m.platform, m.monthly_token_budget,
COALESCE(SUM(r.input_tokens + r.output_tokens), 0) as used
FROM models m
LEFT JOIN api_keys k ON k.platform = m.platform AND k.enabled = 1
LEFT JOIN requests r ON r.model_id = m.model_id AND r.platform = m.platform
AND r.created_at >= ?
WHERE m.enabled = 1
GROUP BY m.id
ORDER BY m.intelligence_rank ASC
`).all(Y),H=X.reduce((M,O)=>{let R=parseFloat((O.monthly_token_budget||"0").replace(/[^0-9.]/g,""))||0;return M+R*1e6},0),_=X.reduce((M,O)=>M+(O.used??0),0);return j({totalBudget:H,totalUsed:_,models:X.map((M)=>({displayName:M.display_name,platform:M.platform,budget:(parseFloat((M.monthly_token_budget||"0").replace(/[^0-9.]/g,""))||0)*1e6}))})}return new Response("Not Found",{status:404})}function o4($){switch($){case"24h":return"datetime('now', '-1 day')";case"7d":return"datetime('now', '-7 days')";case"30d":return"datetime('now', '-30 days')";default:return"datetime('now', '-7 days')"}}async function i1($,J){let Q=J.pathname,W=J.searchParams.get("range")??"7d",G=o4(W);if(Q==="/api/analytics/summary"&&$.method==="GET"){let X=A().prepare(`
SELECT
COUNT(*) as total_requests,
SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success_count,
SUM(input_tokens) as total_input_tokens,
SUM(output_tokens) as total_output_tokens,
AVG(latency_ms) as avg_latency_ms
FROM requests
WHERE created_at >= ${G}
`).get(),H=X.total_requests??0,_=H>0?X.success_count/H*100:0,M=(X.total_input_tokens??0)+(X.total_output_tokens??0),O=(X.total_input_tokens??0)/1e6*3,R=(X.total_output_tokens??0)/1e6*15,D=O+R;return j({totalRequests:H,successRate:Math.round(_*10)/10,avgLatencyMs:Math.round(X.avg_latency_ms??0),totalTokens:M,estimatedSavings:Math.round(D*100)/100})}if(Q==="/api/analytics/requests-over-time"&&$.method==="GET"){let Y=A(),X,H;switch(W){case"24h":X="strftime('%Y-%m-%d %H:00', created_at)",H="%Y-%m-%d %H:00";break;case"30d":X="date(created_at)",H="%Y-%m-%d";break;default:X="date(created_at)",H="%Y-%m-%d"}let _=Y.prepare(`
SELECT
strftime('${H}', created_at) as period,
COUNT(*) as total,
SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success
FROM requests
WHERE created_at >= ${G}
GROUP BY ${X}
ORDER BY period ASC
`).all();return j(_.map((M)=>({period:M.period,total:M.total,success:M.success})))}if(Q==="/api/analytics/platforms"&&$.method==="GET"){let X=A().prepare(`
SELECT
platform,
COUNT(*) as total_requests,
SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success_count,
AVG(latency_ms) as avg_latency_ms,
SUM(input_tokens) as total_input,
SUM(output_tokens) as total_output
FROM requests
WHERE created_at >= ${G}
GROUP BY platform
ORDER BY total_requests DESC
`).all();return j(X.map((H)=>({platform:H.platform,totalRequests:H.total_requests,successRate:H.total_requests>0?Math.round(H.success_count/H.total_requests*1000)/10:0,avgLatencyMs:Math.round(H.avg_latency_ms??0),totalTokens:(H.total_input??0)+(H.total_output??0)})))}if(Q==="/api/analytics/models"&&$.method==="GET"){let X=A().prepare(`
SELECT
platform,
model_id,
COUNT(*) as total_requests,
SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success_count,
AVG(latency_ms) as avg_latency_ms
FROM requests
WHERE created_at >= ${G}
GROUP BY platform, model_id
ORDER BY total_requests DESC
LIMIT 20
`).all();return j(X.map((H)=>({platform:H.platform,modelId:H.model_id,totalRequests:H.total_requests,successRate:H.total_requests>0?Math.round(H.success_count/H.total_requests*1000)/10:0,avgLatencyMs:Math.round(H.avg_latency_ms??0)})))}if(Q==="/api/analytics/recent"&&$.method==="GET"){let Y=A(),X=parseInt(J.searchParams.get("limit")??"50"),H=Y.prepare(`
SELECT *
FROM requests
WHERE created_at >= ${G}
ORDER BY created_at DESC
LIMIT ?
`).all(X);return j(H.map((_)=>({id:_.id,platform:_.platform,modelId:_.model_id,status:_.status,inputTokens:_.input_tokens,outputTokens:_.output_tokens,latencyMs:_.latency_ms,error:_.error,createdAt:_.created_at})))}return new Response("Not Found",{status:404})}async function d1($,J){let W=new URL($.url).pathname;if(W==="/api/health"&&$.method==="GET"){let G=A(),Y=G.prepare(`
SELECT
platform,
COUNT(*) as total_keys,
SUM(CASE WHEN status = 'healthy' THEN 1 ELSE 0 END) as healthy_keys,
SUM(CASE WHEN status = 'rate_limited' THEN 1 ELSE 0 END) as rate_limited_keys,
SUM(CASE WHEN status = 'invalid' THEN 1 ELSE 0 END) as invalid_keys,
SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as error_keys,
SUM(CASE WHEN status = 'unknown' THEN 1 ELSE 0 END) as unknown_keys,
SUM(CASE WHEN enabled = 1 THEN 1 ELSE 0 END) as enabled_keys
FROM api_keys
GROUP BY platform
`).all(),X=G.prepare(`
SELECT id, platform, label, status, enabled, created_at, last_checked_at
FROM api_keys
ORDER BY platform, created_at DESC
`).all();return j({platforms:Y.map((H)=>({platform:H.platform,hasProvider:G0(H.platform),totalKeys:H.total_keys,healthyKeys:H.healthy_keys,rateLimitedKeys:H.rate_limited_keys,invalidKeys:H.invalid_keys,errorKeys:H.error_keys,unknownKeys:H.unknown_keys,enabledKeys:H.enabled_keys})),keys:X.map((H)=>({id:H.id,platform:H.platform,label:H.label,status:H.status,enabled:H.enabled===1,createdAt:H.created_at,lastCheckedAt:H.last_checked_at}))})}if(W.startsWith("/api/health/check/")&&$.method==="POST"){let G=W.split("/"),Y=parseInt(G[G.length-1]);if(isNaN(Y))return new Response("Invalid ID",{status:400});return await F0(Y),j({success:!0})}if(W==="/api/health/check-all"&&$.method==="POST")return await w0(),j({success:!0});return new Response("Not Found",{status:404})}async function o1($,J){let Q=new URL($.url).pathname;if(Q==="/api/settings/api-key"){if($.method==="GET")return j({apiKey:Q0()});if($.method==="POST"&&Q.endsWith("/regenerate")){let W=Q1();return j({apiKey:W})}}return new Response("Not Found",{status:404})}var m$=new Map,a1=1800000;function t1($){let J=$.find((Q)=>Q.role==="user");if(!J||typeof J.content!=="string")return"";return`${J.content.slice(0,100)}:${$.length>2?"multi":"single"}`}function r4($){if(!$.some((G)=>G.role==="assistant"))return;let Q=t1($);if(!Q)return;let W=m$.get(Q);if(!W)return;if(Date.now()-W.lastUsed>a1){m$.delete(Q);return}return W.modelDbId}function r1($,J){let Q=t1($);if(!Q)return;if(m$.set(Q,{modelDbId:J,lastUsed:Date.now()}),m$.size>500){let W=Date.now();for(let[G,Y]of m$)if(W-Y.lastUsed>a1)m$.delete(G)}}var a4=N.object({id:N.string().min(1),type:N.literal("function"),function:N.object({name:N.string().min(1),arguments:N.string()})}),t4=N.object({role:N.literal("system"),content:N.string(),name:N.string().optional()}),s4=N.object({role:N.literal("user"),content:N.string(),name:N.string().optional()}),e4=N.object({role:N.literal("assistant"),content:N.string().nullable().optional(),name:N.string().optional(),tool_calls:N.array(a4).optional()}).refine(($)=>{let J=typeof $.content==="string"&&$.content.length>0,Q=($.tool_calls?.length??0)>0;return J||Q},{message:"assistant messages must include non-empty content or tool_calls"}),$6=N.object({role:N.literal("tool"),content:N.string(),tool_call_id:N.string().min(1),name:N.string().optional()}),J6=N.object({type:N.literal("function"),function:N.object({name:N.string().min(1),description:N.string().optional(),parameters:N.record(N.string(),N.unknown()).optional(),strict:N.boolean().optional()})}),Q6=N.union([N.enum(["none","auto","required"]),N.object({type:N.literal("function"),function:N.object({name:N.string().min(1)})})]),W6=N.object({messages:N.array(N.union([t4,s4,e4,$6])).min(1),model:N.string().optional(),temperature:N.number().min(0).max(2).optional(),max_tokens:N.number().int().positive().optional(),top_p:N.number().min(0).max(1).optional(),stream:N.boolean().optional(),tools:N.array(J6).optional(),tool_choice:Q6.optional(),parallel_tool_calls:N.boolean().optional()}),T0=20;function G6($){let J=($.message??"").toLowerCase();return J.includes("429")||J.includes("rate limit")||J.includes("too many requests")||J.includes("quota")||J.includes("resource_exhausted")||J.includes("aborted")||J.includes("timeout")||J.includes("etimedout")||J.includes("econnrefused")||J.includes("econnreset")||J.includes("503")||J.includes("unavailable")||J.includes("500")||J.includes("internal server error")}function x0($,J,Q,W,G,Y,X){try{A().prepare(`
INSERT INTO requests (platform, model_id, status, input_tokens, output_tokens, latency_ms, error)
VALUES (?, ?, ?, ?, ?, ?, ?)
`).run($,J,Q,W,G,Y,X)}catch(H){console.error("Failed to log request:",H)}}async function s1($,J){let W=new URL($.url).pathname,G=Date.now();if(W==="/v1/models"&&$.method==="GET"){let X=A().prepare("SELECT platform, model_id, display_name, context_window FROM models WHERE enabled = 1 ORDER BY intelligence_rank").all();return new Response(JSON.stringify({object:"list",data:X.map((H)=>({id:H.model_id,object:"model",created:0,owned_by:H.platform,name:H.display_name,context_window:H.context_window}))}),{headers:{"Content-Type":"application/json"}})}if(W==="/v1/chat/completions"&&$.method==="POST"){let Y=$.headers.get("authorization"),X=$.headers.get("x-forwarded-for")??$.headers.get("x-real-ip")??"unknown";if(Y&&!(X==="127.0.0.1"||X==="::1"||X==="::ffff:127.0.0.1")){let w=Y.replace(/^Bearer\s+/i,""),L=Q0();if(w!==L)return new Response(JSON.stringify({error:{message:"Invalid API key",type:"authentication_error"}}),{status:401,headers:{"Content-Type":"application/json"}})}let _;try{_=await $.json()}catch{return new Response(JSON.stringify({error:{message:"Invalid JSON",type:"invalid_request_error"}}),{status:400,headers:{"Content-Type":"application/json"}})}let M=W6.safeParse(_);if(!M.success)return new Response(JSON.stringify({error:{message:`Invalid request: ${M.error.errors.map((w)=>w.message).join(", ")}`,type:"invalid_request_error"}}),{status:400,headers:{"Content-Type":"application/json"}});let{model:O,temperature:R,max_tokens:D,top_p:f,stream:K,tools:g,tool_choice:T,parallel_tool_calls:A$,messages:s$}=M.data,W$=s$.map((w)=>{if(w.role==="assistant")return{role:"assistant",content:w.content??null,...w.name?{name:w.name}:{},...w.tool_calls?{tool_calls:w.tool_calls}:{}};if(w.role==="tool")return{role:"tool",content:w.content,tool_call_id:w.tool_call_id,...w.name?{name:w.name}:{}};return{role:w.role,content:w.content,...w.name?{name:w.name}:{}}}),G$=W$.reduce((w,L)=>{if(typeof L.content!=="string")return w;return w+Math.ceil(L.content.length/4)},0),e$=G$+(D??1000),c$;if(O){let w=A().prepare("SELECT id FROM models WHERE model_id = ? AND enabled = 1").get(O);if(w)c$=w.id}if(c$===void 0)c$=r4(W$);let O$=new Set,V$=null;for(let w=0;w<T0;w++){let L;try{L=n1(e$,O$.size>0?O$:void 0,c$)}catch(b){if(V$)return new Response(JSON.stringify({error:{message:`All models rate-limited. Last error: ${V$.message}`,type:"rate_limit_error"}}),{status:429,headers:{"Content-Type":"application/json"}});else return new Response(JSON.stringify({error:{message:b.message,type:"routing_error"}}),{status:b.status??503,headers:{"Content-Type":"application/json"}})}x1(L.platform,L.modelId,L.keyId);try{if(K){let b=L.provider.streamChatCompletion(L.apiKey,W$,L.modelId,{temperature:R,max_tokens:D,top_p:f,tools:g,tool_choice:T,parallel_tool_calls:A$}),i=0,O0=new ReadableStream({async pull($0){try{let{value:V0,done:YJ}=await b.next();if(YJ){let MJ=new TextEncoder().encode(`data: [DONE]
`);$0.enqueue(MJ),$0.close(),h0(L.platform,L.modelId,L.keyId,G$+i),g0(L.modelDbId),r1(W$,L.modelDbId),x0(L.platform,L.modelId,"success",G$,i,Date.now()-G,null);return}let m0=V0,HJ=m0.choices?.[0]?.delta?.content??"";i+=Math.ceil(HJ.length/4);let _J=`data: ${JSON.stringify(m0)}
`;$0.enqueue(new TextEncoder().encode(_J))}catch(V0){$0.error(V0)}}});return new Response(O0,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Routed-Via":`${L.platform}/${L.modelId}`,...w>0?{"X-Fallback-Attempts":String(w)}:{}}})}else{let b=await L.provider.chatCompletion(L.apiKey,W$,L.modelId,{temperature:R,max_tokens:D,top_p:f,tools:g,tool_choice:T,parallel_tool_calls:A$}),i=b.usage?.total_tokens??0;return h0(L.platform,L.modelId,L.keyId,i),g0(L.modelDbId),r1(W$,L.modelDbId),x0(L.platform,L.modelId,"success",b.usage?.prompt_tokens??0,b.usage?.completion_tokens??0,Date.now()-G,null),new Response(JSON.stringify(b),{headers:{"Content-Type":"application/json","X-Routed-Via":`${L.platform}/${L.modelId}`,...w>0?{"X-Fallback-Attempts":String(w)}:{}}})}}catch(b){let i=Date.now()-G;if(x0(L.platform,L.modelId,"error",G$,0,i,b.message),G6(b)){let O0=`${L.platform}:${L.modelId}:${L.keyId}`;O$.add(O0),Z1(L.platform,L.modelId,L.keyId,120000),m1(L.modelDbId),V$=b,console.log(`[Proxy] ${b.message.slice(0,60)} from ${L.displayName}, falling back (attempt ${w+1}/${T0})`);continue}return new Response(JSON.stringify({error:{message:`Provider error (${L.displayName}): ${b.message}`,type:"provider_error"}}),{status:502,headers:{"Content-Type":"application/json"}})}}return new Response(JSON.stringify({error:{message:`All models rate-limited after ${T0} attempts. Last: ${V$?.message}`,type:"rate_limit_error"}}),{status:429,headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}function t$($){let J=$.headers.get("Authorization");if(!J||!J.startsWith("Bearer "))return{ok:!1,response:j({error:{message:"Authentication required"}},401)};let Q=J.slice(7).trim();if(!Q)return{ok:!1,response:j({error:{message:"Authentication required"}},401)};let G=A().prepare(`
SELECT s.user_id, u.username FROM sessions s
JOIN users u ON s.user_id = u.id
WHERE s.token = ? AND s.expires_at > datetime('now')
`).get(Q);if(!G)return{ok:!1,response:j({error:{message:"Invalid or expired session"}},401)};return{ok:!0,user:{id:G.user_id,username:G.username}}}import q$ from"crypto";async function e1($,J){let Q=J.pathname;if(Q==="/api/auth/login"&&$.method==="POST")try{let W=await f0($),{username:G,password:Y}=W;if(!G||!Y)return j({error:{message:"Username and password required"}},400);let X=A(),H=X.prepare("SELECT * FROM users WHERE username = ?").get(G);if(!H)return j({error:{message:"Invalid credentials"}},401);if(q$.pbkdf2Sync(Y,H.salt,1e5,64,"sha512").toString("hex")!==H.password_hash)return j({error:{message:"Invalid credentials"}},401);let M=q$.randomBytes(32).toString("hex"),O=new Date(Date.now()+604800000).toISOString();return X.prepare("INSERT INTO sessions (user_id, token, expires_at) VALUES (?, ?, ?)").run(H.id,M,O),j({user:{id:H.id,username:H.username},token:M,expiresAt:O})}catch(W){return j({error:{message:W.message}},400)}if(Q==="/api/auth/me"&&$.method==="GET"){let W=t$($);if(!W.ok)return W.response;return j({user:W.user})}if(Q==="/api/auth/logout"&&$.method==="POST"){let W=$.headers.get("Authorization");if(W?.startsWith("Bearer ")){let G=W.slice(7).trim();if(G)A().prepare("DELETE FROM sessions WHERE token = ?").run(G)}return j({success:!0})}if(Q==="/api/auth/change-password"&&$.method==="POST"){let W=t$($);if(!W.ok)return W.response;try{let G=await f0($),{currentPassword:Y,newPassword:X}=G;if(!Y||!X)return j({error:{message:"Current password and new password required"}},400);if(X.length<6)return j({error:{message:"New password must be at least 6 characters"}},400);let H=A(),_=H.prepare("SELECT * FROM users WHERE id = ?").get(W.user.id);if(q$.pbkdf2Sync(Y,_.salt,1e5,64,"sha512").toString("hex")!==_.password_hash)return j({error:{message:"Current password is incorrect"}},401);let O=q$.randomBytes(16).toString("hex"),R=q$.pbkdf2Sync(X,O,1e5,64,"sha512").toString("hex");H.prepare("UPDATE users SET password_hash = ?, salt = ? WHERE id = ?").run(R,O,W.user.id);let f=$.headers.get("Authorization").slice(7).trim();return H.prepare("DELETE FROM sessions WHERE user_id = ? AND token != ?").run(W.user.id,f),j({success:!0})}catch(G){return j({error:{message:G.message}},400)}}return new Response("Not Found",{status:404})}var $J={google:"Google AI Studio",groq:"Groq",cerebras:"Cerebras",sambanova:"SambaNova",nvidia:"NVIDIA NIM",mistral:"Mistral",openrouter:"OpenRouter",github:"GitHub Models",cohere:"Cohere",cloudflare:"Cloudflare Workers AI",zhipu:"Zhipu AI (Z.ai)"};async function JJ($,J){let Q=A(),W=Q.prepare("SELECT DISTINCT platform FROM models").all(),G=Q.prepare("SELECT DISTINCT platform FROM api_keys").all(),Y=new Set,X=[];for(let H of[...W,...G])if(!Y.has(H.platform))Y.add(H.platform),X.push({value:H.platform,label:$J[H.platform]??H.platform});for(let[H,_]of Object.entries($J))if(!Y.has(H))X.push({value:H,label:_});return X.sort((H,_)=>H.value.localeCompare(_.value)),j(X)}import t from"path";import M0 from"fs";var X6={".html":"text/html",".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject",".txt":"text/plain"};function QJ($){return async function(J){let W=new URL(J.url).pathname;if(W.startsWith("/api/")||W.startsWith("/v1/"))return null;try{let G;if(W==="/")G=t.join($,"index.html");else{let M=W.startsWith("/")?W.slice(1):W;G=t.join($,M)}if(!t.resolve(G).startsWith(t.resolve($)))return null;if(!M0.existsSync(G))if(t.extname(G)==="")G=t.join($,"index.html");else return null;if(!M0.existsSync(G))return null;if(!M0.statSync(G).isFile())return null;let H=t.extname(G).toLowerCase(),_=X6[H]??"application/octet-stream";return new Response(Bun.file(G),{headers:{"Content-Type":_,"Cache-Control":"public, max-age=31536000, immutable"}})}catch(G){return console.error("[Static] Error:",G),null}}}import B0 from"path";import{fileURLToPath as Y6}from"url";import WJ from"fs";var Z0=parseInt(process.env.PORT??"3001"),y0=process.env.HOST??"0.0.0.0",H6=import.meta.url.startsWith("file:")?Y6(import.meta.url):import.meta.url,XJ=B0.dirname(H6),l0=B0.join(XJ,"data","freeapi.db"),_6=B0.join(XJ,"web"),GJ=B0.dirname(l0);if(!WJ.existsSync(GJ))WJ.mkdirSync(GJ,{recursive:!0});async function M6(){await L1(l0),await J1(l0);let $=Bun.serve({port:Z0,hostname:y0,async fetch(J){let Q=new URL(J.url),W=Q.pathname;if(J.method==="OPTIONS")return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":J.headers.get("origin")??"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}});if(W.startsWith("/api/auth/")){let X=await e1(J,Q);return p(J,X)}if(W.startsWith("/api/")&&W!=="/api/ping"){let X=t$(J);if(!X.ok)return p(J,X.response)}if(W.startsWith("/api/keys")){let X=await b1(J,Q);return p(J,X)}if(W.startsWith("/api/models")){let X=await k1(J,Q);return p(J,X)}if(W.startsWith("/api/fallback")){let X=await p1(J,Q);return p(J,X)}if(W.startsWith("/api/analytics")){let X=await i1(J,Q);return p(J,X)}if(W.startsWith("/api/health")){let X=await d1(J,Q);return p(J,X)}if(W.startsWith("/api/settings")){let X=await o1(J,Q);return p(J,X)}if(W==="/api/platforms"){let X=await JJ(J,Q);return p(J,X)}if(W.startsWith("/v1")){let X=await s1(J,Q);return p(J,X)}if(W==="/api/ping")return p(J,B6(J));let Y=await QJ(_6)(J);if(Y)return Y;return new Response("Not Found",{status:404})},error(J){return console.error("[Server Error]",J),new Response(JSON.stringify({error:{message:J.message,type:"server_error"}}),{status:500,headers:{"Content-Type":"application/json"}})}});console.log(`
Encryption key: ${d0()}
`),console.log(`Server running on http://${y0}:${Z0}`),console.log(`Proxy endpoint: http://${y0}:${Z0}/v1/chat/completions`),V1(),S1()}M6().catch(console.error);function p($,J){let Q=$.headers.get("origin"),W=new Headers(J.headers);if(Q)W.set("Access-Control-Allow-Origin",Q);return W.set("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),W.set("Access-Control-Allow-Headers","Content-Type, Authorization, X-Requested-With"),W.set("Access-Control-Allow-Credentials","true"),new Response(J.body,{status:J.status,statusText:J.statusText,headers:W})}function B6($){let J={status:"ok",timestamp:new Date().toISOString(),clientInfo:{method:$.method,url:$.url,path:new URL($.url).pathname,query:Object.fromEntries(new URL($.url).searchParams),clientIP:$.headers.get("x-forwarded-for")??$.headers.get("x-real-ip")??"unknown",userAgent:$.headers.get("user-agent")??"",clientHost:$.headers.get("host")??"",referer:$.headers.get("referer")??"",origin:$.headers.get("origin")??""},serverInfo:{timestamp:new Date().toISOString(),uptime:process.uptime(),memoryUsage:process.memoryUsage(),bunVersion:Bun.version,pid:process.pid}};return console.log(`
=== CLIENT CONNECTION DEBUG ===`),console.log(`Timestamp: ${J.timestamp}`),console.log(`Client IP: ${J.clientInfo.clientIP}`),console.log(`User Agent: ${J.clientInfo.userAgent}`),console.log(`Request URL: ${J.clientInfo.url}`),console.log(`=== END DEBUG ===
`),new Response(JSON.stringify(J),{headers:{"Content-Type":"application/json"}})}