@cortexkit/opencode-openai-auth 0.4.3 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +8 -4
  2. package/dist/cli.js +1 -1
  3. package/dist/codex-http.d.ts +1 -1
  4. package/dist/commands.d.ts +6 -0
  5. package/dist/core/accounts.d.ts +6 -1
  6. package/dist/core/background-quota-refresh.d.ts +46 -0
  7. package/dist/core/cachekeep.d.ts +4 -0
  8. package/dist/core/oauth.d.ts +1 -1
  9. package/dist/core/quota-manager.d.ts +11 -4
  10. package/dist/core/refresh-all-quota.d.ts +12 -1
  11. package/dist/core/sticky-routing.d.ts +43 -0
  12. package/dist/dump.d.ts +1 -0
  13. package/dist/{index-xcf8tm40.js → index-6rnw2cgs.js} +1 -1
  14. package/dist/index-j1364eag.js +89 -0
  15. package/dist/index-rfgyxxxq.js +1 -0
  16. package/dist/index-s5fbqqwx.js +3 -0
  17. package/dist/index-vrdc90yd.js +6 -0
  18. package/dist/index-wnxfzjfr.js +2 -0
  19. package/dist/{index-xbq3aq6f.js → index-wpd7mg3p.js} +1 -1
  20. package/dist/index-zkzb0twr.js +2 -0
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +99 -86
  23. package/dist/{quota-normalize-754rewnb.js → quota-normalize-n02dfdx0.js} +1 -1
  24. package/dist/rpc/port-file.d.ts +4 -0
  25. package/dist/rpc/port-file.js +1 -1
  26. package/dist/rpc/protocol.d.ts +1 -0
  27. package/dist/rpc/rpc-client.js +1 -1
  28. package/dist/rpc/rpc-dir.d.ts +6 -0
  29. package/dist/rpc/rpc-dir.js +1 -1
  30. package/dist/rpc/rpc-server.d.ts +2 -0
  31. package/dist/sidebar-state.d.ts +44 -5
  32. package/dist/sidebar-state.js +1 -1
  33. package/dist/{token-xsc39hv8.js → token-5hdnazxp.js} +1 -1
  34. package/dist/token-util-3d2nj45d.js +1 -0
  35. package/dist/tui-preferences.js +1 -1
  36. package/dist/tui.d.ts +9 -0
  37. package/dist/version.d.ts +1 -1
  38. package/package.json +2 -2
  39. package/src/rpc/port-file.ts +115 -8
  40. package/src/rpc/protocol.ts +1 -0
  41. package/src/rpc/rpc-dir.ts +31 -7
  42. package/src/rpc/rpc-server.ts +18 -2
  43. package/src/sidebar-state.ts +744 -27
  44. package/src/tui/command-dialogs.tsx +25 -3
  45. package/src/tui-compiled/rpc/port-file.ts +115 -8
  46. package/src/tui-compiled/rpc/protocol.ts +1 -0
  47. package/src/tui-compiled/rpc/rpc-dir.ts +31 -7
  48. package/src/tui-compiled/sidebar-state.ts +744 -27
  49. package/src/tui-compiled/tui/command-dialogs.tsx +17 -4
  50. package/src/tui-compiled/tui.tsx +50 -15
  51. package/src/tui.tsx +57 -19
  52. package/dist/index-9k2gxqc1.js +0 -89
  53. package/dist/index-ptsh66z7.js +0 -2
  54. package/dist/index-rckqt97a.js +0 -1
  55. package/dist/index-reagbdg3.js +0 -2
  56. package/dist/index-ya6hw803.js +0 -7
  57. package/dist/token-util-xzavn760.js +0 -1
package/dist/index.js CHANGED
@@ -1,155 +1,168 @@
1
- import{d as C4,e as b0,f as FW}from"./index-2ng03cby.js";import{A as A6,B as n1,C as BN,D as O2,E as W2,G as S4,H as G2,I as u6,J as r$,K as L$,L as R0,M as DN,N as KN,O as Q2,P as w2,Q as H2,h as dW,i as oW,j as tW,k as aW,l as sW,m as eW,n as $2,o as I0,p as S0,q as M0,s as U2,t as J2,u as z2,v as X2,w as j2,x as Y2,y as kN,z as CN}from"./index-9k2gxqc1.js";import{T as L2,ca as B2,da as qN,ea as D2,fa as K2}from"./index-reagbdg3.js";import{ka as s1,la as lN,ma as q$,na as N2}from"./index-ya6hw803.js";import{oa as G8}from"./index-ptsh66z7.js";import{ra as V2}from"./index-rckqt97a.js";import{ua as w6}from"./index-xbq3aq6f.js";import{mkdirSync as RD,readFileSync as ID,renameSync as SD,statSync as kD,writeFileSync as CD}from"node:fs";import VN from"node:os";import{join as ZD}from"node:path";import{readFileSync as A2}from"node:fs";import{homedir as E2,tmpdir as M2}from"node:os";import{join as t1}from"node:path";var b2="https://chatgpt.com/backend-api/codex/responses",R2="openai-auth.json",W6={noWebSearch:"CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH",webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function a1(){let $=process.env[W6.configDir]?.trim();if($)return $;return t1(process.env.XDG_CONFIG_HOME||t1(E2(),".config"),"opencode")}function D$(){return process.env[W6.configFile]?.trim()||t1(a1(),R2)}function I2(){try{let $=JSON.parse(A2(D$(),"utf8"));return $!=null&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function IN($){let U=process.env[$];if(U===void 0)return;let z=U.trim().toLowerCase();if(z==="1"||z==="true"||z==="yes"||z==="on")return!0;if(z===""||z==="0"||z==="false"||z==="no"||z==="off")return!1;return}function o1($,U,z){let X=IN($);if(X!==void 0)return X;if(typeof U==="boolean")return U;return z}function S2(){let $=I2(),U=IN(W6.noWebSearch),z=U!==void 0?!U:typeof $.webSearch==="boolean"?$.webSearch:!0,X;if($.dump!==void 0&&$.dump!==null){if(typeof $.dump==="object")X=$.dump.enabled;else if(typeof $.dump==="boolean")X=$.dump}return{webSearch:z,webSockets:o1(W6.webSockets,$.webSockets,!1),rawWebSocket:o1(W6.rawWebSocket,$.rawWebSocket,!1),responsesLite:o1(W6.responsesLite,$.responsesLite,!1),dump:o1(W6.dump,X,!1),dumpDir:process.env[W6.dumpDir]?.trim()||(typeof $.dumpDir==="string"&&$.dumpDir.trim()?$.dumpDir.trim():t1(M2(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[W6.codexApiEndpoint]?.trim()||(typeof $.codexApiEndpoint==="string"&&$.codexApiEndpoint.trim()?$.codexApiEndpoint.trim():b2)}}var Z0;function g$(){if(!Z0)Z0=S2();return Z0}var T0="openai-quota",g0="openai-account",x0="openai-routing",f0="openai-killswitch",h0="openai-dump",y0="openai-logging",c0="openai-cachekeep",ZN=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep"],K$=q$("commands");function SN($){return $==="fallback-first"?"Try usable fallback accounts before the main account.":"Try the main account first. Use fallback accounts only when required."}async function k2($){let U=await $.refreshAllQuota?.(),z=$.quotaManager.getMain(),X=["## OpenAI Quota",""];if(z?.quota){let Y=z.quota;X.push("### Main account");for(let N of["primary","secondary"]){let W=Y[N];if(W){let G=Math.round(W.usedPercent),Q="█".repeat(Math.max(0,Math.min(Math.round(G/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(G/10),10)));X.push(`- ${N}: ${Q} ${G}% used (${Math.round(W.remainingPercent)}% remaining)`)}}if(Y.resetCreditsAvailable!==void 0)X.push(`- resets: ${Y.resetCreditsAvailable}`)}else X.push("No main quota snapshot available. Send a request first.");let j=[...$.quotaManager.getAllFallbacks().entries()].filter(([,Y])=>Y);if(j.length>0){X.push(""),X.push("### Fallback accounts");for(let[Y,N]of j){if(!N?.quota)continue;X.push(`**${Y}**`);for(let W of["primary","secondary"]){let G=N.quota[W];if(G){let Q=Math.round(G.usedPercent);X.push(` - ${W}: ${Q}% used (${Math.round(G.remainingPercent)}% remaining)`)}}if(N.quota.resetCreditsAvailable!==void 0)X.push(` - resets: ${N.quota.resetCreditsAvailable}`)}}if(U?.length){let Y=U.filter((N)=>!N.ok);if(Y.length>0){X.push("");for(let N of Y)X.push(`- ${N.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:X.join(`
2
- `),knobs:{}}}async function C2($,U){let z=$.trim().split(/\s+/).filter(Boolean),X=await U.loadAccounts(U.accountStoragePath)??{version:1,accounts:[]},J=X.accounts??[];if(z.length===0){let j=["## OpenAI Accounts",""];if(J.length===0)j.push("No accounts configured. Use `/login openai` to add your main account, or `/openai-account add` to add a fallback account.");else{let Y=X.routing?.mode??"main-first";j.push(`Routing: \`${Y}\` (set with \`/openai-routing\`).`),j.push("");for(let N of J){let W=N.type??"oauth";j.push(`- \`${N.id}\` (${W})`)}}return j.push(""),j.push("Commands: `/openai-account add [label]` | `/openai-account remove <id>`"),{command:"openai-account",text:j.join(`
3
- `),knobs:{accounts:J}}}if(z[0]==="remove"&&z[1]){let j=z[1],Y=!1,N=await L$((W)=>{let G=W.accounts.findIndex((Q)=>Q.id===j);if(G===-1)return W;return Y=!0,W.accounts.splice(G,1),W},U.accountStoragePath);if(!Y)return{command:"openai-account",text:`## Account Not Found
1
+ import{d as E1,e as WY,f as DG}from"./index-2ng03cby.js";import{A as o0,B as b1,C as Y8,D as GW,E as WW,G as q1,H as zW,I as H1,J as A0,K as X0,L as zY,M as KY,N as h9,O as UY,P as KW,Q as UW,R as HW,h as iG,i as nG,j as oG,k as rG,l as sG,m as aG,n as tG,o as LY,p as NY,q as eY,s as eG,t as YW,u as XW,v as JW,w as QW,x as $W,y as GX,z as WX}from"./index-j1364eag.js";import{T as P8,W as HY,X as LW,_ as L1,ca as NW,da as VW,ea as BW,ja as ZW,ka as X8,la as OW,ma as FW,na as qW,oa as jW}from"./index-wnxfzjfr.js";import{ta as PY}from"./index-vrdc90yd.js";import{ua as lX,va as dX}from"./index-zkzb0twr.js";import{xa as DY,ya as EX,za as L0}from"./index-s5fbqqwx.js";import{Ca as DW}from"./index-rfgyxxxq.js";import{Fa as g8}from"./index-wpd7mg3p.js";import{mkdirSync as wN,readFileSync as EN,renameSync as MN,statSync as AN,writeFileSync as RN}from"node:fs";import x9 from"node:os";import{join as TN}from"node:path";import{readFileSync as SW}from"node:fs";import{homedir as kW,tmpdir as bW}from"node:os";import{join as qY}from"node:path";var xW="https://chatgpt.com/backend-api/codex/responses",vW="openai-auth.json",m0={noWebSearch:"CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH",webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function jY(){let Y=process.env[m0.configDir]?.trim();if(Y)return Y;return qY(process.env.XDG_CONFIG_HOME||qY(kW(),".config"),"opencode")}function U0(){return process.env[m0.configFile]?.trim()||qY(jY(),vW)}function hW(){try{let Y=JSON.parse(SW(U0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function QX(Y){let X=process.env[Y];if(X===void 0)return;let J=X.trim().toLowerCase();if(J==="1"||J==="true"||J==="yes"||J==="on")return!0;if(J===""||J==="0"||J==="false"||J==="no"||J==="off")return!1;return}function FY(Y,X,J){let Q=QX(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function gW(){let Y=hW(),X=QX(m0.noWebSearch),J=X!==void 0?!X:typeof Y.webSearch==="boolean"?Y.webSearch:!0,Q;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")Q=Y.dump.enabled;else if(typeof Y.dump==="boolean")Q=Y.dump}return{webSearch:J,webSockets:FY(m0.webSockets,Y.webSockets,!1),rawWebSocket:FY(m0.rawWebSocket,Y.rawWebSocket,!1),responsesLite:FY(m0.responsesLite,Y.responsesLite,!1),dump:FY(m0.dump,Q,!1),dumpDir:process.env[m0.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():qY(bW(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[m0.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():xW)}}var W8;function w0(){if(!W8)W8=gW();return W8}var z8="openai-quota",K8="openai-account",U8="openai-routing",H8="openai-killswitch",L8="openai-dump",N8="openai-logging",V8="openai-cachekeep",zX=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep"],G0=L0("commands");function $X(Y){if(Y==="fallback-first")return"Try usable fallback accounts before the main account.";if(Y==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}async function yW(Y){let X=await Y.refreshAllQuota?.(),J=Y.quotaManager.getMain(),Q=["## OpenAI Quota",""];if(J?.quota){let W=J.quota;Q.push("### Main account");for(let K of["primary","secondary"]){let H=W[K];if(H){let U=Math.round(H.usedPercent),N="█".repeat(Math.max(0,Math.min(Math.round(U/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(U/10),10)));Q.push(`- ${K}: ${N} ${U}% used (${Math.round(H.remainingPercent)}% remaining)`)}}if(W.resetCreditsAvailable!==void 0)Q.push(`- resets: ${W.resetCreditsAvailable}`)}else Q.push("No main quota snapshot available. Send a request first.");let G=[...Y.quotaManager.getAllFallbacks().entries()].filter(([,W])=>W);if(G.length>0){Q.push(""),Q.push("### Fallback accounts");for(let[W,K]of G){if(!K?.quota)continue;Q.push(`**${W}**`);for(let H of["primary","secondary"]){let U=K.quota[H];if(U){let N=Math.round(U.usedPercent);Q.push(` - ${H}: ${N}% used (${Math.round(U.remainingPercent)}% remaining)`)}}if(K.quota.resetCreditsAvailable!==void 0)Q.push(` - resets: ${K.quota.resetCreditsAvailable}`)}}if(X?.length){let W=X.filter((K)=>!K.ok);if(W.length>0){Q.push("");for(let K of W)Q.push(`- ${K.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:Q.join(`
2
+ `),knobs:{}}}async function fW(Y,X){let J=Y.trim().split(/\s+/).filter(Boolean),Q=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},$=Q.accounts??[];if(J.length===0){let G=["## OpenAI Accounts",""];if($.length===0)G.push("No accounts configured. Use `/login openai` to add your main account, or `/openai-account add` to add a fallback account.");else{let W=Q.routing?.mode??"main-first";G.push(`Routing: \`${W}\` (set with \`/openai-routing\`). Modes: main-first, fallback-first, or sticky-balanced. \`/openai-routing reset\` clears this session's pin.`),G.push("");for(let K of $){let H=K.type??"oauth";G.push(`- \`${K.id}\` (${H})`)}}return G.push(""),G.push("Commands: `/openai-account add [label]` | `/openai-account remove <id>`"),{command:"openai-account",text:G.join(`
3
+ `),knobs:{accounts:$}}}if(J[0]==="remove"&&J[1]){let G=J[1],W=!1,K=await X0((H)=>{let U=H.accounts.findIndex((N)=>N.id===G);if(U===-1)return H;return W=!0,H.accounts.splice(U,1),H},X.accountStoragePath);if(!W)return{command:"openai-account",text:`## Account Not Found
4
4
 
5
- No account with id \`${j}\` exists.`,knobs:{accounts:N.accounts}};return K$.info("account removed",{id:j}),U.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
5
+ No account with id \`${G}\` exists.`,knobs:{accounts:K.accounts}};return G0.info("account removed",{id:G}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
6
6
 
7
- Removed account \`${j}\`.`,knobs:{accounts:N.accounts}}}if(z[0]==="order"&&z.length>=3){let j=!1,Y=await L$((N)=>{let W=N.accounts.findIndex((L)=>L.id===z[1]),G=N.accounts.findIndex((L)=>L.id===z[2]);if(W===-1||G===-1)return N;j=!0;let Q=N.accounts[W];return N.accounts[W]=N.accounts[G],N.accounts[G]=Q,N},U.accountStoragePath);if(!j)return{command:"openai-account",text:`## Invalid Order
7
+ Removed account \`${G}\`.`,knobs:{accounts:K.accounts}}}if(J[0]==="order"&&J.length>=3){let G=!1,W=await X0((K)=>{let H=K.accounts.findIndex((O)=>O.id===J[1]),U=K.accounts.findIndex((O)=>O.id===J[2]);if(H===-1||U===-1)return K;G=!0;let N=K.accounts[H];return K.accounts[H]=K.accounts[U],K.accounts[U]=N,K},X.accountStoragePath);if(!G)return{command:"openai-account",text:`## Invalid Order
8
8
 
9
- Both account IDs must exist.`,knobs:{accounts:Y.accounts}};return K$.info("accounts reordered",{a:z[1],b:z[2]}),U.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Accounts Reordered
9
+ Both account IDs must exist.`,knobs:{accounts:W.accounts}};return G0.info("accounts reordered",{a:J[1],b:J[2]}),X.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Accounts Reordered
10
10
 
11
- Swapped positions of \`${z[1]}\` and \`${z[2]}\`.`,knobs:{accounts:Y.accounts}}}if(z[0]==="add"){let j=z.includes("--headless"),Y=z.filter((w)=>w!=="add"&&w!=="--headless"),N=Y.length>0?Y.join(" "):void 0,{url:W,instructions:G,completion:Q}=await CN({label:N,headless:j}),L=U.notify,H=U.sessionId;if(Q.then(async(w)=>{let B=!1;if(await L$((q)=>{if(w.accountId&&q.mainAccountId&&w.accountId===q.mainAccountId)return B=!0,q;return kN(q.accounts,w),q},U.accountStoragePath),B){K$.warn("account add rejected (main identity)",{id:w.id,sessionId:H}),L?.({command:"openai-account",text:`## Add Failed
11
+ Swapped positions of \`${J[1]}\` and \`${J[2]}\`.`,knobs:{accounts:W.accounts}}}if(J[0]==="add"){let G=J.includes("--headless"),W=J.filter((L)=>L!=="add"&&L!=="--headless"),K=W.length>0?W.join(" "):void 0,{url:H,instructions:U,completion:N}=await WX({label:K,headless:G}),O=X.notify,B=X.sessionId;if(N.then(async(L)=>{let Z=!1;if(await X0((j)=>{if(L.accountId&&j.mainAccountId&&L.accountId===j.mainAccountId)return Z=!0,j;return GX(j.accounts,L),j},X.accountStoragePath),Z){G0.warn("account add rejected (main identity)",{id:L.id,sessionId:B}),O?.({command:"openai-account",text:`## Add Failed
12
12
 
13
- ${"That account is already your main account — not added as a fallback."}`,knobs:{}});return}K$.info("account added",{id:w.id,label:w.label}),U.refreshSidebar?.().catch(()=>{}),L?.({command:"openai-account",text:`## Account Added
13
+ ${"That account is already your main account — not added as a fallback."}`,knobs:{}});return}G0.info("account added",{id:L.id,label:L.label}),X.refreshSidebar?.().catch(()=>{}),O?.({command:"openai-account",text:`## Account Added
14
14
 
15
- Added account \`${w.id}\`${w.label?` ("${w.label}")`:""}.
15
+ Added account \`${L.id}\`${L.label?` ("${L.label}")`:""}.
16
16
 
17
- Run \`/openai-account\` to confirm.`,knobs:{}})}).catch((w)=>{let B=w instanceof Error?w.message:String(w??"unknown error");K$.warn("account add failed",{error:B,sessionId:H}),L?.({command:"openai-account",text:`## Add Failed
17
+ Run \`/openai-account\` to confirm.`,knobs:{}})}).catch((L)=>{let Z=L instanceof Error?L.message:String(L??"unknown error");G0.warn("account add failed",{error:Z,sessionId:B}),O?.({command:"openai-account",text:`## Add Failed
18
18
 
19
- Account add failed: ${B}`,knobs:{}})}),j){let w=G.match(/Enter code: (.+)/)?.[1]??G;return{command:"openai-account",text:`## Device Code
19
+ Account add failed: ${Z}`,knobs:{}})}),G){let L=U.match(/Enter code: (.+)/)?.[1]??U;return{command:"openai-account",text:`## Device Code
20
20
 
21
21
  1. Open this verification URL:
22
22
 
23
- ${W}
23
+ ${H}
24
24
 
25
- 2. Enter the code: **${w}**
25
+ 2. Enter the code: **${L}**
26
26
 
27
- ${G}
27
+ ${U}
28
28
 
29
- The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:W,userCode:w,instructions:G}}}return{command:"openai-account",text:`## Add OpenAI Account
29
+ The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:H,userCode:L,instructions:U}}}return{command:"openai-account",text:`## Add OpenAI Account
30
30
 
31
31
  Open this URL and complete sign-in:
32
32
 
33
- ${W}
33
+ ${H}
34
34
 
35
- ${G}
35
+ ${U}
36
36
 
37
- The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:W,instructions:G}}}return{command:"openai-account",text:"## Account Commands\n\n- `/openai-account` — show accounts\n- `/openai-account add [label]` — add a new account\n- `/openai-account remove <id>` — remove\n- `/openai-account order <a> <b>` — swap fallback positions\n\nRouting is set with `/openai-routing` (main-first / fallback-first).",knobs:{accounts:J}}}async function Z2($,U){let z=$.trim().toLowerCase().split(/\s+/).filter(Boolean),J=(await U.loadAccounts(U.accountStoragePath)??{version:1,accounts:[]}).routing?.mode??"main-first";if(z.length===1&&(z[0]==="main-first"||z[0]==="fallback-first")){let j=z[0];return await L$((Y)=>{return Y.routing={...Y.routing??{},mode:j},Y},U.accountStoragePath),K$.info("routing mode changed",{mode:j}),{command:"openai-routing",text:`## OpenAI Routing Updated
37
+ The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:H,instructions:U}}}return{command:"openai-account",text:"## Account Commands\n\n- `/openai-account` — show accounts\n- `/openai-account add [label]` — add a new account\n- `/openai-account remove <id>` — remove\n- `/openai-account order <a> <b>` — swap fallback positions\n\nRouting modes are `main-first`, `fallback-first`, and `sticky-balanced`. `/openai-routing reset` clears the current session pin.",knobs:{accounts:$}}}async function mW(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=(await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]}).routing?.mode??"main-first";if(J.length===1&&J[0]==="reset"){if(!X.sessionId)return{command:"openai-routing",text:`## OpenAI Routing Reset
38
38
 
39
- Mode: \`${j}\`
40
- - ${SN(j)}
39
+ No current session is available, so no pin was changed.`,knobs:{mode:$}};if(!X.clearStickyRouting)return{command:"openai-routing",text:`## OpenAI Routing Reset
41
40
 
42
- Usage: \`/openai-routing\`, \`/openai-routing main-first\`, or \`/openai-routing fallback-first\`.`,knobs:{mode:j}}}return{command:"openai-routing",text:`## OpenAI Routing
41
+ This runtime cannot clear the current session pin.`,knobs:{mode:$}};return await X.clearStickyRouting(X.sessionId),G0.info("routing session pin cleared"),{command:"openai-routing",text:`## OpenAI Routing Reset
43
42
 
44
- - Mode: \`${J}\`
45
- - ${SN(J)}
43
+ This session's pin was cleared. The next request may choose the same account if it remains the best selection.`,knobs:{mode:$}}}if(J.length===1&&(J[0]==="main-first"||J[0]==="fallback-first"||J[0]==="sticky-balanced")){let K=J[0];return await X0((H)=>{return H.routing={...H.routing??{},mode:K},H},X.accountStoragePath),G0.info("routing mode changed",{mode:K}),{command:"openai-routing",text:`## OpenAI Routing Updated
46
44
 
47
- Usage: \`/openai-routing\`, \`/openai-routing main-first\`, or \`/openai-routing fallback-first\`.`,knobs:{mode:J}}}async function T2($,U){let z=await U.loadAccounts(U.accountStoragePath)??{version:1,accounts:[]},X=z.killswitch??{},J=(z.accounts??[]).filter((Y)=>Y.enabled!==!1).map((Y)=>Y.id),j=$.trim().toLowerCase().split(/\s+/).filter(Boolean);if(j.length===0){let Y=X.enabled===!0,N=["## Killswitch","",`Status: **${Y?"ON":"OFF"}**`];if(Y){N.push(""),N.push("| Account | primary threshold | secondary threshold |"),N.push("| ------- | ------------ | ------------ |");let W=X.main??{},G=W.primary??W["5h"]??u6.primary,Q=W.secondary??W["1w"]??u6.secondary;N.push(`| main | ≥ ${G}% | ≥ ${Q}% |`);for(let L of J){let H=X.accounts?.[L]??X.main??{},w=H.primary??H["5h"]??u6.primary,B=H.secondary??H["1w"]??u6.secondary;N.push(`| ${L} | ≥ ${w}% | ≥ ${B}% |`)}}return N.push(""),N.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:N.join(`
48
- `),knobs:{config:X,accountIds:J}}}if(j[0]==="on"){let Y={...X,enabled:!0,main:X.main??{primary:u6.primary,secondary:u6.secondary}};return await L$((N)=>{return N.killswitch=Y,N},U.accountStoragePath),K$.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:Y,accountIds:J}}}if(j[0]==="off"){let Y={...X,enabled:!1};return await L$((N)=>{return N.killswitch=Y,N},U.accountStoragePath),K$.info("killswitch disabled"),{command:"openai-killswitch",text:"## Killswitch Disabled",knobs:{config:Y,accountIds:J}}}if(j[0]==="set"&&j.length>1){let Y={...X,enabled:!0,accounts:{...X.accounts??{}}};for(let N=1;N<j.length;N++){let W=j[N]?.match(/^([^:]+):(\d+),(\d+)$/);if(!W)continue;let[,G,Q,L]=W,H={primary:Number.parseInt(Q,10),secondary:Number.parseInt(L,10)};if(G==="main")Y.main=H;else if(G==="all"){Y.main=H;for(let w of J)Y.accounts[w]=H}else Y.accounts[G]=H}return await L$((N)=>{return N.killswitch=Y,N},U.accountStoragePath),K$.info("killswitch thresholds updated",{count:j.length-1}),{command:"openai-killswitch",text:"## Killswitch Updated",knobs:{config:Y,accountIds:J}}}return{command:"openai-killswitch",text:"Usage: `/openai-killswitch`, `/openai-killswitch on`, `/openai-killswitch off`, `/openai-killswitch set <acct>:<5h>,<1w> ...`",knobs:{config:X,accountIds:J}}}async function g2($,U){let z=$.trim().toLowerCase().split(/\s+/).filter(Boolean),X=g$(),J=X.dump;if(z.length===0)return{command:"openai-dump",text:`## Request Dump
45
+ Mode: \`${K}\`
46
+ - ${$X(K)}
49
47
 
50
- - Enabled: ${J?"ON":"OFF"}
51
- - Directory: ${X.dumpDir}
48
+ Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:K}}}let G=$==="sticky-balanced"&&X.sessionId?await X.getStickyRouting?.(X.sessionId):void 0,W=$==="sticky-balanced"?G?`
49
+ - Session pin: \`${G}\`. Use \`/openai-routing reset\` to clear it.`:`
50
+ - Session pin: none yet. A request will choose one when a usable account is available.`:"";return{command:"openai-routing",text:`## OpenAI Routing
52
51
 
53
- Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:J}};if(z[0]==="on")return await L$((j)=>{return j.dump={...j.dump??{},enabled:!0},j},U.accountStoragePath),K$.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
52
+ - Mode: \`${$}\`
53
+ - ${$X($)}${W}
54
54
 
55
- Dump directory: ${X.dumpDir}
55
+ Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:$}}}async function cW(Y,X){let J=await X.loadAccounts(X.accountStoragePath)??{version:1,accounts:[]},Q=J.killswitch??{},$=(J.accounts??[]).filter((W)=>W.enabled!==!1).map((W)=>W.id),G=Y.trim().toLowerCase().split(/\s+/).filter(Boolean);if(G.length===0){let W=Q.enabled===!0,K=["## Killswitch","",`Status: **${W?"ON":"OFF"}**`];if(W){K.push(""),K.push("| Account | primary threshold | secondary threshold |"),K.push("| ------- | ------------ | ------------ |");let H=Q.main??{},U=H.primary??H["5h"]??H1.primary,N=H.secondary??H["1w"]??H1.secondary;K.push(`| main | ≥ ${U}% | ≥ ${N}% |`);for(let O of $){let B=Q.accounts?.[O]??Q.main??{},L=B.primary??B["5h"]??H1.primary,Z=B.secondary??B["1w"]??H1.secondary;K.push(`| ${O} | ≥ ${L}% | ≥ ${Z}% |`)}}return K.push(""),K.push("Commands: `/openai-killswitch on` | `/openai-killswitch off` | `/openai-killswitch set <acct>:<5h>,<1w> ...`"),{command:"openai-killswitch",text:K.join(`
56
+ `),knobs:{config:Q,accountIds:$}}}if(G[0]==="on"){let W={...Q,enabled:!0,main:Q.main??{primary:H1.primary,secondary:H1.secondary}};return await X0((K)=>{return K.killswitch=W,K},X.accountStoragePath),G0.info("killswitch enabled"),{command:"openai-killswitch",text:"## Killswitch Enabled",knobs:{config:W,accountIds:$}}}if(G[0]==="off"){let W={...Q,enabled:!1};return await X0((K)=>{return K.killswitch=W,K},X.accountStoragePath),G0.info("killswitch disabled"),{command:"openai-killswitch",text:"## Killswitch Disabled",knobs:{config:W,accountIds:$}}}if(G[0]==="set"&&G.length>1){let W={...Q,enabled:!0,accounts:{...Q.accounts??{}}};for(let K=1;K<G.length;K++){let H=G[K]?.match(/^([^:]+):(\d+),(\d+)$/);if(!H)continue;let[,U,N,O]=H,B={primary:Number.parseInt(N,10),secondary:Number.parseInt(O,10)};if(U==="main")W.main=B;else if(U==="all"){W.main=B;for(let L of $)W.accounts[L]=B}else W.accounts[U]=B}return await X0((K)=>{return K.killswitch=W,K},X.accountStoragePath),G0.info("killswitch thresholds updated",{count:G.length-1}),{command:"openai-killswitch",text:"## Killswitch Updated",knobs:{config:W,accountIds:$}}}return{command:"openai-killswitch",text:"Usage: `/openai-killswitch`, `/openai-killswitch on`, `/openai-killswitch off`, `/openai-killswitch set <acct>:<5h>,<1w> ...`",knobs:{config:Q,accountIds:$}}}async function uW(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=w0(),$=Q.dump;if(J.length===0)return{command:"openai-dump",text:`## Request Dump
56
57
 
57
- Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}};if(z[0]==="off")return await L$((j)=>{return j.dump={...j.dump??{},enabled:!1},j},U.accountStoragePath),K$.info("request dump disabled"),{command:"openai-dump",text:"## Request Dump Disabled",knobs:{enabled:!1}};return{command:"openai-dump",text:"Usage: `/openai-dump`, `/openai-dump on`, or `/openai-dump off`.",knobs:{enabled:J}}}async function x2($,U){let z=$.trim().toLowerCase().split(/\s+/).filter(Boolean),X=["error","warn","info","debug","trace"];if(z.length===0){let Y=(await U.loadAccounts(U.accountStoragePath))?.logging?.level??"info";return{command:"openai-logging",text:`## Logging
58
+ - Enabled: ${$?"ON":"OFF"}
59
+ - Directory: ${Q.dumpDir}
58
60
 
59
- - Level: \`${Y}\`
61
+ Usage: \`/openai-dump on\` or \`/openai-dump off\``,knobs:{enabled:$}};if(J[0]==="on")return await X0((G)=>{return G.dump={...G.dump??{},enabled:!0},G},X.accountStoragePath),G0.info("request dump enabled"),{command:"openai-dump",text:`## Request Dump Enabled
60
62
 
61
- Valid levels: ${X.map((N)=>`\`${N}\``).join(", ")}
63
+ Dump directory: ${Q.dumpDir}
62
64
 
63
- Usage: \`/openai-logging <level>\``,knobs:{level:Y}}}let J=z[0];if(J&&X.includes(J)){let j=J;return s1(j),await L$((Y)=>{return Y.logging={...Y.logging??{},level:j},Y},U.accountStoragePath),K$.info("log level changed",{level:j}),{command:"openai-logging",text:`## Logging Updated
65
+ Warning: body dumps may contain prompt/session content. Turn this off after debugging.`,knobs:{enabled:!0}};if(J[0]==="off")return await X0((G)=>{return G.dump={...G.dump??{},enabled:!1},G},X.accountStoragePath),G0.info("request dump disabled"),{command:"openai-dump",text:"## Request Dump Disabled",knobs:{enabled:!1}};return{command:"openai-dump",text:"Usage: `/openai-dump`, `/openai-dump on`, or `/openai-dump off`.",knobs:{enabled:$}}}async function pW(Y,X){let J=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),Q=["error","warn","info","debug","trace"];if(J.length===0){let W=(await X.loadAccounts(X.accountStoragePath))?.logging?.level??"info";return{command:"openai-logging",text:`## Logging
64
66
 
65
- Level set to \`${j}\`.`,knobs:{level:j}}}return{command:"openai-logging",text:`## Invalid Level
67
+ - Level: \`${W}\`
66
68
 
67
- Valid levels: ${X.map((j)=>`\`${j}\``).join(", ")}`,knobs:{level:"info"}}}function f2($){let U=/^(\d{1,2})-(\d{1,2})$/.exec($.trim());if(!U)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let z=Number(U[1]),X=Number(U[2]);if(!Number.isInteger(z)||!Number.isInteger(X)||z<0||z>23||X<0||X>23||z===X)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:z,endHour:X}}async function h2($,U){let z=U.cacheKeepManager,X=$.trim().toLowerCase().split(/\s+/).filter(Boolean),J=await U.loadAccounts(U.accountStoragePath),j=J?.cachekeep?.enabled===!0;if(X.length===0||X[0]==="status"){if(!z)return{command:"openai-cachekeep",text:`## Cachekeep
69
+ Valid levels: ${Q.map((K)=>`\`${K}\``).join(", ")}
68
70
 
69
- Status: **not available** (manager not wired)`,knobs:{}};let N=z.status(),W=N.window,G=W?`${String(W.startHour).padStart(2,"0")}-${String(W.endHour).padStart(2,"0")}`:"always (no window)",Q=["## Cachekeep","",`Status: **${j?"ON":"OFF"}**`,`Timer: **${N.running?"armed":"idle"}**`,`Subagent warming: **${J?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Window: **${G}**`];if(Q.push(`Tracked sessions: **${N.tracked}**`),N.targets.length>0){Q.push("");for(let H of N.targets){let w=H.sessionKey.length>12?`${H.sessionKey.slice(0,12)}…`:H.sessionKey,B=Math.ceil((H.cacheExpiresAt-N.generatedAt)/1000);Q.push(`- \`${w}\` (${H.accountId??"main"}) — expires in ${B}s`+(H.lastWarmedAt?`, last warm ${Math.ceil((N.generatedAt-H.lastWarmedAt)/1000)}s ago`:"")+(H.backoffUntil&&H.backoffUntil>N.generatedAt?`, backoff ${Math.ceil((H.backoffUntil-N.generatedAt)/1000)}s`:""))}}Q.push(""),Q.push(`TTL: ${Math.round(N.ttlMs/1000)}s | Lead: ${Math.round(N.leadMs/1000)}s | Max idle warm: ${Math.round(N.maxIdleWarmMs/60000)}min`),Q.push(""),Q.push("Commands: `/openai-cachekeep on` | `/openai-cachekeep off` | `/openai-cachekeep HH-HH` | `/openai-cachekeep window clear` | `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off` | `/openai-cachekeep`");let L=Math.max(0,...N.targets.map((H)=>H.lastWarmedAt??0));return{command:"openai-cachekeep",text:Q.join(`
70
- `),knobs:{enabled:j,subagents:J?.cachekeep?.subagents===!0,window:W,running:N.running,tracked:N.tracked,lastWarmAt:L||void 0,generatedAt:N.generatedAt,maxIdleWarmMs:N.maxIdleWarmMs,maxSubagentIdleMs:N.maxSubagentIdleMs}}}if(X[0]==="on"){if(!z)return{command:"openai-cachekeep",text:`## Cachekeep
71
+ Usage: \`/openai-logging <level>\``,knobs:{level:W}}}let $=J[0];if($&&Q.includes($)){let G=$;return DY(G),await X0((W)=>{return W.logging={...W.logging??{},level:G},W},X.accountStoragePath),G0.info("log level changed",{level:G}),{command:"openai-logging",text:`## Logging Updated
71
72
 
72
- Cannot start: manager not wired.`,knobs:{}};await L$((G)=>{return G.cachekeep={...G.cachekeep??{},enabled:!0},G},U.accountStoragePath),K$.info("cachekeep enabled"),U.setCacheKeepEnabled?.(!0),z.start();let N=z.status(),W=Math.max(0,...N.targets.map((G)=>G.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
73
+ Level set to \`${G}\`.`,knobs:{level:G}}}return{command:"openai-logging",text:`## Invalid Level
73
74
 
74
- TTL: ${Math.round(N.ttlMs/1000)}s | Max idle warm ${Math.round(N.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:J?.cachekeep?.subagents===!0,window:N.window,running:N.running,tracked:N.tracked,lastWarmAt:W||void 0,generatedAt:N.generatedAt,maxIdleWarmMs:N.maxIdleWarmMs,maxSubagentIdleMs:N.maxSubagentIdleMs}}}if(X[0]==="off")return await L$((N)=>{return N.cachekeep={...N.cachekeep??{},enabled:!1},N},U.accountStoragePath),K$.info("cachekeep disabled"),U.setCacheKeepEnabled?.(!1),z?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,running:!1,tracked:0}};if(X[0]==="subagents"){let N=X[1];if(!N||N!=="on"&&N!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let W=N==="on";await L$((Q)=>{return Q.cachekeep={...Q.cachekeep??{},subagents:W},Q},U.accountStoragePath),K$.info(W?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),U.setCacheKeepSubagents?.(W);let G=z?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
75
+ Valid levels: ${Q.map((G)=>`\`${G}\``).join(", ")}`,knobs:{level:"info"}}}function lW(Y){let X=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!X)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let J=Number(X[1]),Q=Number(X[2]);if(!Number.isInteger(J)||!Number.isInteger(Q)||J<0||J>23||Q<0||Q>23||J===Q)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:J,endHour:Q}}async function dW(Y,X){let J=X.cacheKeepManager,Q=Y.trim().toLowerCase().split(/\s+/).filter(Boolean),$=await X.loadAccounts(X.accountStoragePath),G=$?.cachekeep?.enabled===!0;if(Q.length===0||Q[0]==="status"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
75
76
 
76
- Subagent warming: **${W?"ON":"OFF"}**`,knobs:{enabled:j,subagents:W,window:G?.window,running:G?.running??!1,tracked:G?.tracked??0,generatedAt:G?.generatedAt??Date.now(),maxIdleWarmMs:G?.maxIdleWarmMs??3600000,maxSubagentIdleMs:G?.maxSubagentIdleMs??1800000}}}if(X[0]==="window"){let N=X[1];if(N==="clear"||N==="off"){await L$((G)=>{if(G.cachekeep)delete G.cachekeep.startHour,delete G.cachekeep.endHour;return G},U.accountStoragePath),U.setCacheKeepWindow?.(void 0),K$.info("cachekeep window cleared");let W=z?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
77
+ Status: **not available** (manager not wired)`,knobs:{}};let K=J.status(),H=K.window,U=H?`${String(H.startHour).padStart(2,"0")}-${String(H.endHour).padStart(2,"0")}`:"always (no window)",N=["## Cachekeep","",`Status: **${G?"ON":"OFF"}**`,`Timer: **${K.running?"armed":"idle"}**`,`Subagent warming: **${$?.cachekeep?.subagents===!0?"ON":"OFF"}**`,`Idle policy: **sustain ${K.sustain?"ON":"OFF"} (main only)**`,`Window: **${U}**`];if(N.push(`Tracked sessions: **${K.tracked}**`),K.targets.length>0){N.push("");for(let B of K.targets){let L=B.sessionKey.length>12?`${B.sessionKey.slice(0,12)}…`:B.sessionKey,Z=Math.ceil((B.cacheExpiresAt-K.generatedAt)/1000);N.push(`- \`${L}\` (${B.accountId??"main"}) — expires in ${Z}s`+(B.lastWarmedAt?`, last warm ${Math.ceil((K.generatedAt-B.lastWarmedAt)/1000)}s ago`:"")+(B.backoffUntil&&B.backoffUntil>K.generatedAt?`, backoff ${Math.ceil((B.backoffUntil-K.generatedAt)/1000)}s`:""))}}N.push(""),N.push(`TTL: ${Math.round(K.ttlMs/1000)}s | Lead: ${Math.round(K.leadMs/1000)}s | Max idle warm: ${Math.round(K.maxIdleWarmMs/60000)}min`),N.push(""),N.push("Commands: `/openai-cachekeep on` | `/openai-cachekeep off` | `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off` | `/openai-cachekeep HH-HH` | `/openai-cachekeep window clear` | `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off` | `/openai-cachekeep`");let O=Math.max(0,...K.targets.map((B)=>B.lastWarmedAt??0));return{command:"openai-cachekeep",text:N.join(`
78
+ `),knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:H,running:K.running,tracked:K.tracked,lastWarmAt:O||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="on"){if(!J)return{command:"openai-cachekeep",text:`## Cachekeep
77
79
 
78
- Cachekeep will now warm on every tick (within idle caps).`,knobs:{enabled:j,subagents:J?.cachekeep?.subagents===!0,window:void 0,running:W?.running??!1,tracked:W?.tracked??0,generatedAt:W?.generatedAt??Date.now(),maxIdleWarmMs:W?.maxIdleWarmMs??3600000,maxSubagentIdleMs:W?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep window clear`",knobs:{}}}let Y=X[0];if(Y&&/^\d{1,2}-\d{1,2}$/.test(Y)){let N=f2(Y);if(!N.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
80
+ Cannot start: manager not wired.`,knobs:{}};await X0((U)=>{return U.cachekeep={...U.cachekeep??{},enabled:!0},U},X.accountStoragePath),G0.info("cachekeep enabled"),X.setCacheKeepEnabled?.(!0),J.start();let K=J.status(),H=Math.max(0,...K.targets.map((U)=>U.lastWarmedAt??0));return{command:"openai-cachekeep",text:`## Cachekeep Enabled
79
81
 
80
- ${N.reason}`,knobs:{}};let{startHour:W,endHour:G}=N;await L$((H)=>{return H.cachekeep={...H.cachekeep??{},startHour:W,endHour:G},H},U.accountStoragePath),U.setCacheKeepWindow?.({startHour:W,endHour:G}),K$.info("cachekeep window set",{startHour:W,endHour:G});let Q=z?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
82
+ TTL: ${Math.round(K.ttlMs/1000)}s | Max idle warm ${Math.round(K.maxIdleWarmMs/60000)}min`,knobs:{enabled:!0,subagents:$?.cachekeep?.subagents===!0,sustain:K.sustain,window:K.window,running:K.running,tracked:K.tracked,lastWarmAt:H||void 0,generatedAt:K.generatedAt,maxIdleWarmMs:K.maxIdleWarmMs,maxSubagentIdleMs:K.maxSubagentIdleMs}}}if(Q[0]==="off")return await X0((K)=>{return K.cachekeep={...K.cachekeep??{},enabled:!1},K},X.accountStoragePath),G0.info("cachekeep disabled"),X.setCacheKeepEnabled?.(!1),J?.stop(),{command:"openai-cachekeep",text:"## Cachekeep Disabled",knobs:{enabled:!1,sustain:$?.cachekeep?.sustain===!0,running:!1,tracked:0}};if(Q[0]==="sustain"){let K=Q[1];if(Q.length!==2||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep sustain on` | `/openai-cachekeep sustain off`",knobs:{}};let H=K==="on";await X0((N)=>{return N.cachekeep={...N.cachekeep??{},sustain:H},N},X.accountStoragePath),G0.info(`cachekeep sustain ${H?"enabled":"disabled"}`),X.setCacheKeepSustain?.(H);let U=J?.status();return{command:"openai-cachekeep",text:H?`## Cachekeep Sustain Enabled
81
83
 
82
- Warming limited to **${`${String(W).padStart(2,"0")}-${String(G).padStart(2,"0")}`}** local hours.`,knobs:{enabled:j,subagents:J?.cachekeep?.subagents===!0,window:{startHour:W,endHour:G},running:Q?.running??!1,tracked:Q?.tracked??0,generatedAt:Q?.generatedAt??Date.now(),maxIdleWarmMs:Q?.maxIdleWarmMs??3600000,maxSubagentIdleMs:Q?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep`, `/openai-cachekeep on`, `/openai-cachekeep off`, `/openai-cachekeep HH-HH`, `/openai-cachekeep window clear`, `/openai-cachekeep subagents on`, `/openai-cachekeep subagents off`",knobs:{}}}async function m0($,U,z){switch($){case"openai-quota":return k2(z);case"openai-account":return C2(U,z);case"openai-routing":return Z2(U,z);case"openai-killswitch":return T2(U,z);case"openai-dump":return g2(U,z);case"openai-logging":return x2(U,z);case"openai-cachekeep":return h2(U,z);default:throw Error(`unhandled command: ${$}`)}}function k($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function u0($){if(typeof $!=="string")return!1;try{let U=JSON.parse($);return k(U)&&k(U.client_metadata)&&U.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function i0($){if(typeof $!=="string")return $;try{let U=JSON.parse($);if(!k(U)||!k(U.client_metadata))return $;if(!(("x-codex-turn-metadata"in U.client_metadata)||("x-codex-ws-stream-request-start-ms"in U.client_metadata)||("ws_request_header_x_openai_internal_codex_responses_lite"in U.client_metadata)))return $;let z={...U.client_metadata};return delete z["x-codex-turn-metadata"],delete z["x-codex-ws-stream-request-start-ms"],delete z.ws_request_header_x_openai_internal_codex_responses_lite,JSON.stringify({...U,client_metadata:z})}catch{return $}}function e1($){if($?.method?.toUpperCase()!=="POST")return $;let U=new Headers($.headers);if(U.set("accept","text/event-stream"),U.set("content-type","application/json"),u0($.body))U.set("x-openai-internal-codex-responses-lite","true");return{...$,headers:U,body:i0($.body)}}function hN($){if(!$.enabled||typeof $.body!=="string")return;let U=$.headers.has("x-parent-session-id");if(U&&!$.includeSubagents)return;let z=$.headers.get("session-id")??$.headers.get("x-opencode-session")??$.headers.get("x-session-affinity")??void 0;if(!z)return;let X={};for(let J of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let j=$.headers.get(J);if(j)X[J]=j}return{sessionKey:z,bodyText:$.body,replayHeaders:X,isSubagent:U}}function yN($){let U=Number($?.cachekeep?.startHour),z=Number($?.cachekeep?.endHour);if(!Number.isInteger(U)||!Number.isInteger(z)||U<0||U>23||z<0||z>23||U===z)return;return{startHour:U,endHour:z}}function TN($,U=new Date){if(!$)return!1;let z=U.getHours();if($.startHour<$.endHour)return z>=$.startHour&&z<$.endHour;return z>=$.startHour||z<$.endHour}var y2=300000,cN=1800000,gN=2*cN+900000,c2=3600000,xN=1800000,fN=60000,m2=32,u2=8388608,l0=600000;function mN($){try{let z=JSON.parse($).model;if(typeof z!=="string")return!1;return z==="gpt-5.6"||z.startsWith("gpt-5.6-")}catch{return!1}}function i2($){let z=JSON.parse($);return z.store=!1,delete z.max_output_tokens,delete z.max_tokens,delete z.max_completion_tokens,JSON.stringify(z)}function l2($,U){return mN($)?cN:U}function n0(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function uN($){if(!$||typeof $!=="object")return n0();let U=$,z=Number(U.input_tokens)||Number(U.prompt_tokens)||0,X=Number(U.output_tokens)||Number(U.completion_tokens)||0,J=U.input_tokens_details??U.prompt_tokens_details,j=Number(J?.cached_tokens)||Number(U.cached_tokens)||0,Y=z>0?j/z:null;return{input_tokens:z,output_tokens:X,cached_tokens:j,hit_rate:Y}}function n2($){try{let U=JSON.parse($);return uN(U.usage)}catch{return n0()}}function r2($){let U,z=[],X,J=()=>{if(!z.length)return;let j=z.join(`
83
- `).trim();z=[];let Y=U;if(U=void 0,!j||j==="[DONE]")return;try{let N=JSON.parse(j),W=N.type??Y;if(W!=="response.completed"&&W!=="response.done")return;let G=N.response;X=uN(G?.usage??N.usage)}catch{}};for(let j of $.split(/\r?\n/)){if(j===""){J();continue}if(j.startsWith("event:")){U=j.slice(6).trim();continue}if(j.startsWith("data:"))z.push(j.slice(5).trim())}return J(),X??n0()}class r0{targets=new Map;fetchImpl;getMainToken;refreshFallback;codexResponsesUrl;log;now;ttlMs;leadMs;maxIdleWarmMs;maxSubagentIdleMs;tickIntervalMs;maxTargets;maxBytes;getWindow;timer=null;startedAt=null;totalBytes=0;tickInFlight=!1;disposed=!1;abortController=new AbortController;logPayload($={}){return{pid:process.pid,...$}}constructor($){this.fetchImpl=$.fetchImpl,this.getMainToken=$.getMainToken,this.refreshFallback=$.refreshFallback,this.codexResponsesUrl=$.codexResponsesUrl,this.log=$.logger,this.now=$.now,this.ttlMs=$.ttlMs??y2,this.tickIntervalMs=$.tickIntervalMs??fN,this.leadMs=$.leadMs??this.tickIntervalMs+15000;let U=$.maxIdleWarmMs??$.maxDurationMs;this.maxIdleWarmMs=typeof U==="number"&&Number.isFinite(U)&&U>0?U:c2;let z=$.maxSubagentIdleMs??xN;this.maxSubagentIdleMs=typeof z==="number"&&Number.isFinite(z)&&z>0?z:xN,this.tickIntervalMs=$.tickIntervalMs??fN,this.maxTargets=$.maxTargets??m2,this.maxBytes=$.maxBytes??u2,this.getWindow=$.getWindow}track($,U,z,X,J={},j=!1){this.pruneStale();let Y=U.length;if(Y>this.maxBytes){this.log.debug("cachekeep track skipped (body exceeds maxBytes)",this.logPayload({sessionKey:$,bodyBytes:Y,maxBytes:this.maxBytes}));return}let N=this.getWindow?.();if(N&&!TN(N,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:$,startHour:N.startHour,endHour:N.endHour}));return}if(this.targets.has($)){let Q=this.targets.get($);if(Q)this.totalBytes-=Q.bodyText.length;this.targets.delete($)}else this.log.debug("cachekeep captured target",this.logPayload({sessionKey:$,accountId:z}));while(this.targets.size>=this.maxTargets||this.totalBytes+Y>this.maxBytes&&this.targets.size>0){let Q,L=Number.POSITIVE_INFINITY;for(let[w,B]of this.targets){let q=Math.max(B.lastRealRequestAt,B.lastWarmedAt??0);if(q<L)Q=w,L=q}if(Q===void 0)break;let H=this.targets.get(Q);if(H)this.totalBytes-=H.bodyText.length;this.targets.delete(Q)}let W=l2(U,this.ttlMs),G={bodyText:U,accountId:z||void 0,chatgptAccountId:X,route:"main",ttlMs:W,cacheExpiresAt:this.now()+W,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:J,isSubagent:j,is56:mN(U)};this.targets.set($,G),this.totalBytes+=Y,this.start()}isGpt56Subagent($){return $.isSubagent===!0&&$.is56}pruneStale(){let $=this.now(),U=$-this.maxIdleWarmMs,z=$-this.maxSubagentIdleMs,X=$-gN;for(let[J,j]of this.targets){let Y,N;if(this.isGpt56Subagent(j))Y=X,N=gN;else Y=j.isSubagent?z:U,N=j.isSubagent?this.maxSubagentIdleMs:this.maxIdleWarmMs;if(j.lastRealRequestAt<Y)this.log.debug("cachekeep pruned idle target",this.logPayload({sessionKey:J,accountId:j.accountId??"main",lastRealRequestAt:j.lastRealRequestAt,maxIdleWarmMs:N})),this.totalBytes-=j.bodyText.length,this.targets.delete(J)}}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.log.debug("cachekeep started",this.logPayload({ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})),this.timer=setInterval(()=>{this.tick().catch(()=>{})},this.tickIntervalMs),"unref"in this.timer)this.timer.unref()}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)clearInterval(this.timer),this.timer=null;this.startedAt=null,this.targets.clear(),this.totalBytes=0,this.log.debug("cachekeep stopped",this.logPayload())}remove($){let U=this.targets.get($);if(U)this.totalBytes-=U.bodyText.length,this.targets.delete($),this.log.debug("cachekeep removed target",this.logPayload({sessionKey:$}))}status(){let $=this.now(),U=Array.from(this.targets.entries()).map(([z,X])=>({sessionKey:z,accountId:X.accountId,route:X.route,cacheExpiresAt:X.cacheExpiresAt,lastRealRequestAt:X.lastRealRequestAt,lastWarmedAt:X.lastWarmedAt,backoffUntil:X.backoffUntil,bodyBytes:X.bodyText.length}));return{running:this.timer!=null,tracked:this.targets.size,generatedAt:$,startedAt:this.startedAt,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,ttlMs:this.ttlMs,leadMs:this.leadMs,window:this.getWindow?.(),targets:U}}async tick(){if(this.tickInFlight)return;this.tickInFlight=!0;try{this.pruneStale();let $=this.getWindow?.();if($&&!TN($,new Date(this.now())))return;let U=this.now(),z=U+this.leadMs;for(let[X,J]of this.targets)if(J.backoffUntil&&U>=J.backoffUntil&&J.cacheExpiresAt<=z)await this.prewarm(X,J);for(let[X,J]of this.targets){if(J.backoffUntil&&U<J.backoffUntil)continue;if(J.cacheExpiresAt<=z)await this.prewarm(X,J)}}finally{this.tickInFlight=!1}}async prewarm($,U){let z;try{if(U.accountId&&U.accountId!=="main")z=await this.refreshFallback(U.accountId);else z=await this.getMainToken()}catch(J){if(!this.disposed&&this.targets.get($)===U)U.backoffUntil=this.now()+l0;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:$,accountId:U.accountId??"main",error:J instanceof Error?J.message:String(J)}));return}if(this.disposed||this.targets.get($)!==U)return;let X={...U.replayHeaders,authorization:`Bearer ${z}`,"content-type":"application/json"};if(U.chatgptAccountId)X["ChatGPT-Account-Id"]=U.chatgptAccountId;else delete X["ChatGPT-Account-Id"];try{let J=i2(U.bodyText),j;try{let q=JSON.parse(J);j={warmBodyKeys:Object.keys(q),stream:q.stream,max_output_tokens:q.max_output_tokens,store:q.store,has_stream_options:"stream_options"in q,has_max_tokens:"max_tokens"in q,model:q.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...j,headerKeys:Object.keys(X),hasChatGptAccountId:"ChatGPT-Account-Id"in X}));let Y=e1({method:"POST",headers:X,body:J,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),N=await this.fetchImpl(this.codexResponsesUrl,Y),W="";try{W=await N.text()}catch{}if(this.disposed||this.targets.get($)!==U)return;if(!N.ok){U.backoffUntil=this.now()+l0,this.log.warn("cachekeep failed",this.logPayload({session:$,accountId:U.accountId??"main",status:N.status,error:`HTTP ${N.status}`,responseBody:W.slice(0,600)}));return}let G=N.headers.get("content-type")??"",Q=G.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(W.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:N.status,contentType:G,bodyLen:W.length,isSse:Q}));let L=Q?r2(W):n2(W),H=C4(N.headers),w=H.primary?.usedPercent??null,B=H.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:$,accountId:U.accountId??"main",input_tokens:L.input_tokens,cached_tokens:L.cached_tokens,hit_rate:L.hit_rate,output_tokens:L.output_tokens,quota_primary_pct:w,quota_secondary_pct:B})),U.cacheExpiresAt=this.now()+U.ttlMs,U.lastWarmedAt=this.now(),U.backoffUntil=void 0,U.warmCount+=1,this.isGpt56Subagent(U)&&U.warmCount>=2){if(this.targets.get($)===U)this.totalBytes-=U.bodyText.length,this.targets.delete($);return}}catch(J){if(this.disposed||this.targets.get($)!==U)return;U.backoffUntil=this.now()+l0,this.log.warn("cachekeep failed",this.logPayload({session:$,accountId:U.accountId??"main",error:J instanceof Error?J.message:String(J)}))}}}var p2=q$("quota");async function p0($){let U=$.whamFn;if(!U)throw Error("whamFn is required for refreshAllQuota");let z=[],X=$.logger??p2,J=(N)=>{z.push(N);let W={pid:process.pid,accountId:N.account,status:N.ok?"ok":"error",...N.error?{error:N.error}:{}};if(N.ok)X.debug("quota refresh succeeded",W);else X.warn("quota refresh failed",W)};try{let N=await $.getAuth();if(N.type==="oauth"){if(!N.access||(N.expires??0)<$.now()){let W=await $.codexRefreshFn({refreshToken:N.refresh??"",fetchImpl:$.fetchImpl,now:$.now});await $.client.auth.set({path:{id:"openai"},body:{type:"oauth",access:W.access,refresh:W.refresh,expires:W.expires}}),N={...N,access:W.access,expires:W.expires}}if(N.access)if($.respectBackoff&&$.quotaManager.isBackedOff())J({account:"main",ok:!0});else{let W=await U({accessToken:N.access,fetchImpl:$.fetchImpl,now:$.now,accountId:$.storageMainAccountId,accountKey:"main"});$.quotaManager.setMain(N.access,{quota:W,refreshAfter:$.now()+300000,checkedAt:$.now()},void 0,!0),J({account:"main",ok:!0})}else J({account:"main",ok:!1,error:"no access token"})}else J({account:"main",ok:!1,error:"auth type is not oauth"})}catch(N){J({account:"main",ok:!1,error:A6(N)})}let j=await $.loadAccounts($.configPath);if(j)for(let N of j.accounts){if(N.enabled===!1||!$.isOAuthAccountFn(N))continue;try{if($.respectBackoff&&$.quotaManager.isFallbackBackedOff(N.id,N.access)){J({account:N.id,ok:!0});continue}let W;try{W=await $.fallbackManager.refreshAccount(N,j)}catch{W=N}if(!W.access){J({account:N.id,ok:!1,error:"no access token"});continue}let G=await U({accessToken:W.access,fetchImpl:$.fetchImpl,now:$.now,accountId:W.accountId,accountKey:N.id});$.quotaManager.setFallback(N.id,{quota:G,refreshAfter:$.now()+300000,checkedAt:$.now()},W.access,!0),J({account:N.id,ok:!0})}catch(W){J({account:N.id,ok:!1,error:A6(W)})}}let Y=await $.loadAccounts($.configPath);return await $.writeSidebarState($.quotaManager,Y),z}import{createHash as d2}from"node:crypto";import{chmod as o2,mkdir as t2,writeFile as d0}from"node:fs/promises";import{join as a2}from"node:path";var a0=q$("dump"),E6="x-cortexkit-openai-auth-dump-session",iN=0,j4=new Map,s2=100;function o0($){return $.length<=16?$:`${$.slice(0,12)}…`}function e2($){let U=$.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!U)return"session-unknown";return U.length<=80?U:U.slice(0,80)}function nN($){return d2("sha256").update($).digest("hex")}function t0($){return nN(JSON.stringify($))}function rN($){try{let U=JSON.parse($);return U!=null&&typeof U==="object"&&!Array.isArray(U)?U:void 0}catch{return}}function $G($,U){if($===void 0)return null;if($===U)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:$.length,currentBytes:U.length};let z=0;while(z<$.length&&z<U.length&&$[z]===U[z])z++;let X=$.length-1,J=U.length-1;while(X>=z&&J>=z&&$[X]===U[J])X--,J--;return{changed:!0,firstByte:z,lastPreviousByte:X,lastCurrentByte:J,changedPreviousBytes:X-z+1,changedCurrentBytes:J-z+1,previousBytes:$.length,currentBytes:U.length}}function UG($,U){if(!j4.has($))while(j4.size>=s2){let z=j4.keys().next().value;if(z===void 0)break;j4.delete(z)}j4.set($,U)}function JG($){if($===void 0)return;return Object.fromEntries(new Headers($).entries())}function s0($){if(Array.isArray($))return $.map(s0);if($==null||typeof $!=="object")return $;let U={};for(let[z,X]of Object.entries($)){let J=z.toLowerCase();if(J==="authorization"||J==="chatgpt-account-id"||J==="cookie"||J==="set-cookie"){U[z]="[redacted]";continue}U[z]=s0(X)}return U}function zG($){let U=rN($);if(U===void 0)return $;let z=lN(U),X=JSON.stringify(z);if(X===void 0)return $;return JSON.stringify(U)===X?$:X}function XG($){return $!=null&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type:"unknown"}function jG($){let U=rN($);if(!U)return{parseable:!1};let z=Array.isArray(U.input)?U.input:[],X=Array.isArray(U.tools)?U.tools:[],J=X.map(XG),j=U.client_metadata!=null&&typeof U.client_metadata==="object"&&!Array.isArray(U.client_metadata)?U.client_metadata:void 0;return{parseable:!0,model:typeof U.model==="string"?U.model:void 0,stream:U.stream,generate:U.generate,store:U.store,previousResponseID:typeof U.previous_response_id==="string"?U.previous_response_id:void 0,promptCacheKey:typeof U.prompt_cache_key==="string"?U.prompt_cache_key:void 0,reasoning:U.reasoning,inputCount:z.length,inputHash:t0(z),inputBytes:JSON.stringify(z).length,firstInputHash:z[0]===void 0?null:t0(z[0]),toolsCount:X.length,toolTypes:J,toolsHash:t0(X),hasWebSearch:J.includes("web_search"),clientMetadataKeys:j?Object.keys(j).sort():[]}}async function Y4($){let U=g$();if(!U.dump)return;iN++;let z=$.sessionID?.trim()||"session-unknown",X=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(iN).padStart(5,"0")}-${e2(z)}-${$.transport}-${$.phase}`,J=a2(U.dumpDir,X),j={body:`${J}.body.json`,metadata:`${J}.meta.json`,request:`${J}.request.json`},Y=`${$.transport}:${z}`,N=j4.get(Y);try{await t2(U.dumpDir,{recursive:!0,mode:448}),await o2(U.dumpDir,448).catch(()=>{});let W=zG($.bodyText),G={id:X,createdAt:new Date().toISOString(),session:o0(z),transport:$.transport,phase:$.phase,status:$.status,error:$.error,bodyBytes:$.bodyText.length,bodyHash:nN($.bodyText),diff:$G(N,$.bodyText),body:jG($.bodyText),files:j};await Promise.all([d0(j.body,W,{encoding:"utf8",mode:384}),d0(j.metadata,`${JSON.stringify(G,null,2)}
84
- `,{encoding:"utf8",mode:384}),d0(j.request,`${JSON.stringify(s0({url:$.url,method:$.method,headers:JG($.headers)}),null,2)}
85
- `,{encoding:"utf8",mode:384})]),a0.debug("dumped request",{id:X,session:o0(z),body:j.body,meta:j.metadata}),UG(Y,$.bodyText)}catch(W){a0.warn("request dump failed",{session:o0(z),error:W instanceof Error?W.message:String(W)})}}async function G6($){if(!g$().dump)return;a0.debug("diagnostic",$)}import{tool as Z4}from"@opencode-ai/plugin";var $U="ws_",oN=new Map,tN=Z4({description:"Provider-executed OpenAI web search. This tool is handled server-side by OpenAI; the local plugin records the hosted action for deterministic replay.",args:{type:Z4.schema.string().optional(),query:Z4.schema.string().optional(),queries:Z4.schema.array(Z4.schema.string()).optional()},async execute($){return{title:"OpenAI Web Search",output:JSON.stringify({action:$}),metadata:{action:$}}}});function $J($){if(YG($))return;if(!OG($))return $;let U=$.item;return oN.set(U.id,U),{...$,item:{type:"function_call",id:U.id,call_id:U.id,name:"web_search",arguments:JSON.stringify(k(U.action)?U.action:{})}}}function aN($){if(!$.body)return $;if(!($.headers.get("content-type")??"").includes("text/event-stream"))return $;return new Response(NG($.body),{status:$.status,statusText:$.statusText,headers:$.headers})}function sN($){if(!Array.isArray($.input))return!1;let U=!1,z=new Map,X=[],J=new Map,j=new Map;for(let Y of $.input)if(k(Y)&&typeof Y.call_id==="string"&&Y.call_id.startsWith($U)){if(Y.type==="function_call")J.set(Y.call_id,Y);else if(Y.type==="function_call_output"&&typeof Y.output==="string")j.set(Y.call_id,Y.output)}for(let Y of $.input){if(WG(Y)){z.set(Y.call_id,Y),U=!0;continue}if(GG(Y,z)){X.push(e0(Y.call_id,Y.output,z.get(Y.call_id))),U=!0;continue}if(QG(Y)){let N=oN.get(Y.id);if(N)X.push(e0(Y.id,N));else{let W=J.get(Y.id),G=j.get(Y.id);if(W||G)X.push(e0(Y.id,G,W));else X.push(Y)}U=!0;continue}X.push(Y)}if(U)$.input=X;return U}function YG($){if(typeof $.type==="string"&&$.type.startsWith("response.web_search_call."))return!0;return $.type==="response.output_item.added"&&k($.item)&&$.item.type==="web_search_call"}function NG($){let U=new TextDecoder,z=new TextEncoder,X="";return $.pipeThrough(new TransformStream({transform(J,j){X+=U.decode(J,{stream:!0});let Y=pN(X);while(Y){let N=X.slice(0,Y.index);X=X.slice(Y.index+Y.length);let W=dN(N);if(W)j.enqueue(z.encode(W));Y=pN(X)}},flush(J){if(X+=U.decode(),!X)return;let j=dN(X);if(j)J.enqueue(z.encode(j))}}))}function pN($){let U=$.indexOf(`
84
+ Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.
86
85
 
87
- `),z=$.indexOf(`\r
86
+ Before enabling sustain with Magic Context, set a non-expiring \`cache_ttl\` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.`:`## Cachekeep Sustain Disabled
87
+
88
+ Main-agent sessions again stop warming at the configured idle cap.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:H,window:U?.window,running:U?.running??!1,tracked:U?.tracked??0,generatedAt:U?.generatedAt??Date.now(),maxIdleWarmMs:U?.maxIdleWarmMs??3600000,maxSubagentIdleMs:U?.maxSubagentIdleMs??1800000}}}if(Q[0]==="subagents"){let K=Q[1];if(!K||K!=="on"&&K!=="off")return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep subagents on` | `/openai-cachekeep subagents off`",knobs:{}};let H=K==="on";await X0((N)=>{return N.cachekeep={...N.cachekeep??{},subagents:H},N},X.accountStoragePath),G0.info(H?"cachekeep subagent warming enabled":"cachekeep subagent warming disabled"),X.setCacheKeepSubagents?.(H);let U=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Subagent Warming
89
+
90
+ Subagent warming: **${H?"ON":"OFF"}**`,knobs:{enabled:G,subagents:H,sustain:U?.sustain??$?.cachekeep?.sustain===!0,window:U?.window,running:U?.running??!1,tracked:U?.tracked??0,generatedAt:U?.generatedAt??Date.now(),maxIdleWarmMs:U?.maxIdleWarmMs??3600000,maxSubagentIdleMs:U?.maxSubagentIdleMs??1800000}}}if(Q[0]==="window"){let K=Q[1];if(K==="clear"||K==="off"){await X0((U)=>{if(U.cachekeep)delete U.cachekeep.startHour,delete U.cachekeep.endHour;return U},X.accountStoragePath),X.setCacheKeepWindow?.(void 0),G0.info("cachekeep window cleared");let H=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Cleared
91
+
92
+ Cachekeep will now warm on every tick (within idle caps).`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:H?.sustain??$?.cachekeep?.sustain===!0,window:void 0,running:H?.running??!1,tracked:H?.tracked??0,generatedAt:H?.generatedAt??Date.now(),maxIdleWarmMs:H?.maxIdleWarmMs??3600000,maxSubagentIdleMs:H?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep window clear`",knobs:{}}}let W=Q[0];if(W&&/^\d{1,2}-\d{1,2}$/.test(W)){let K=lW(W);if(!K.ok)return{command:"openai-cachekeep",text:`## Cachekeep Window Invalid
93
+
94
+ ${K.reason}`,knobs:{}};let{startHour:H,endHour:U}=K;await X0((B)=>{return B.cachekeep={...B.cachekeep??{},startHour:H,endHour:U},B},X.accountStoragePath),X.setCacheKeepWindow?.({startHour:H,endHour:U}),G0.info("cachekeep window set",{startHour:H,endHour:U});let N=J?.status();return{command:"openai-cachekeep",text:`## Cachekeep Window Set
95
+
96
+ Warming limited to **${`${String(H).padStart(2,"0")}-${String(U).padStart(2,"0")}`}** local hours.`,knobs:{enabled:G,subagents:$?.cachekeep?.subagents===!0,sustain:N?.sustain??$?.cachekeep?.sustain===!0,window:{startHour:H,endHour:U},running:N?.running??!1,tracked:N?.tracked??0,generatedAt:N?.generatedAt??Date.now(),maxIdleWarmMs:N?.maxIdleWarmMs??3600000,maxSubagentIdleMs:N?.maxSubagentIdleMs??1800000}}}return{command:"openai-cachekeep",text:"Usage: `/openai-cachekeep`, `/openai-cachekeep on`, `/openai-cachekeep off`, `/openai-cachekeep sustain on`, `/openai-cachekeep sustain off`, `/openai-cachekeep HH-HH`, `/openai-cachekeep window clear`, `/openai-cachekeep subagents on`, `/openai-cachekeep subagents off`",knobs:{}}}async function B8(Y,X,J){switch(Y){case"openai-quota":return yW(J);case"openai-account":return fW(X,J);case"openai-routing":return mW(X,J);case"openai-killswitch":return cW(X,J);case"openai-dump":return uW(X,J);case"openai-logging":return pW(X,J);case"openai-cachekeep":return dW(X,J);default:throw Error(`unhandled command: ${Y}`)}}var iW=L0("quota");async function y1(Y,X={}){let J=Y.whamFn;if(!J)throw Error("whamFn is required for refreshAllQuota");let Q=[],$=Y.logger??iW,G=(L)=>{Q.push(L);let Z={pid:process.pid,accountId:L.account,status:L.ok?"ok":"error",...L.error?{error:L.error}:{}};if(L.ok)$.debug("quota refresh succeeded",Z);else $.warn("quota refresh failed",Z)},W=Y.skipFresherThanMs,K=!1,H;if(W!==void 0)try{H=await(Y.readSidebarState??L1)()}catch{}let U=new Map(H?.fallbacks.map((L)=>[L.id,L])??[]),N=(...L)=>W!==void 0&&L.some((Z)=>typeof Z==="number"&&Number.isFinite(Z)&&Z<=Y.now()&&Y.now()-Z<W),O=await Y.loadAccounts(Y.configPath).catch(()=>{return}),B=O?.mainAccountId??Y.storageMainAccountId;if(!X.accountKey||X.accountKey==="main")try{let L=await Y.getAuth();if(L.type==="oauth"){let Z=H&&B!==void 0&&H.main.mainAccountId===B?H.main.quota:void 0;if(N(Y.quotaManager.peekMainForPolicy(B)?.checkedAt,Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt))G({account:"main",ok:!0});else{if(!L.access||(L.expires??0)<Y.now()){let w=await Y.refreshMainWithLease();L={...L,access:w.access,expires:w.expires}}if(L.access)if(Y.respectBackoff&&Y.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let w=await J({accessToken:L.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:B,accountKey:"main"});Y.quotaManager.setMain(L.access,{quota:w,refreshAfter:Y.now()+300000,checkedAt:Y.now()},B,!0),K=!0,G({account:"main",ok:!0})}else G({account:"main",ok:!1,error:"no access token"})}}else G({account:"main",ok:!1,error:"auth type is not oauth"})}catch(L){G({account:"main",ok:!1,error:o0(L)})}if(O)for(let L of O.accounts){if(X.accountKey&&(X.accountKey==="main"||L.id!==X.accountKey))continue;if(L.enabled===!1||!Y.isOAuthAccountFn(L)){if(X.accountKey)G({account:L.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let Z=U.get(L.id),j=L.accountId,w=Z&&j!==void 0&&Z.accountId===j?Z.quota:void 0;if(N(Y.quotaManager.peekFallbackForPolicy(L.id,j)?.checkedAt,w?.primary?.checkedAt,w?.secondary?.checkedAt,w?.checkedAt)){G({account:L.id,ok:!0});continue}if(Y.respectBackoff&&Y.quotaManager.isFallbackBackedOff(L.id,L.access)){G({account:L.id,ok:!0});continue}let P;try{P=await Y.fallbackManager.refreshAccount(L,O)}catch{P=L}if(!P.access){G({account:L.id,ok:!1,error:"no access token"});continue}let k=await J({accessToken:P.access,fetchImpl:Y.fetchImpl,now:Y.now,accountId:P.accountId,accountKey:L.id});Y.quotaManager.setFallback(L.id,{quota:k,refreshAfter:Y.now()+300000,checkedAt:Y.now()},P.access,!0,P.accountId),K=!0,G({account:L.id,ok:!0})}catch(Z){G({account:L.id,ok:!1,error:o0(Z)})}}if(X.accountKey&&X.accountKey!=="main"&&!Q.some((L)=>L.account===X.accountKey))Q.push({account:X.accountKey,ok:!1,error:"account not found"});if(W===void 0||K){let L=await Y.loadAccounts(Y.configPath);await Y.writeSidebarState(Y.quotaManager,L)}return Q}var nW=300000,oW=30000,rW=240000,sW="bg-quota-refresh",aW=120000;function tW(Y,X){return PY({name:sW,ttlMs:aW,path:Y,renew:!0,...X})}function KX(Y,X=y1,J=()=>tW(Y.configPath)){return eW(Y,X,J)}async function eW(Y,X,J){let Q;try{Q=await J()}catch{Q=void 0}if(Q===null)return[];try{return await X({...Y,respectBackoff:!0,skipFresherThanMs:rW})}finally{await Q?.release().catch(()=>{})}}class Z8{setIntervalFn;clearIntervalFn;random;onError;run;timer;tickPromise;stopped=!1;constructor(Y={}){this.setIntervalFn=Y.setIntervalFn??setInterval,this.clearIntervalFn=Y.clearIntervalFn??clearInterval,this.random=Y.random??Math.random,this.onError=Y.onError}start(Y,X=this.onError){if(this.run=Y,this.onError=X,this.stopped=!1,this.timer)return;let J=Math.round((this.random()*2-1)*oW);if(this.timer=this.setIntervalFn(()=>{let Q=this.run;if(this.stopped||!Q||this.tickPromise)return;let $=Q().catch((G)=>{try{this.onError?.(G)}catch{}}).finally(()=>{if(this.tickPromise===$)this.tickPromise=void 0});this.tickPromise=$},nW+J),"unref"in this.timer)this.timer.unref()}stop(){if(this.stopped=!0,this.run=void 0,!this.timer)return;this.clearIntervalFn(this.timer),this.timer=void 0}isStopped(){return this.stopped}}function _(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}function O8(Y){if(typeof Y!=="string")return!1;try{let X=JSON.parse(Y);return _(X)&&_(X.client_metadata)&&X.client_metadata.ws_request_header_x_openai_internal_codex_responses_lite==="true"}catch{return!1}}function F8(Y){if(typeof Y!=="string")return Y;try{let X=JSON.parse(Y);if(!_(X)||!_(X.client_metadata))return Y;if(!(("x-codex-turn-metadata"in X.client_metadata)||("x-codex-ws-stream-request-start-ms"in X.client_metadata)||("ws_request_header_x_openai_internal_codex_responses_lite"in X.client_metadata)))return Y;let J={...X.client_metadata};return delete J["x-codex-turn-metadata"],delete J["x-codex-ws-stream-request-start-ms"],delete J.ws_request_header_x_openai_internal_codex_responses_lite,JSON.stringify({...X,client_metadata:J})}catch{return Y}}function wY(Y){if(Y?.method?.toUpperCase()!=="POST")return Y;let X=new Headers(Y.headers);if(X.set("accept","text/event-stream"),X.set("content-type","application/json"),O8(Y.body))X.set("x-openai-internal-codex-responses-lite","true");return{...Y,headers:X,body:F8(Y.body)}}function VX(Y){if(!Y.enabled||typeof Y.body!=="string")return;let X=Y.headers.has("x-parent-session-id");if(X&&!Y.includeSubagents)return;let J=Y.headers.get("session-id")??Y.headers.get("x-opencode-session")??Y.headers.get("x-session-affinity")??void 0;if(!J)return;let Q={};for(let $ of["session-id","x-session-affinity","x-parent-session-id","user-agent","version","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-client-request-id","thread-id","x-openai-internal-codex-responses-lite"]){let G=Y.headers.get($);if(G)Q[$]=G}return{sessionKey:J,bodyText:Y.body,replayHeaders:Q,isSubagent:X}}function BX(Y){let X=Number(Y?.cachekeep?.startHour),J=Number(Y?.cachekeep?.endHour);if(!Number.isInteger(X)||!Number.isInteger(J)||X<0||X>23||J<0||J>23||X===J)return;return{startHour:X,endHour:J}}function UX(Y,X=new Date){if(!Y)return!1;let J=X.getHours();if(Y.startHour<Y.endHour)return J>=Y.startHour&&J<Y.endHour;return J>=Y.startHour||J<Y.endHour}var Y5=300000,ZX=1800000,HX=2*ZX+900000,X5=3600000,LX=1800000,NX=60000,J5=32,Q5=8388608,q8=600000;function OX(Y){try{let J=JSON.parse(Y).model;if(typeof J!=="string")return!1;return J==="gpt-5.6"||J.startsWith("gpt-5.6-")}catch{return!1}}function $5(Y){let J=JSON.parse(Y);return J.store=!1,delete J.max_output_tokens,delete J.max_tokens,delete J.max_completion_tokens,JSON.stringify(J)}function G5(Y,X){return OX(Y)?ZX:X}function j8(){return{input_tokens:0,output_tokens:0,cached_tokens:0,hit_rate:null}}function FX(Y){if(!Y||typeof Y!=="object")return j8();let X=Y,J=Number(X.input_tokens)||Number(X.prompt_tokens)||0,Q=Number(X.output_tokens)||Number(X.completion_tokens)||0,$=X.input_tokens_details??X.prompt_tokens_details,G=Number($?.cached_tokens)||Number(X.cached_tokens)||0,W=J>0?G/J:null;return{input_tokens:J,output_tokens:Q,cached_tokens:G,hit_rate:W}}function W5(Y){try{let X=JSON.parse(Y);return FX(X.usage)}catch{return j8()}}function z5(Y){let X,J=[],Q,$=()=>{if(!J.length)return;let G=J.join(`
97
+ `).trim();J=[];let W=X;if(X=void 0,!G||G==="[DONE]")return;try{let K=JSON.parse(G),H=K.type??W;if(H!=="response.completed"&&H!=="response.done")return;let U=K.response;Q=FX(U?.usage??K.usage)}catch{}};for(let G of Y.split(/\r?\n/)){if(G===""){$();continue}if(G.startsWith("event:")){X=G.slice(6).trim();continue}if(G.startsWith("data:"))J.push(G.slice(5).trim())}return $(),Q??j8()}class D8{targets=new Map;fetchImpl;getMainToken;refreshFallback;codexResponsesUrl;log;now;ttlMs;leadMs;maxIdleWarmMs;maxSubagentIdleMs;tickIntervalMs;maxTargets;maxBytes;getWindow;getSustain;timer=null;startedAt=null;totalBytes=0;tickInFlight=!1;disposed=!1;abortController=new AbortController;logPayload(Y={}){return{pid:process.pid,...Y}}constructor(Y){this.fetchImpl=Y.fetchImpl,this.getMainToken=Y.getMainToken,this.refreshFallback=Y.refreshFallback,this.codexResponsesUrl=Y.codexResponsesUrl,this.log=Y.logger,this.now=Y.now,this.ttlMs=Y.ttlMs??Y5,this.tickIntervalMs=Y.tickIntervalMs??NX,this.leadMs=Y.leadMs??this.tickIntervalMs+15000;let X=Y.maxIdleWarmMs??Y.maxDurationMs;this.maxIdleWarmMs=typeof X==="number"&&Number.isFinite(X)&&X>0?X:X5;let J=Y.maxSubagentIdleMs??LX;this.maxSubagentIdleMs=typeof J==="number"&&Number.isFinite(J)&&J>0?J:LX,this.tickIntervalMs=Y.tickIntervalMs??NX,this.maxTargets=Y.maxTargets??J5,this.maxBytes=Y.maxBytes??Q5,this.getWindow=Y.getWindow,this.getSustain=Y.getSustain}track(Y,X,J,Q,$={},G=!1){this.pruneStale();let W=X.length;if(W>this.maxBytes){this.log.debug("cachekeep track skipped (body exceeds maxBytes)",this.logPayload({sessionKey:Y,bodyBytes:W,maxBytes:this.maxBytes}));return}let K=this.getWindow?.();if(K&&!UX(K,new Date(this.now()))){this.log.debug("cachekeep track skipped (outside window)",this.logPayload({sessionKey:Y,startHour:K.startHour,endHour:K.endHour}));return}if(this.targets.has(Y)){let N=this.targets.get(Y);if(N)this.totalBytes-=N.bodyText.length;this.targets.delete(Y)}else this.log.debug("cachekeep captured target",this.logPayload({sessionKey:Y,accountId:J}));while(this.targets.size>=this.maxTargets||this.totalBytes+W>this.maxBytes&&this.targets.size>0){let N,O=Number.POSITIVE_INFINITY;for(let[L,Z]of this.targets){let j=Math.max(Z.lastRealRequestAt,Z.lastWarmedAt??0);if(j<O)N=L,O=j}if(N===void 0)break;let B=this.targets.get(N);if(B)this.totalBytes-=B.bodyText.length;this.targets.delete(N)}let H=G5(X,this.ttlMs),U={bodyText:X,accountId:J||void 0,chatgptAccountId:Q,route:"main",ttlMs:H,cacheExpiresAt:this.now()+H,warmCount:0,lastRealRequestAt:this.now(),replayHeaders:$,isSubagent:G,is56:OX(X)};this.targets.set(Y,U),this.totalBytes+=W,this.start()}isGpt56Subagent(Y){return Y.isSubagent===!0&&Y.is56}pruneStale(){let Y=this.now(),X=Y-this.maxIdleWarmMs,J=Y-this.maxSubagentIdleMs,Q=Y-HX;for(let[$,G]of this.targets){let W,K;if(this.isGpt56Subagent(G))W=Q,K=HX;else W=G.isSubagent?J:X,K=G.isSubagent?this.maxSubagentIdleMs:this.maxIdleWarmMs;if(!(G.isSubagent!==!0&&this.getSustain?.()===!0)&&G.lastRealRequestAt<W)this.log.debug("cachekeep pruned idle target",this.logPayload({sessionKey:$,accountId:G.accountId??"main",lastRealRequestAt:G.lastRealRequestAt,maxIdleWarmMs:K})),this.totalBytes-=G.bodyText.length,this.targets.delete($)}}start(){if(this.disposed=!1,this.timer)return;if(this.startedAt=this.now(),this.log.debug("cachekeep started",this.logPayload({ttlMs:this.ttlMs,leadMs:this.leadMs,maxIdleWarmMs:this.maxIdleWarmMs})),this.timer=setInterval(()=>{this.tick().catch(()=>{})},this.tickIntervalMs),"unref"in this.timer)this.timer.unref()}stop(){if(this.disposed=!0,this.abortController.abort(),this.abortController=new AbortController,this.timer)clearInterval(this.timer),this.timer=null;this.startedAt=null,this.targets.clear(),this.totalBytes=0,this.log.debug("cachekeep stopped",this.logPayload())}remove(Y){let X=this.targets.get(Y);if(X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y),this.log.debug("cachekeep removed target",this.logPayload({sessionKey:Y}))}status(){let Y=this.now(),X=Array.from(this.targets.entries()).map(([J,Q])=>({sessionKey:J,accountId:Q.accountId,route:Q.route,cacheExpiresAt:Q.cacheExpiresAt,lastRealRequestAt:Q.lastRealRequestAt,lastWarmedAt:Q.lastWarmedAt,backoffUntil:Q.backoffUntil,bodyBytes:Q.bodyText.length}));return{running:this.timer!=null,tracked:this.targets.size,generatedAt:Y,startedAt:this.startedAt,maxIdleWarmMs:this.maxIdleWarmMs,maxSubagentIdleMs:this.maxSubagentIdleMs,ttlMs:this.ttlMs,leadMs:this.leadMs,sustain:this.getSustain?.()===!0,window:this.getWindow?.(),targets:X}}async tick(){if(this.tickInFlight)return;this.tickInFlight=!0;try{this.pruneStale();let Y=this.getWindow?.();if(Y&&!UX(Y,new Date(this.now())))return;let X=this.now(),J=X+this.leadMs;for(let[Q,$]of this.targets)if($.backoffUntil&&X>=$.backoffUntil&&$.cacheExpiresAt<=J)await this.prewarm(Q,$);for(let[Q,$]of this.targets){if($.backoffUntil&&X<$.backoffUntil)continue;if($.cacheExpiresAt<=J)await this.prewarm(Q,$)}}finally{this.tickInFlight=!1}}async prewarm(Y,X){let J;try{if(X.accountId&&X.accountId!=="main")J=await this.refreshFallback(X.accountId);else J=await this.getMainToken()}catch($){if(!this.disposed&&this.targets.get(Y)===X)X.backoffUntil=this.now()+q8;this.log.debug("cachekeep skip (no token)",this.logPayload({sessionKey:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}));return}if(this.disposed||this.targets.get(Y)!==X)return;let Q={...X.replayHeaders,authorization:`Bearer ${J}`,"content-type":"application/json"};if(X.chatgptAccountId)Q["ChatGPT-Account-Id"]=X.chatgptAccountId;else delete Q["ChatGPT-Account-Id"];try{let $=$5(X.bodyText),G;try{let j=JSON.parse($);G={warmBodyKeys:Object.keys(j),stream:j.stream,max_output_tokens:j.max_output_tokens,store:j.store,has_stream_options:"stream_options"in j,has_max_tokens:"max_tokens"in j,model:j.model}}catch{}this.log.debug("cachekeep warm request",this.logPayload({...G,headerKeys:Object.keys(Q),hasChatGptAccountId:"ChatGPT-Account-Id"in Q}));let W=wY({method:"POST",headers:Q,body:$,signal:AbortSignal.any([AbortSignal.timeout(30000),this.abortController.signal])}),K=await this.fetchImpl(this.codexResponsesUrl,W),H="";try{H=await K.text()}catch{}if(this.disposed||this.targets.get(Y)!==X)return;if(!K.ok){X.backoffUntil=this.now()+q8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",status:K.status,error:`HTTP ${K.status}`,responseBody:H.slice(0,600)}));return}let U=K.headers.get("content-type")??"",N=U.includes("text/event-stream")||/(^|\n)(data:|event:)/.test(H.slice(0,200));this.log.debug("cachekeep warm response",this.logPayload({status:K.status,contentType:U,bodyLen:H.length,isSse:N}));let O=N?z5(H):W5(H),B=E1(K.headers),L=B.primary?.usedPercent??null,Z=B.secondary?.usedPercent??null;if(this.log.debug("cachekeep fired",this.logPayload({session:Y,accountId:X.accountId??"main",input_tokens:O.input_tokens,cached_tokens:O.cached_tokens,hit_rate:O.hit_rate,output_tokens:O.output_tokens,quota_primary_pct:L,quota_secondary_pct:Z})),X.cacheExpiresAt=this.now()+X.ttlMs,X.lastWarmedAt=this.now(),X.backoffUntil=void 0,X.warmCount+=1,this.isGpt56Subagent(X)&&X.warmCount>=2){if(this.targets.get(Y)===X)this.totalBytes-=X.bodyText.length,this.targets.delete(Y);return}}catch($){if(this.disposed||this.targets.get(Y)!==X)return;X.backoffUntil=this.now()+q8,this.log.warn("cachekeep failed",this.logPayload({session:Y,accountId:X.accountId??"main",error:$ instanceof Error?$.message:String($)}))}}}var DX=900000,K5=0.016666666666666666,qX=0.000001;function w8(Y,X){for(let J of[Y?.primary?.checkedAt,Y?.checkedAt,X])if(typeof J==="number"&&Number.isFinite(J))return J;return}function E8(Y){if(Y.status===401||Y.status===403)return{action:"migrate",reason:"permanent"};if(!Y.quota)return{action:"retain",reason:"unknown"};let X=w8(Y.quota,Y.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Y.now-X>DX)return{action:"retain",reason:"stale"};if(Y.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};let J=P8(Y.quota).sort((Q,$)=>{let G=Q.windowMs,W=$.windowMs,K=typeof G==="number"&&Number.isFinite(G),H=typeof W==="number"&&Number.isFinite(W);if(K!==H)return K?-1:1;if(K&&H)return W-G;return 0});for(let{key:Q,window:$}of J)if(Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)return{action:"migrate",reason:"exhausted",windowKey:Q,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{}};if(Y.status===void 0||Y.status===0||!Number.isFinite(Y.status)||Y.status>=500&&Y.status<=599||Y.status===429)return{action:"retain",reason:"transient"};return{action:"retain",reason:"healthy"}}function U5(Y,X,J){let Q=Math.max(0,Y.remainingPercent-X);if(Q<=0)return 0;if(!Y.resetsAt)return Q;let $=Date.parse(Y.resetsAt);if(!Number.isFinite($)||$<=J)return Q;let G=Math.max(($-J)/3600000,K5);return Q/G}function jX(Y,X){if(Y<X)return-1;if(Y>X)return 1;return 0}function H5(Y,X){if(!Y.quota)return;let J=w8(Y.quota,Y.quotaCheckedAt);if(J===void 0||X-J>DX)return;let Q=P8(Y.quota).map(({key:G,window:W})=>{return U5(W,Y.reservePercent[G]??0,X)}),$=Q.length>0?Math.min(...Q):0;return $>0?{candidate:Y,quotaCheckedAt:J,weight:$}:void 0}function PX(Y){let X=Y.candidates.filter(($)=>$.killswitchPasses!==!1);if(Y.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if(X.length===0)return;let J=X.map(($)=>H5($,Y.now)).filter(($)=>$!==void 0);if(J.length>0){J.sort((G,W)=>{let K=((Y.pendingBytes.get(G.candidate.accountId)??0)+Y.requestBytes)/Math.max(G.weight,qX),H=((Y.pendingBytes.get(W.candidate.accountId)??0)+Y.requestBytes)/Math.max(W.weight,qX);return K-H||G.candidate.configuredOrder-W.candidate.configuredOrder||jX(G.candidate.accountId,W.candidate.accountId)});let $=J[0];if($)return{accountId:$.candidate.accountId,quotaCheckedAt:$.quotaCheckedAt,source:"weighted"}}Y.onEmptyWeightedSet?.();let Q=[...X].sort(($,G)=>{let W=($.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-W||$.configuredOrder-G.configuredOrder||jX($.accountId,G.accountId)})[0];if(!Q)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:Q.accountId,quotaCheckedAt:w8(Q.quota,Q.quotaCheckedAt),source:"mode-fallback"}}import{createHash as L5}from"node:crypto";import{chmod as N5,mkdir as V5,writeFile as M8}from"node:fs/promises";import{join as B5}from"node:path";var T8=L0("dump"),r0="x-cortexkit-openai-auth-dump-session",wX=0,M1=new Map,Z5=100;function A8(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function O5(Y){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return"session-unknown";return X.length<=80?X:X.slice(0,80)}function MX(Y){return L5("sha256").update(Y).digest("hex")}function R8(Y){return MX(JSON.stringify(Y))}function AX(Y){try{let X=JSON.parse(Y);return X!=null&&typeof X==="object"&&!Array.isArray(X)?X:void 0}catch{return}}function F5(Y,X){if(Y===void 0)return null;if(Y===X)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:X.length};let J=0;while(J<Y.length&&J<X.length&&Y[J]===X[J])J++;let Q=Y.length-1,$=X.length-1;while(Q>=J&&$>=J&&Y[Q]===X[$])Q--,$--;return{changed:!0,firstByte:J,lastPreviousByte:Q,lastCurrentByte:$,changedPreviousBytes:Q-J+1,changedCurrentBytes:$-J+1,previousBytes:Y.length,currentBytes:X.length}}function q5(Y,X){if(!M1.has(Y))while(M1.size>=Z5){let J=M1.keys().next().value;if(J===void 0)break;M1.delete(J)}M1.set(Y,X)}function j5(Y){if(Y===void 0)return;return Object.fromEntries(new Headers(Y).entries())}function C8(Y){if(Array.isArray(Y))return Y.map(C8);if(Y==null||typeof Y!=="object")return Y;let X={};for(let[J,Q]of Object.entries(Y)){let $=J.toLowerCase();if($==="authorization"||$==="chatgpt-account-id"||$==="cookie"||$==="set-cookie"){X[J]="[redacted]";continue}X[J]=C8(Q)}return X}function D5(Y){let X=AX(Y);if(X===void 0)return Y;let J=EX(X),Q=JSON.stringify(J);if(Q===void 0)return Y;return JSON.stringify(X)===Q?Y:Q}function P5(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function w5(Y){let X=AX(Y);if(!X)return{parseable:!1};let J=Array.isArray(X.input)?X.input:[],Q=Array.isArray(X.tools)?X.tools:[],$=Q.map(P5),G=X.client_metadata!=null&&typeof X.client_metadata==="object"&&!Array.isArray(X.client_metadata)?X.client_metadata:void 0;return{parseable:!0,model:typeof X.model==="string"?X.model:void 0,stream:X.stream,generate:X.generate,store:X.store,previousResponseID:typeof X.previous_response_id==="string"?X.previous_response_id:void 0,promptCacheKey:typeof X.prompt_cache_key==="string"?X.prompt_cache_key:void 0,reasoning:X.reasoning,inputCount:J.length,inputHash:R8(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:R8(J[0]),toolsCount:Q.length,toolTypes:$,toolsHash:R8(Q),hasWebSearch:$.includes("web_search"),clientMetadataKeys:G?Object.keys(G).sort():[]}}async function A1(Y){let X=w0();if(!X.dump)return;wX++;let J=Y.sessionID?.trim()||"session-unknown",Q=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(wX).padStart(5,"0")}-${O5(J)}-${Y.transport}-${Y.phase}`,$=B5(X.dumpDir,Q),G={body:`${$}.body.json`,metadata:`${$}.meta.json`,request:`${$}.request.json`},W=`${Y.transport}:${J}`,K=M1.get(W);try{await V5(X.dumpDir,{recursive:!0,mode:448}),await N5(X.dumpDir,448).catch(()=>{});let H=D5(Y.bodyText),U={id:Q,createdAt:new Date().toISOString(),session:A8(J),transport:Y.transport,phase:Y.phase,accountId:Y.accountId,status:Y.status,error:Y.error,bodyBytes:Y.bodyText.length,bodyHash:MX(Y.bodyText),diff:F5(K,Y.bodyText),body:w5(Y.bodyText),files:G};await Promise.all([M8(G.body,H,{encoding:"utf8",mode:384}),M8(G.metadata,`${JSON.stringify(U,null,2)}
98
+ `,{encoding:"utf8",mode:384}),M8(G.request,`${JSON.stringify(C8({url:Y.url,method:Y.method,accountId:Y.accountId,headers:j5(Y.headers)}),null,2)}
99
+ `,{encoding:"utf8",mode:384})]),T8.debug("dumped request",{id:Q,session:A8(J),body:G.body,meta:G.metadata}),q5(W,Y.bodyText)}catch(H){T8.warn("request dump failed",{session:A8(J),error:H instanceof Error?H.message:String(H)})}}async function c0(Y){if(!w0().dump)return;T8.debug("diagnostic",Y)}import{tool as f1}from"@opencode-ai/plugin";var EY="ws_",CX=new Map,_X=f1({description:"Provider-executed OpenAI web search. This tool is handled server-side by OpenAI; the local plugin records the hosted action for deterministic replay.",args:{type:f1.schema.string().optional(),query:f1.schema.string().optional(),queries:f1.schema.array(f1.schema.string()).optional()},async execute(Y){return{title:"OpenAI Web Search",output:JSON.stringify({action:Y}),metadata:{action:Y}}}});function I8(Y){if(E5(Y))return;if(!A5(Y))return Y;let X=Y.item;return CX.set(X.id,X),{...Y,item:{type:"function_call",id:X.id,call_id:X.id,name:"web_search",arguments:JSON.stringify(_(X.action)?X.action:{})}}}function IX(Y){if(!Y.body)return Y;if(!(Y.headers.get("content-type")??"").includes("text/event-stream"))return Y;return new Response(M5(Y.body),{status:Y.status,statusText:Y.statusText,headers:Y.headers})}function SX(Y){if(!Array.isArray(Y.input))return!1;let X=!1,J=new Map,Q=[],$=new Map,G=new Map;for(let W of Y.input)if(_(W)&&typeof W.call_id==="string"&&W.call_id.startsWith(EY)){if(W.type==="function_call")$.set(W.call_id,W);else if(W.type==="function_call_output"&&typeof W.output==="string")G.set(W.call_id,W.output)}for(let W of Y.input){if(R5(W)){J.set(W.call_id,W),X=!0;continue}if(T5(W,J)){Q.push(_8(W.call_id,W.output,J.get(W.call_id))),X=!0;continue}if(C5(W)){let K=CX.get(W.id);if(K)Q.push(_8(W.id,K));else{let H=$.get(W.id),U=G.get(W.id);if(H||U)Q.push(_8(W.id,U,H));else Q.push(W)}X=!0;continue}Q.push(W)}if(X)Y.input=Q;return X}function E5(Y){if(typeof Y.type==="string"&&Y.type.startsWith("response.web_search_call."))return!0;return Y.type==="response.output_item.added"&&_(Y.item)&&Y.item.type==="web_search_call"}function M5(Y){let X=new TextDecoder,J=new TextEncoder,Q="";return Y.pipeThrough(new TransformStream({transform($,G){Q+=X.decode($,{stream:!0});let W=RX(Q);while(W){let K=Q.slice(0,W.index);Q=Q.slice(W.index+W.length);let H=TX(K);if(H)G.enqueue(J.encode(H));W=RX(Q)}},flush($){if(Q+=X.decode(),!Q)return;let G=TX(Q);if(G)$.enqueue(J.encode(G))}}))}function RX(Y){let X=Y.indexOf(`
100
+
101
+ `),J=Y.indexOf(`\r
88
102
  \r
89
- `);if(U===-1)return z===-1?void 0:{index:z,length:4};if(z===-1||U<z)return{index:U,length:2};return{index:z,length:4}}function dN($){let U=$.split(/\r?\n/).filter((z)=>z.startsWith("data:")).map((z)=>z.slice(5).trimStart()).join(`
90
- `);if(!U)return`${$}
103
+ `);if(X===-1)return J===-1?void 0:{index:J,length:4};if(J===-1||X<J)return{index:X,length:2};return{index:J,length:4}}function TX(Y){let X=Y.split(/\r?\n/).filter((J)=>J.startsWith("data:")).map((J)=>J.slice(5).trimStart()).join(`
104
+ `);if(!X)return`${Y}
91
105
 
92
- `;if(U==="[DONE]")return`data: [DONE]
106
+ `;if(X==="[DONE]")return`data: [DONE]
93
107
 
94
- `;try{let z=JSON.parse(U);if(!k(z))return`${$}
108
+ `;try{let J=JSON.parse(X);if(!_(J))return`${Y}
95
109
 
96
- `;let X=$J(z);if(!X)return"";return`data: ${JSON.stringify(X)}
110
+ `;let Q=I8(J);if(!Q)return"";return`data: ${JSON.stringify(Q)}
97
111
 
98
- `}catch{return`${$}
112
+ `}catch{return`${Y}
99
113
 
100
- `}}function OG($){return $.type==="response.output_item.done"&&k($.item)&&$.item.type==="web_search_call"&&typeof $.item.id==="string"}function WG($){return k($)&&$.type==="function_call"&&$.name==="web_search"&&typeof $.call_id==="string"&&$.call_id.startsWith($U)}function GG($,U){return k($)&&$.type==="function_call_output"&&typeof $.call_id==="string"&&typeof $.output==="string"&&$.call_id.startsWith($U)&&U.has($.call_id)}function QG($){return k($)&&$.type==="item_reference"&&typeof $.id==="string"&&$.id.startsWith($U)}function e0($,U,z){let X=wG(U),J=k(X?.action)?X.action:HG(z?.arguments);return{type:"web_search_call",status:"completed",...J?{action:J}:{}}}function wG($){if(k($))return $;if(typeof $!=="string")return;try{let U=JSON.parse($);return k(U)?U:void 0}catch{return}}function HG($){if(k($))return $;if(typeof $!=="string")return;try{let U=JSON.parse($);return k(U)?U:void 0}catch{return}}import{readFile as VG}from"node:fs/promises";import{homedir as LG}from"node:os";import{join as eN}from"node:path";var BG="https://models.dev/api.json",DG="OPENCODE_OPENAI_AUTH_MODELS_CACHE",KG="OPENCODE_MODELS_PATH",qG="OPENCODE_DISABLE_MODELS_FETCH",_G=1e4,vG=300000;function M6($){return $!==null&&typeof $==="object"&&!Array.isArray($)?$:null}function $8($){if($===void 0)return 0;return typeof $==="number"&&Number.isFinite($)&&$>=0?$:null}function UJ($){let{input:U,output:z}=$;if(typeof U!=="number"||!Number.isFinite(U)||U<0)return null;if(typeof z!=="number"||!Number.isFinite(z)||z<0)return null;let X=$8($.cache_read),J=$8($.cache_write);if(X===null||J===null)return null;return{input:U,output:z,cache:{read:X,write:J}}}function FG($){let U=M6($);if(!U)return null;let z=UJ(U);if(!z)return null;let X=z;if(Array.isArray(U.tiers)){let Y=[];for(let N of U.tiers){let W=M6(N);if(!W)continue;let G=M6(W.tier),Q=G?.size;if(G?.type!=="context")continue;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=0)continue;let L=UJ(W);if(!L)continue;Y.push({...L,tier:{type:"context",size:Q}})}if(Y.length>0)X.tiers=Y}let J=M6(U.context_over_200k),j=J?UJ(J):null;if(j)X.experimentalOver200K=j;return X}function U8($){let U=M6($),z=M6(U?.openai),X=M6(z?.models);if(!X)return null;let J={};for(let[j,Y]of Object.entries(X)){let N=M6(Y),W=FG(N?.cost);if(W)J[j]=W}return Object.keys(J).length>0?J:null}function PG(){let $=process.env[DG]?.trim();if($)return $;let U=process.env[KG]?.trim();if(U)return U;let z=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||eN(LG(),".cache");return eN(z,"opencode","models.json")}function AG(){let $=process.env[qG]?.toLowerCase();return $==="true"||$==="1"}async function EG(){try{let $=U8(JSON.parse(await VG(PG(),"utf8")));if($)return $}catch{}if(AG())return null;try{let $=await fetch(BG,{signal:AbortSignal.timeout(_G)});if(!$.ok)return null;return U8(await $.json())}catch{return null}}var N4;function J8(){let $=Date.now();if(N4&&N4.expiresAt>$)return N4.promise;let U={expiresAt:$+vG,promise:EG()};return N4=U,U.promise.then((z)=>{if(z===null&&N4===U)N4=void 0}),U.promise}function O4($){return typeof $==="object"&&$!==null}function MG($){if(Array.isArray($))return $;if(O4($)&&Array.isArray($.data))return $.data;return[]}function bG($){if(!O4($)||!O4($.info))return;return typeof $.info.role==="string"?$.info.role:void 0}function z8($){if(!O4($)||!O4($.info))return null;let U=$.info,z=O4(U.model)?U.model:void 0,X=typeof U.agent==="string"?U.agent:void 0,J=typeof z?.providerID==="string"?z.providerID:typeof U.providerID==="string"?U.providerID:void 0,j=typeof z?.modelID==="string"?z.modelID:typeof U.modelID==="string"?U.modelID:void 0,Y=typeof z?.variant==="string"?z.variant:typeof U.variant==="string"?U.variant:void 0;if(!X&&(!J||!j)&&!Y)return null;let N={};if(X)N.agent=X;if(J&&j)N.model={providerID:J,modelID:j};if(Y)N.variant=Y;return N}function X8($,U){return{agent:$.agent??U.agent,model:$.model??U.model,variant:$.variant??U.variant}}function j8($){return Boolean($.agent&&$.model&&$.variant)}async function Y8($,U){if(!$||!U)return null;let z=$;if(typeof z.session?.messages!=="function")return null;let X=[];try{X=MG(await Promise.resolve(z.session.messages({path:{id:U},query:{limit:100}})))}catch{return null}if(X.length===0)return null;let J={};for(let j=X.length-1;j>=0;j--){if(bG(X[j])!=="assistant")continue;let Y=z8(X[j]);if(!Y)continue;if(J=X8(J,Y),j8(J))return J}for(let j=X.length-1;j>=0;j--){let Y=z8(X[j]);if(!Y)continue;if(J=X8(J,Y),j8(J))return J}if(!J.agent&&!J.model&&!J.variant)return null;return J}var b6=[],RG=1,JJ=0,N8=new Map;function zJ($,U){if(b6.push({id:RG++,type:"open-dialog",payload:$,sessionId:U}),b6.length>100)b6=b6.slice(b6.length-100)}function O8($=0,U){let z=Date.now();if(JJ=z,U!==void 0)N8.set(U,z);let X=(J)=>U===void 0||J.sessionId===void 0||J.sessionId===U;if($>0)b6=b6.filter((J)=>{if(J.id>$)return!0;if(U===void 0)return!1;return J.sessionId!==U});return b6.filter((J)=>J.id>$&&X(J))}function W8($){let U=Date.now();if($!==void 0){let z=N8.get($)??0;return z>0&&U-z<3000}return JJ>0&&U-JJ<3000}import{randomBytes as IG,timingSafeEqual as SG}from"node:crypto";import{unlink as kG}from"node:fs/promises";import{createServer as CG}from"node:http";import{join as ZG}from"node:path";var TG=q$("rpc");function gG($){return new Promise((U,z)=>{let X=[],J=0;$.on("data",(j)=>{if(J+=j.length,J>1e6){$.destroy(),z(Error("body too large"));return}X.push(j)}),$.on("end",()=>U(Buffer.concat(X).toString("utf8"))),$.on("error",z)})}function xG($,U){if(!$?.startsWith("Bearer "))return!1;let z=Buffer.from($.slice(7)),X=Buffer.from(U);return z.length===X.length&&SG(z,X)}async function Q8($){let U=IG(32).toString("hex"),z=$.timeoutMs??2000,X=CG((Y,N)=>{Y.setTimeout(z,()=>{Y.socket.destroy()}),J(Y,N)});X.requestTimeout=z,X.headersTimeout=z;async function J(Y,N){let W=(G,Q)=>{if(N.headersSent||N.writableEnded||N.destroyed)return;N.writeHead(G,{"content-type":"application/json"}),N.end(JSON.stringify(Q))};try{let G=Y.url??"";if(Y.method==="GET"&&G==="/health")return W(200,{ok:!0});if(Y.method!=="POST"||!G.startsWith("/rpc/"))return W(404,{error:"not found"});if(!xG(Y.headers.authorization,U))return W(401,{error:"unauthorized"});let Q=G.slice(5),L=await gG(Y),H=JSON.parse(L||"{}");if(Q==="pending-notifications"){let w=$.drain(Number(H.lastReceivedId??0),typeof H.sessionId==="string"?H.sessionId:void 0);return W(200,{messages:w})}if(Q==="apply"){let w=await $.apply(H);return W(200,w)}return W(404,{error:"unknown method"})}catch(G){W(500,{error:G instanceof Error?G.message:String(G)})}}let j=await new Promise((Y,N)=>{X.on("error",N),X.listen(0,"127.0.0.1",()=>{let W=X.address();if(W&&typeof W==="object")Y(W.port);else N(Error("no port"))})});X.unref();try{await G8($.dir,{port:j,token:U,pid:process.pid}),TG.debug("rpc server pid",{pid:process.pid,rpcPort:j})}catch(Y){throw await new Promise((N)=>X.close(()=>N())),Y}return{port:j,token:U,async stop(){await new Promise((Y)=>X.close(()=>Y())),await kG(ZG($.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function Q6($){return JSON.stringify(XJ($))??"undefined"}function XJ($){if(Array.isArray($))return $.map(XJ);if(!k($))return $;return Object.fromEntries(Object.keys($).sort().map((U)=>[U,XJ($[U])]))}function i6(){let $=crypto.getRandomValues(new Uint8Array(16)),U=Date.now();$[0]=U/1099511627776&255,$[1]=U/4294967296&255,$[2]=U/16777216&255,$[3]=U/65536&255,$[4]=U/256&255,$[5]=U&255,$[6]=($[6]??0)&15|112,$[8]=($[8]??0)&63|128;let z=Array.from($,(X)=>X.toString(16).padStart(2,"0")).join("");return`${z.slice(0,8)}-${z.slice(8,12)}-${z.slice(12,16)}-${z.slice(16,20)}-${z.slice(20)}`}var h6={};w6(h6,{withoutInternalHeaders:()=>xW,sanitizeHttpFallbackBody:()=>i0,orderCodexBody:()=>l1,hasWebSocketResponsesLiteMetadata:()=>u0,createWebSocketFetch:()=>QD,applyTurnId:()=>ZW,TITLE_HEADER:()=>wN,QUOTA_ACCOUNT_HEADER:()=>E0,OpenAIWebSocketPool:()=>h6,CODEX_BODY_KEY_ORDER:()=>kW});import{createHash as YD}from"node:crypto";var u8="vercel.ai.error",fG=Symbol.for(u8),w8,H8,$$=class $ extends(H8=Error,w8=fG,H8){constructor({name:U,message:z,cause:X}){super(z);this[w8]=!0,this.name=U,this.cause=X}static isInstance(U){return $.hasMarker(U,u8)}static hasMarker(U,z){let X=Symbol.for(z);return U!=null&&typeof U==="object"&&X in U&&typeof U[X]==="boolean"&&U[X]===!0}},i8="AI_APICallError",l8=`vercel.ai.error.${i8}`,hG=Symbol.for(l8),V8,L8,T4=class extends(L8=$$,V8=hG,L8){constructor({message:$,url:U,requestBodyValues:z,statusCode:X,responseHeaders:J,responseBody:j,cause:Y,isRetryable:N=X!=null&&(X===408||X===409||X===429||X>=500),data:W}){super({name:i8,message:$,cause:Y});this[V8]=!0,this.url=U,this.requestBodyValues=z,this.statusCode=X,this.responseHeaders=J,this.responseBody=j,this.isRetryable=N,this.data=W}static isInstance($){return $$.hasMarker($,l8)}},n8="AI_EmptyResponseBodyError",r8=`vercel.ai.error.${n8}`,yG=Symbol.for(r8),B8,D8,cG=class extends(D8=$$,B8=yG,D8){constructor({message:$="Empty response body"}={}){super({name:n8,message:$});this[B8]=!0}static isInstance($){return $$.hasMarker($,r8)}};function jJ($){if($==null)return"unknown error";if(typeof $==="string")return $;if($ instanceof Error)return $.toString();return JSON.stringify($)}var p8="AI_InvalidArgumentError",d8=`vercel.ai.error.${p8}`,mG=Symbol.for(d8),K8,q8,o8=class extends(q8=$$,K8=mG,q8){constructor({message:$,cause:U,argument:z}){super({name:p8,message:$,cause:U});this[K8]=!0,this.argument=z}static isInstance($){return $$.hasMarker($,d8)}},t8="AI_InvalidPromptError",a8=`vercel.ai.error.${t8}`,uG=Symbol.for(a8),_8,v8,iG=class extends(v8=$$,_8=uG,v8){constructor({prompt:$,message:U,cause:z}){super({name:t8,message:`Invalid prompt: ${U}`,cause:z});this[_8]=!0,this.prompt=$}static isInstance($){return $$.hasMarker($,a8)}},s8="AI_InvalidResponseDataError",e8=`vercel.ai.error.${s8}`,lG=Symbol.for(e8),F8,P8,nG=class extends(P8=$$,F8=lG,P8){constructor({data:$,message:U=`Invalid response data: ${JSON.stringify($)}.`}){super({name:s8,message:U});this[F8]=!0,this.data=$}static isInstance($){return $$.hasMarker($,e8)}},$9="AI_JSONParseError",U9=`vercel.ai.error.${$9}`,rG=Symbol.for(U9),A8,E8,UU=class extends(E8=$$,A8=rG,E8){constructor({text:$,cause:U}){super({name:$9,message:`JSON parsing failed: Text: ${$}.
101
- Error message: ${jJ(U)}`,cause:U});this[A8]=!0,this.text=$}static isInstance($){return $$.hasMarker($,U9)}},J9="AI_LoadAPIKeyError",z9=`vercel.ai.error.${J9}`,pG=Symbol.for(z9),M8,b8,dG=class extends(b8=$$,M8=pG,b8){constructor({message:$}){super({name:J9,message:$});this[M8]=!0}static isInstance($){return $$.hasMarker($,z9)}},X9="AI_LoadSettingError",j9=`vercel.ai.error.${X9}`,oG=Symbol.for(j9),R8,I8,tG=class extends(I8=$$,R8=oG,I8){constructor({message:$}){super({name:X9,message:$});this[R8]=!0}static isInstance($){return $$.hasMarker($,j9)}},Y9="AI_NoContentGeneratedError",N9=`vercel.ai.error.${Y9}`,aG=Symbol.for(N9),S8,k8,sG=class extends(k8=$$,S8=aG,k8){constructor({message:$="No content generated."}={}){super({name:Y9,message:$});this[S8]=!0}static isInstance($){return $$.hasMarker($,N9)}},O9="AI_NoSuchModelError",W9=`vercel.ai.error.${O9}`,eG=Symbol.for(W9),C8,Z8,$Q=class extends(Z8=$$,C8=eG,Z8){constructor({errorName:$=O9,modelId:U,modelType:z,message:X=`No such ${z}: ${U}`}){super({name:$,message:X});this[C8]=!0,this.modelId=U,this.modelType=z}static isInstance($){return $$.hasMarker($,W9)}},G9="AI_NoSuchProviderReferenceError",Q9=`vercel.ai.error.${G9}`,UQ=Symbol.for(Q9),T8,g8,JQ=class extends(g8=$$,T8=UQ,g8){constructor({provider:$,reference:U,message:z=`No provider reference found for provider '${$}'. Available providers: ${Object.keys(U).join(", ")}`}){super({name:G9,message:z});this[T8]=!0,this.provider=$,this.reference=U}static isInstance($){return $$.hasMarker($,Q9)}},w9="AI_TooManyEmbeddingValuesForCallError",H9=`vercel.ai.error.${w9}`,zQ=Symbol.for(H9),x8,f8,XQ=class extends(f8=$$,x8=zQ,f8){constructor($){super({name:w9,message:`Too many values for a single embedding call. The ${$.provider} model "${$.modelId}" can only embed up to ${$.maxEmbeddingsPerCall} values per call, but ${$.values.length} values were provided.`});this[x8]=!0,this.provider=$.provider,this.modelId=$.modelId,this.maxEmbeddingsPerCall=$.maxEmbeddingsPerCall,this.values=$.values}static isInstance($){return $$.hasMarker($,H9)}},V9="AI_TypeValidationError",L9=`vercel.ai.error.${V9}`,jQ=Symbol.for(L9),h8,y8,s$=class $ extends(y8=$$,h8=jQ,y8){constructor({value:U,cause:z,context:X}){let J="Type validation failed";if(X==null?void 0:X.field)J+=` for ${X.field}`;if((X==null?void 0:X.entityName)||(X==null?void 0:X.entityId)){J+=" (";let j=[];if(X.entityName)j.push(X.entityName);if(X.entityId)j.push(`id: "${X.entityId}"`);J+=j.join(", "),J+=")"}super({name:V9,message:`${J}: Value: ${JSON.stringify(U)}.
102
- Error message: ${jJ(z)}`,cause:z});this[h8]=!0,this.value=U,this.context=X}static isInstance(U){return $$.hasMarker(U,L9)}static wrap({value:U,cause:z,context:X}){var J,j,Y;if($.isInstance(z)&&z.value===U&&((J=z.context)==null?void 0:J.field)===(X==null?void 0:X.field)&&((j=z.context)==null?void 0:j.entityName)===(X==null?void 0:X.entityName)&&((Y=z.context)==null?void 0:Y.entityId)===(X==null?void 0:X.entityId))return z;return new $({value:U,cause:z,context:X})}},B9="AI_UnsupportedFunctionalityError",D9=`vercel.ai.error.${B9}`,YQ=Symbol.for(D9),c8,m8,NQ=class extends(m8=$$,c8=YQ,m8){constructor({functionality:$,message:U=`'${$}' functionality not supported.`}){super({name:B9,message:U});this[c8]=!0,this.functionality=$}static isInstance($){return $$.hasMarker($,D9)}};var O={};w6(O,{xid:()=>d7,void:()=>K5,uuidv7:()=>c7,uuidv6:()=>y7,uuidv4:()=>h7,uuid:()=>f7,util:()=>v,url:()=>m7,uppercase:()=>N1,unknown:()=>v4,union:()=>fY,undefined:()=>B5,ulid:()=>p7,uint64:()=>V5,uint32:()=>Q5,tuple:()=>HO,trim:()=>H1,treeifyError:()=>BJ,transform:()=>cY,toUpperCase:()=>L1,toLowerCase:()=>V1,toJSONSchema:()=>B1,templateLiteral:()=>g5,symbol:()=>L5,superRefine:()=>hO,success:()=>C5,stringbool:()=>m5,stringFormat:()=>X5,string:()=>LY,strictObject:()=>F5,startsWith:()=>W1,size:()=>X1,setErrorMap:()=>n5,set:()=>b5,safeParseAsync:()=>D1,safeParse:()=>YY,safeEncodeAsync:()=>HY,safeEncode:()=>QY,safeDecodeAsync:()=>VY,safeDecode:()=>wY,registry:()=>bU,regexes:()=>i$,regex:()=>j1,refine:()=>fO,record:()=>VO,readonly:()=>kO,property:()=>pj,promise:()=>x5,prettifyError:()=>DJ,preprocess:()=>i5,prefault:()=>AO,positive:()=>ij,pipe:()=>z0,partialRecord:()=>E5,parseAsync:()=>jY,parse:()=>XY,overwrite:()=>L6,optional:()=>U0,object:()=>v5,number:()=>s9,nullish:()=>k5,nullable:()=>J0,null:()=>zO,normalize:()=>w1,nonpositive:()=>nj,nonoptional:()=>EO,nonnegative:()=>rj,never:()=>gY,negative:()=>lj,nativeEnum:()=>R5,nanoid:()=>l7,nan:()=>Z5,multipleOf:()=>d6,minSize:()=>o6,minLength:()=>Z6,mime:()=>Q1,maxSize:()=>D4,maxLength:()=>K4,map:()=>M5,lte:()=>l$,lt:()=>H6,lowercase:()=>Y1,looseObject:()=>P5,locales:()=>$1,literal:()=>I5,length:()=>q4,lazy:()=>TO,ksuid:()=>o7,keyof:()=>_5,jwt:()=>z5,json:()=>u5,iso:()=>eU,ipv6:()=>a7,ipv4:()=>t7,intersection:()=>QO,int64:()=>H5,int32:()=>G5,int:()=>BY,instanceof:()=>c5,includes:()=>O1,httpUrl:()=>u7,hostname:()=>j5,hex:()=>Y5,hash:()=>N5,guid:()=>x7,gte:()=>I$,gt:()=>V6,globalRegistry:()=>U6,getErrorMap:()=>r5,function:()=>f5,formatError:()=>l4,float64:()=>W5,float32:()=>O5,flattenError:()=>i4,file:()=>S5,enum:()=>yY,endsWith:()=>G1,encodeAsync:()=>WY,encode:()=>NY,emoji:()=>i7,email:()=>g7,e164:()=>J5,discriminatedUnion:()=>A5,decodeAsync:()=>GY,decode:()=>OY,date:()=>q5,custom:()=>y5,cuid2:()=>r7,cuid:()=>n7,core:()=>B6,config:()=>H$,coerce:()=>rY,codec:()=>T5,clone:()=>E$,cidrv6:()=>e7,cidrv4:()=>s7,check:()=>h5,catch:()=>RO,boolean:()=>e9,bigint:()=>w5,base64url:()=>U5,base64:()=>$5,array:()=>Y0,any:()=>D5,_function:()=>f5,_default:()=>FO,_ZodString:()=>DY,ZodXID:()=>AY,ZodVoid:()=>NO,ZodUnknown:()=>jO,ZodUnion:()=>xY,ZodUndefined:()=>UO,ZodUUID:()=>D6,ZodURL:()=>X0,ZodULID:()=>PY,ZodType:()=>i,ZodTuple:()=>wO,ZodTransform:()=>qO,ZodTemplateLiteral:()=>CO,ZodSymbol:()=>$O,ZodSuccess:()=>MO,ZodStringFormat:()=>z$,ZodString:()=>q1,ZodSet:()=>BO,ZodRecord:()=>hY,ZodRealError:()=>S$,ZodReadonly:()=>SO,ZodPromise:()=>gO,ZodPrefault:()=>PO,ZodPipe:()=>iY,ZodOptional:()=>mY,ZodObject:()=>N0,ZodNumberFormat:()=>F4,ZodNumber:()=>v1,ZodNullable:()=>_O,ZodNull:()=>JO,ZodNonOptional:()=>uY,ZodNever:()=>YO,ZodNanoID:()=>_Y,ZodNaN:()=>IO,ZodMap:()=>LO,ZodLiteral:()=>DO,ZodLazy:()=>ZO,ZodKSUID:()=>EY,ZodJWT:()=>ZY,ZodIssueCode:()=>l5,ZodIntersection:()=>GO,ZodISOTime:()=>aU,ZodISODuration:()=>sU,ZodISODateTime:()=>oU,ZodISODate:()=>tU,ZodIPv6:()=>bY,ZodIPv4:()=>MY,ZodGUID:()=>$0,ZodFunction:()=>xO,ZodFirstPartyTypeKind:()=>nY,ZodFile:()=>KO,ZodError:()=>Z7,ZodEnum:()=>K1,ZodEmoji:()=>qY,ZodEmail:()=>KY,ZodE164:()=>CY,ZodDiscriminatedUnion:()=>WO,ZodDefault:()=>vO,ZodDate:()=>j0,ZodCustomStringFormat:()=>_1,ZodCustom:()=>O0,ZodCodec:()=>lY,ZodCatch:()=>bO,ZodCUID2:()=>FY,ZodCUID:()=>vY,ZodCIDRv6:()=>IY,ZodCIDRv4:()=>RY,ZodBoolean:()=>F1,ZodBigIntFormat:()=>TY,ZodBigInt:()=>P1,ZodBase64URL:()=>kY,ZodBase64:()=>SY,ZodArray:()=>OO,ZodAny:()=>XO,TimePrecision:()=>Lj,NEVER:()=>YJ,$output:()=>Qj,$input:()=>wj,$brand:()=>NJ});var B6={};w6(B6,{version:()=>Hz,util:()=>v,treeifyError:()=>BJ,toJSONSchema:()=>B1,toDotPath:()=>P9,safeParseAsync:()=>qJ,safeParse:()=>KJ,safeEncodeAsync:()=>cQ,safeEncode:()=>hQ,safeDecodeAsync:()=>mQ,safeDecode:()=>yQ,registry:()=>bU,regexes:()=>i$,prettifyError:()=>DJ,parseAsync:()=>jU,parse:()=>XU,locales:()=>$1,isValidJWT:()=>m9,isValidBase64URL:()=>c9,isValidBase64:()=>Tz,globalRegistry:()=>U6,globalConfig:()=>g4,formatError:()=>l4,flattenError:()=>i4,encodeAsync:()=>xQ,encode:()=>TQ,decodeAsync:()=>fQ,decode:()=>gQ,config:()=>H$,clone:()=>E$,_xid:()=>hU,_void:()=>yj,_uuidv7:()=>CU,_uuidv6:()=>kU,_uuidv4:()=>SU,_uuid:()=>IU,_url:()=>z1,_uppercase:()=>N1,_unknown:()=>fj,_union:()=>G7,_undefined:()=>Tj,_ulid:()=>fU,_uint64:()=>Cj,_uint32:()=>Mj,_tuple:()=>H7,_trim:()=>H1,_transform:()=>_7,_toUpperCase:()=>L1,_toLowerCase:()=>V1,_templateLiteral:()=>I7,_symbol:()=>Zj,_superRefine:()=>sj,_success:()=>E7,_stringbool:()=>ej,_stringFormat:()=>_4,_string:()=>Hj,_startsWith:()=>W1,_size:()=>X1,_set:()=>B7,_safeParseAsync:()=>L4,_safeParse:()=>V4,_safeEncodeAsync:()=>wU,_safeEncode:()=>GU,_safeDecodeAsync:()=>HU,_safeDecode:()=>QU,_regex:()=>j1,_refine:()=>aj,_record:()=>V7,_readonly:()=>R7,_property:()=>pj,_promise:()=>k7,_positive:()=>ij,_pipe:()=>b7,_parseAsync:()=>H4,_parse:()=>w4,_overwrite:()=>L6,_optional:()=>v7,_number:()=>_j,_nullable:()=>F7,_null:()=>gj,_normalize:()=>w1,_nonpositive:()=>nj,_nonoptional:()=>A7,_nonnegative:()=>rj,_never:()=>hj,_negative:()=>lj,_nativeEnum:()=>K7,_nanoid:()=>TU,_nan:()=>uj,_multipleOf:()=>d6,_minSize:()=>o6,_minLength:()=>Z6,_min:()=>I$,_mime:()=>Q1,_maxSize:()=>D4,_maxLength:()=>K4,_max:()=>l$,_map:()=>L7,_lte:()=>l$,_lt:()=>H6,_lowercase:()=>Y1,_literal:()=>q7,_length:()=>q4,_lazy:()=>S7,_ksuid:()=>yU,_jwt:()=>pU,_isoTime:()=>Kj,_isoDuration:()=>qj,_isoDateTime:()=>Bj,_isoDate:()=>Dj,_ipv6:()=>mU,_ipv4:()=>cU,_intersection:()=>w7,_int64:()=>kj,_int32:()=>Ej,_int:()=>Fj,_includes:()=>O1,_guid:()=>J1,_gte:()=>I$,_gt:()=>V6,_float64:()=>Aj,_float32:()=>Pj,_file:()=>oj,_enum:()=>D7,_endsWith:()=>G1,_encodeAsync:()=>OU,_encode:()=>YU,_emoji:()=>ZU,_email:()=>RU,_e164:()=>rU,_discriminatedUnion:()=>Q7,_default:()=>P7,_decodeAsync:()=>WU,_decode:()=>NU,_date:()=>cj,_custom:()=>tj,_cuid2:()=>xU,_cuid:()=>gU,_coercedString:()=>Vj,_coercedNumber:()=>vj,_coercedDate:()=>mj,_coercedBoolean:()=>Rj,_coercedBigint:()=>Sj,_cidrv6:()=>iU,_cidrv4:()=>uU,_check:()=>d9,_catch:()=>M7,_boolean:()=>bj,_bigint:()=>Ij,_base64url:()=>nU,_base64:()=>lU,_array:()=>dj,_any:()=>xj,TimePrecision:()=>Lj,NEVER:()=>YJ,JSONSchemaGenerator:()=>dU,JSONSchema:()=>o9,Doc:()=>DU,$output:()=>Qj,$input:()=>wj,$constructor:()=>V,$brand:()=>NJ,$ZodXID:()=>Az,$ZodVoid:()=>dz,$ZodUnknown:()=>rz,$ZodUnion:()=>EU,$ZodUndefined:()=>iz,$ZodUUID:()=>Bz,$ZodURL:()=>Kz,$ZodULID:()=>Pz,$ZodType:()=>c,$ZodTuple:()=>MU,$ZodTransform:()=>YX,$ZodTemplateLiteral:()=>DX,$ZodSymbol:()=>uz,$ZodSuccess:()=>wX,$ZodStringFormat:()=>J$,$ZodString:()=>p6,$ZodSet:()=>JX,$ZodRegistry:()=>U1,$ZodRecord:()=>$X,$ZodRealError:()=>R$,$ZodReadonly:()=>BX,$ZodPromise:()=>qX,$ZodPrefault:()=>GX,$ZodPipe:()=>LX,$ZodOptional:()=>NX,$ZodObjectJIT:()=>az,$ZodObject:()=>l9,$ZodNumberFormat:()=>cz,$ZodNumber:()=>PU,$ZodNullable:()=>OX,$ZodNull:()=>lz,$ZodNonOptional:()=>QX,$ZodNever:()=>pz,$ZodNanoID:()=>_z,$ZodNaN:()=>VX,$ZodMap:()=>UX,$ZodLiteral:()=>XX,$ZodLazy:()=>_X,$ZodKSUID:()=>Ez,$ZodJWT:()=>hz,$ZodIntersection:()=>ez,$ZodISOTime:()=>Rz,$ZodISODuration:()=>Iz,$ZodISODateTime:()=>Mz,$ZodISODate:()=>bz,$ZodIPv6:()=>kz,$ZodIPv4:()=>Sz,$ZodGUID:()=>Lz,$ZodFunction:()=>KX,$ZodFile:()=>jX,$ZodError:()=>u4,$ZodEnum:()=>zX,$ZodEncodeError:()=>l6,$ZodEmoji:()=>qz,$ZodEmail:()=>Dz,$ZodE164:()=>fz,$ZodDiscriminatedUnion:()=>sz,$ZodDefault:()=>WX,$ZodDate:()=>oz,$ZodCustomStringFormat:()=>yz,$ZodCustom:()=>vX,$ZodCodec:()=>d4,$ZodCheckUpperCase:()=>Yz,$ZodCheckStringFormat:()=>B4,$ZodCheckStartsWith:()=>Oz,$ZodCheckSizeEquals:()=>$z,$ZodCheckRegex:()=>Xz,$ZodCheckProperty:()=>Gz,$ZodCheckOverwrite:()=>wz,$ZodCheckNumberFormat:()=>tJ,$ZodCheckMultipleOf:()=>oJ,$ZodCheckMinSize:()=>eJ,$ZodCheckMinLength:()=>Jz,$ZodCheckMimeType:()=>Qz,$ZodCheckMaxSize:()=>sJ,$ZodCheckMaxLength:()=>Uz,$ZodCheckLowerCase:()=>jz,$ZodCheckLessThan:()=>LU,$ZodCheckLengthEquals:()=>zz,$ZodCheckIncludes:()=>Nz,$ZodCheckGreaterThan:()=>BU,$ZodCheckEndsWith:()=>Wz,$ZodCheckBigIntFormat:()=>aJ,$ZodCheck:()=>j$,$ZodCatch:()=>HX,$ZodCUID2:()=>Fz,$ZodCUID:()=>vz,$ZodCIDRv6:()=>Zz,$ZodCIDRv4:()=>Cz,$ZodBoolean:()=>p4,$ZodBigIntFormat:()=>mz,$ZodBigInt:()=>AU,$ZodBase64URL:()=>xz,$ZodBase64:()=>gz,$ZodAsyncError:()=>e$,$ZodArray:()=>tz,$ZodAny:()=>nz});var YJ=Object.freeze({status:"aborted"});function V($,U,z){function X(N,W){var G;Object.defineProperty(N,"_zod",{value:N._zod??{},enumerable:!1}),(G=N._zod).traits??(G.traits=new Set),N._zod.traits.add($),U(N,W);for(let Q in Y.prototype)if(!(Q in N))Object.defineProperty(N,Q,{value:Y.prototype[Q].bind(N)});N._zod.constr=Y,N._zod.def=W}let J=z?.Parent??Object;class j extends J{}Object.defineProperty(j,"name",{value:$});function Y(N){var W;let G=z?.Parent?new j:this;X(G,N),(W=G._zod).deferred??(W.deferred=[]);for(let Q of G._zod.deferred)Q();return G}return Object.defineProperty(Y,"init",{value:X}),Object.defineProperty(Y,Symbol.hasInstance,{value:(N)=>{if(z?.Parent&&N instanceof z.Parent)return!0;return N?._zod?.traits?.has($)}}),Object.defineProperty(Y,"name",{value:$}),Y}var NJ=Symbol("zod_brand");class e$ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class l6 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}var g4={};function H$($){if($)Object.assign(g4,$);return g4}var v={};w6(v,{unwrapMessage:()=>x4,uint8ArrayToHex:()=>CQ,uint8ArrayToBase64url:()=>SQ,uint8ArrayToBase64:()=>_9,stringifyPrimitive:()=>P,shallowClone:()=>QJ,safeExtend:()=>AQ,required:()=>bQ,randomString:()=>DQ,propertyKeyTypes:()=>y4,promiseAllObject:()=>BQ,primitiveTypes:()=>wJ,prefixIssues:()=>x$,pick:()=>vQ,partial:()=>MQ,optionalKeys:()=>HJ,omit:()=>FQ,objectClone:()=>HQ,numKeys:()=>KQ,nullish:()=>R6,normalizeParams:()=>A,mergeDefs:()=>S6,merge:()=>EQ,jsonStringifyReplacer:()=>W4,joinValues:()=>D,issue:()=>Q4,isPlainObject:()=>k6,isObject:()=>n6,hexToUint8Array:()=>kQ,getSizableOrigin:()=>c4,getParsedType:()=>qQ,getLengthableOrigin:()=>m4,getEnumValues:()=>f4,getElementAtPath:()=>LQ,floatSafeRemainder:()=>WJ,finalizeIssue:()=>f$,extend:()=>PQ,escapeRegex:()=>$6,esc:()=>JU,defineLazy:()=>a,createTransparentProxy:()=>_Q,cloneDef:()=>VQ,clone:()=>E$,cleanRegex:()=>h4,cleanEnum:()=>RQ,captureStackTrace:()=>zU,cached:()=>G4,base64urlToUint8Array:()=>IQ,base64ToUint8Array:()=>q9,assignProp:()=>I6,assertNotEqual:()=>WQ,assertNever:()=>QQ,assertIs:()=>GQ,assertEqual:()=>OQ,assert:()=>wQ,allowsEval:()=>GJ,aborted:()=>C6,NUMBER_FORMAT_RANGES:()=>VJ,Class:()=>v9,BIGINT_FORMAT_RANGES:()=>LJ});function OQ($){return $}function WQ($){return $}function GQ($){}function QQ($){throw Error()}function wQ($){}function f4($){let U=Object.values($).filter((X)=>typeof X==="number");return Object.entries($).filter(([X,J])=>U.indexOf(+X)===-1).map(([X,J])=>J)}function D($,U="|"){return $.map((z)=>P(z)).join(U)}function W4($,U){if(typeof U==="bigint")return U.toString();return U}function G4($){return{get value(){{let z=$();return Object.defineProperty(this,"value",{value:z}),z}throw Error("cached value already set")}}}function R6($){return $===null||$===void 0}function h4($){let U=$.startsWith("^")?1:0,z=$.endsWith("$")?$.length-1:$.length;return $.slice(U,z)}function WJ($,U){let z=($.toString().split(".")[1]||"").length,X=U.toString(),J=(X.split(".")[1]||"").length;if(J===0&&/\d?e-\d?/.test(X)){let W=X.match(/\d?e-(\d?)/);if(W?.[1])J=Number.parseInt(W[1])}let j=z>J?z:J,Y=Number.parseInt($.toFixed(j).replace(".","")),N=Number.parseInt(U.toFixed(j).replace(".",""));return Y%N/10**j}var K9=Symbol("evaluating");function a($,U,z){let X=void 0;Object.defineProperty($,U,{get(){if(X===K9)return;if(X===void 0)X=K9,X=z();return X},set(J){Object.defineProperty($,U,{value:J})},configurable:!0})}function HQ($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function I6($,U,z){Object.defineProperty($,U,{value:z,writable:!0,enumerable:!0,configurable:!0})}function S6(...$){let U={};for(let z of $){let X=Object.getOwnPropertyDescriptors(z);Object.assign(U,X)}return Object.defineProperties({},U)}function VQ($){return S6($._zod.def)}function LQ($,U){if(!U)return $;return U.reduce((z,X)=>z?.[X],$)}function BQ($){let U=Object.keys($),z=U.map((X)=>$[X]);return Promise.all(z).then((X)=>{let J={};for(let j=0;j<U.length;j++)J[U[j]]=X[j];return J})}function DQ($=10){let z="";for(let X=0;X<$;X++)z+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return z}function JU($){return JSON.stringify($)}var zU="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function n6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var GJ=G4(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function k6($){if(n6($)===!1)return!1;let U=$.constructor;if(U===void 0)return!0;let z=U.prototype;if(n6(z)===!1)return!1;if(Object.prototype.hasOwnProperty.call(z,"isPrototypeOf")===!1)return!1;return!0}function QJ($){if(k6($))return{...$};if(Array.isArray($))return[...$];return $}function KQ($){let U=0;for(let z in $)if(Object.prototype.hasOwnProperty.call($,z))U++;return U}var qQ=($)=>{let U=typeof $;switch(U){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${U}`)}},y4=new Set(["string","number","symbol"]),wJ=new Set(["string","number","bigint","boolean","symbol","undefined"]);function $6($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function E$($,U,z){let X=new $._zod.constr(U??$._zod.def);if(!U||z?.parent)X._zod.parent=$;return X}function A($){let U=$;if(!U)return{};if(typeof U==="string")return{error:()=>U};if(U?.message!==void 0){if(U?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");U.error=U.message}if(delete U.message,typeof U.error==="string")return{...U,error:()=>U.error};return U}function _Q($){let U;return new Proxy({},{get(z,X,J){return U??(U=$()),Reflect.get(U,X,J)},set(z,X,J,j){return U??(U=$()),Reflect.set(U,X,J,j)},has(z,X){return U??(U=$()),Reflect.has(U,X)},deleteProperty(z,X){return U??(U=$()),Reflect.deleteProperty(U,X)},ownKeys(z){return U??(U=$()),Reflect.ownKeys(U)},getOwnPropertyDescriptor(z,X){return U??(U=$()),Reflect.getOwnPropertyDescriptor(U,X)},defineProperty(z,X,J){return U??(U=$()),Reflect.defineProperty(U,X,J)}})}function P($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function HJ($){return Object.keys($).filter((U)=>{return $[U]._zod.optin==="optional"&&$[U]._zod.optout==="optional"})}var VJ={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},LJ={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function vQ($,U){let z=$._zod.def,X=S6($._zod.def,{get shape(){let J={};for(let j in U){if(!(j in z.shape))throw Error(`Unrecognized key: "${j}"`);if(!U[j])continue;J[j]=z.shape[j]}return I6(this,"shape",J),J},checks:[]});return E$($,X)}function FQ($,U){let z=$._zod.def,X=S6($._zod.def,{get shape(){let J={...$._zod.def.shape};for(let j in U){if(!(j in z.shape))throw Error(`Unrecognized key: "${j}"`);if(!U[j])continue;delete J[j]}return I6(this,"shape",J),J},checks:[]});return E$($,X)}function PQ($,U){if(!k6(U))throw Error("Invalid input to extend: expected a plain object");let z=$._zod.def.checks;if(z&&z.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let J=S6($._zod.def,{get shape(){let j={...$._zod.def.shape,...U};return I6(this,"shape",j),j},checks:[]});return E$($,J)}function AQ($,U){if(!k6(U))throw Error("Invalid input to safeExtend: expected a plain object");let z={...$._zod.def,get shape(){let X={...$._zod.def.shape,...U};return I6(this,"shape",X),X},checks:$._zod.def.checks};return E$($,z)}function EQ($,U){let z=S6($._zod.def,{get shape(){let X={...$._zod.def.shape,...U._zod.def.shape};return I6(this,"shape",X),X},get catchall(){return U._zod.def.catchall},checks:[]});return E$($,z)}function MQ($,U,z){let X=S6(U._zod.def,{get shape(){let J=U._zod.def.shape,j={...J};if(z)for(let Y in z){if(!(Y in J))throw Error(`Unrecognized key: "${Y}"`);if(!z[Y])continue;j[Y]=$?new $({type:"optional",innerType:J[Y]}):J[Y]}else for(let Y in J)j[Y]=$?new $({type:"optional",innerType:J[Y]}):J[Y];return I6(this,"shape",j),j},checks:[]});return E$(U,X)}function bQ($,U,z){let X=S6(U._zod.def,{get shape(){let J=U._zod.def.shape,j={...J};if(z)for(let Y in z){if(!(Y in j))throw Error(`Unrecognized key: "${Y}"`);if(!z[Y])continue;j[Y]=new $({type:"nonoptional",innerType:J[Y]})}else for(let Y in J)j[Y]=new $({type:"nonoptional",innerType:J[Y]});return I6(this,"shape",j),j},checks:[]});return E$(U,X)}function C6($,U=0){if($.aborted===!0)return!0;for(let z=U;z<$.issues.length;z++)if($.issues[z]?.continue!==!0)return!0;return!1}function x$($,U){return U.map((z)=>{var X;return(X=z).path??(X.path=[]),z.path.unshift($),z})}function x4($){return typeof $==="string"?$:$?.message}function f$($,U,z){let X={...$,path:$.path??[]};if(!$.message){let J=x4($.inst?._zod.def?.error?.($))??x4(U?.error?.($))??x4(z.customError?.($))??x4(z.localeError?.($))??"Invalid input";X.message=J}if(delete X.inst,delete X.continue,!U?.reportInput)delete X.input;return X}function c4($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function m4($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function Q4(...$){let[U,z,X]=$;if(typeof U==="string")return{message:U,code:"custom",input:z,inst:X};return{...U}}function RQ($){return Object.entries($).filter(([U,z])=>{return Number.isNaN(Number.parseInt(U,10))}).map((U)=>U[1])}function q9($){let U=atob($),z=new Uint8Array(U.length);for(let X=0;X<U.length;X++)z[X]=U.charCodeAt(X);return z}function _9($){let U="";for(let z=0;z<$.length;z++)U+=String.fromCharCode($[z]);return btoa(U)}function IQ($){let U=$.replace(/-/g,"+").replace(/_/g,"/"),z="=".repeat((4-U.length%4)%4);return q9(U+z)}function SQ($){return _9($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function kQ($){let U=$.replace(/^0x/,"");if(U.length%2!==0)throw Error("Invalid hex string length");let z=new Uint8Array(U.length/2);for(let X=0;X<U.length;X+=2)z[X/2]=Number.parseInt(U.slice(X,X+2),16);return z}function CQ($){return Array.from($).map((U)=>U.toString(16).padStart(2,"0")).join("")}class v9{constructor(...$){}}var F9=($,U)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:U,enumerable:!1}),$.message=JSON.stringify(U,W4,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},u4=V("$ZodError",F9),R$=V("$ZodError",F9,{Parent:Error});function i4($,U=(z)=>z.message){let z={},X=[];for(let J of $.issues)if(J.path.length>0)z[J.path[0]]=z[J.path[0]]||[],z[J.path[0]].push(U(J));else X.push(U(J));return{formErrors:X,fieldErrors:z}}function l4($,U){let z=U||function(j){return j.message},X={_errors:[]},J=(j)=>{for(let Y of j.issues)if(Y.code==="invalid_union"&&Y.errors.length)Y.errors.map((N)=>J({issues:N}));else if(Y.code==="invalid_key")J({issues:Y.issues});else if(Y.code==="invalid_element")J({issues:Y.issues});else if(Y.path.length===0)X._errors.push(z(Y));else{let N=X,W=0;while(W<Y.path.length){let G=Y.path[W];if(W!==Y.path.length-1)N[G]=N[G]||{_errors:[]};else N[G]=N[G]||{_errors:[]},N[G]._errors.push(z(Y));N=N[G],W++}}};return J($),X}function BJ($,U){let z=U||function(j){return j.message},X={errors:[]},J=(j,Y=[])=>{var N,W;for(let G of j.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((Q)=>J({issues:Q},G.path));else if(G.code==="invalid_key")J({issues:G.issues},G.path);else if(G.code==="invalid_element")J({issues:G.issues},G.path);else{let Q=[...Y,...G.path];if(Q.length===0){X.errors.push(z(G));continue}let L=X,H=0;while(H<Q.length){let w=Q[H],B=H===Q.length-1;if(typeof w==="string")L.properties??(L.properties={}),(N=L.properties)[w]??(N[w]={errors:[]}),L=L.properties[w];else L.items??(L.items=[]),(W=L.items)[w]??(W[w]={errors:[]}),L=L.items[w];if(B)L.errors.push(z(G));H++}}};return J($),X}function P9($){let U=[],z=$.map((X)=>typeof X==="object"?X.key:X);for(let X of z)if(typeof X==="number")U.push(`[${X}]`);else if(typeof X==="symbol")U.push(`[${JSON.stringify(String(X))}]`);else if(/[^\w$]/.test(X))U.push(`[${JSON.stringify(X)}]`);else{if(U.length)U.push(".");U.push(X)}return U.join("")}function DJ($){let U=[],z=[...$.issues].sort((X,J)=>(X.path??[]).length-(J.path??[]).length);for(let X of z)if(U.push(`✖ ${X.message}`),X.path?.length)U.push(` → at ${P9(X.path)}`);return U.join(`
103
- `)}var w4=($)=>(U,z,X,J)=>{let j=X?Object.assign(X,{async:!1}):{async:!1},Y=U._zod.run({value:z,issues:[]},j);if(Y instanceof Promise)throw new e$;if(Y.issues.length){let N=new(J?.Err??$)(Y.issues.map((W)=>f$(W,j,H$())));throw zU(N,J?.callee),N}return Y.value},XU=w4(R$),H4=($)=>async(U,z,X,J)=>{let j=X?Object.assign(X,{async:!0}):{async:!0},Y=U._zod.run({value:z,issues:[]},j);if(Y instanceof Promise)Y=await Y;if(Y.issues.length){let N=new(J?.Err??$)(Y.issues.map((W)=>f$(W,j,H$())));throw zU(N,J?.callee),N}return Y.value},jU=H4(R$),V4=($)=>(U,z,X)=>{let J=X?{...X,async:!1}:{async:!1},j=U._zod.run({value:z,issues:[]},J);if(j instanceof Promise)throw new e$;return j.issues.length?{success:!1,error:new($??u4)(j.issues.map((Y)=>f$(Y,J,H$())))}:{success:!0,data:j.value}},KJ=V4(R$),L4=($)=>async(U,z,X)=>{let J=X?Object.assign(X,{async:!0}):{async:!0},j=U._zod.run({value:z,issues:[]},J);if(j instanceof Promise)j=await j;return j.issues.length?{success:!1,error:new $(j.issues.map((Y)=>f$(Y,J,H$())))}:{success:!0,data:j.value}},qJ=L4(R$),YU=($)=>(U,z,X)=>{let J=X?Object.assign(X,{direction:"backward"}):{direction:"backward"};return w4($)(U,z,J)},TQ=YU(R$),NU=($)=>(U,z,X)=>{return w4($)(U,z,X)},gQ=NU(R$),OU=($)=>async(U,z,X)=>{let J=X?Object.assign(X,{direction:"backward"}):{direction:"backward"};return H4($)(U,z,J)},xQ=OU(R$),WU=($)=>async(U,z,X)=>{return H4($)(U,z,X)},fQ=WU(R$),GU=($)=>(U,z,X)=>{let J=X?Object.assign(X,{direction:"backward"}):{direction:"backward"};return V4($)(U,z,J)},hQ=GU(R$),QU=($)=>(U,z,X)=>{return V4($)(U,z,X)},yQ=QU(R$),wU=($)=>async(U,z,X)=>{let J=X?Object.assign(X,{direction:"backward"}):{direction:"backward"};return L4($)(U,z,J)},cQ=wU(R$),HU=($)=>async(U,z,X)=>{return L4($)(U,z,X)},mQ=HU(R$);var i$={};w6(i$,{xid:()=>PJ,uuid7:()=>nQ,uuid6:()=>lQ,uuid4:()=>iQ,uuid:()=>r6,uppercase:()=>dJ,unicodeEmail:()=>A9,undefined:()=>rJ,ulid:()=>FJ,time:()=>hJ,string:()=>cJ,sha512_hex:()=>Gw,sha512_base64url:()=>ww,sha512_base64:()=>Qw,sha384_hex:()=>Nw,sha384_base64url:()=>Ww,sha384_base64:()=>Ow,sha256_hex:()=>Xw,sha256_base64url:()=>Yw,sha256_base64:()=>jw,sha1_hex:()=>Uw,sha1_base64url:()=>zw,sha1_base64:()=>Jw,rfc5322Email:()=>pQ,number:()=>iJ,null:()=>nJ,nanoid:()=>EJ,md5_hex:()=>sQ,md5_base64url:()=>$w,md5_base64:()=>eQ,lowercase:()=>pJ,ksuid:()=>AJ,ipv6:()=>kJ,ipv4:()=>SJ,integer:()=>uJ,idnEmail:()=>dQ,html5Email:()=>rQ,hostname:()=>gJ,hex:()=>aQ,guid:()=>bJ,extendedDuration:()=>uQ,emoji:()=>IJ,email:()=>RJ,e164:()=>xJ,duration:()=>MJ,domain:()=>tQ,datetime:()=>yJ,date:()=>fJ,cuid2:()=>vJ,cuid:()=>_J,cidrv6:()=>ZJ,cidrv4:()=>CJ,browserEmail:()=>oQ,boolean:()=>lJ,bigint:()=>mJ,base64url:()=>VU,base64:()=>TJ});var _J=/^[cC][^\s-]{8,}$/,vJ=/^[0-9a-z]+$/,FJ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,PJ=/^[0-9a-vA-V]{20}$/,AJ=/^[A-Za-z0-9]{27}$/,EJ=/^[a-zA-Z0-9_-]{21}$/,MJ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,uQ=/^[-+]?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)?)??$/,bJ=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,r6=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},iQ=r6(4),lQ=r6(6),nQ=r6(7),RJ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,rQ=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,pQ=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,A9=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,dQ=A9,oQ=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;function IJ(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var SJ=/^(?:(?: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])$/,kJ=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,CJ=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ZJ=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,TJ=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,VU=/^[A-Za-z0-9_-]*$/,gJ=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,tQ=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,xJ=/^\+(?:[0-9]){6,14}[0-9]$/,E9="(?:(?:\\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])))",fJ=new RegExp(`^${E9}$`);function M9($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function hJ($){return new RegExp(`^${M9($)}$`)}function yJ($){let U=M9({precision:$.precision}),z=["Z"];if($.local)z.push("");if($.offset)z.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let X=`${U}(?:${z.join("|")})`;return new RegExp(`^${E9}T(?:${X})$`)}var cJ=($)=>{let U=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${U}$`)},mJ=/^-?\d+n?$/,uJ=/^-?\d+$/,iJ=/^-?\d+(?:\.\d+)?/,lJ=/^(?:true|false)$/i,nJ=/^null$/i;var rJ=/^undefined$/i;var pJ=/^[^A-Z]*$/,dJ=/^[^a-z]*$/,aQ=/^[0-9a-fA-F]*$/;function n4($,U){return new RegExp(`^[A-Za-z0-9+/]{${$}}${U}$`)}function r4($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var sQ=/^[0-9a-fA-F]{32}$/,eQ=n4(22,"=="),$w=r4(22),Uw=/^[0-9a-fA-F]{40}$/,Jw=n4(27,"="),zw=r4(27),Xw=/^[0-9a-fA-F]{64}$/,jw=n4(43,"="),Yw=r4(43),Nw=/^[0-9a-fA-F]{96}$/,Ow=n4(64,""),Ww=r4(64),Gw=/^[0-9a-fA-F]{128}$/,Qw=n4(86,"=="),ww=r4(86);var j$=V("$ZodCheck",($,U)=>{var z;$._zod??($._zod={}),$._zod.def=U,(z=$._zod).onattach??(z.onattach=[])}),R9={number:"number",bigint:"bigint",object:"date"},LU=V("$ZodCheckLessThan",($,U)=>{j$.init($,U);let z=R9[typeof U.value];$._zod.onattach.push((X)=>{let J=X._zod.bag,j=(U.inclusive?J.maximum:J.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(U.value<j)if(U.inclusive)J.maximum=U.value;else J.exclusiveMaximum=U.value}),$._zod.check=(X)=>{if(U.inclusive?X.value<=U.value:X.value<U.value)return;X.issues.push({origin:z,code:"too_big",maximum:U.value,input:X.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),BU=V("$ZodCheckGreaterThan",($,U)=>{j$.init($,U);let z=R9[typeof U.value];$._zod.onattach.push((X)=>{let J=X._zod.bag,j=(U.inclusive?J.minimum:J.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(U.value>j)if(U.inclusive)J.minimum=U.value;else J.exclusiveMinimum=U.value}),$._zod.check=(X)=>{if(U.inclusive?X.value>=U.value:X.value>U.value)return;X.issues.push({origin:z,code:"too_small",minimum:U.value,input:X.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),oJ=V("$ZodCheckMultipleOf",($,U)=>{j$.init($,U),$._zod.onattach.push((z)=>{var X;(X=z._zod.bag).multipleOf??(X.multipleOf=U.value)}),$._zod.check=(z)=>{if(typeof z.value!==typeof U.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof z.value==="bigint"?z.value%U.value===BigInt(0):WJ(z.value,U.value)===0)return;z.issues.push({origin:typeof z.value,code:"not_multiple_of",divisor:U.value,input:z.value,inst:$,continue:!U.abort})}}),tJ=V("$ZodCheckNumberFormat",($,U)=>{j$.init($,U),U.format=U.format||"float64";let z=U.format?.includes("int"),X=z?"int":"number",[J,j]=VJ[U.format];$._zod.onattach.push((Y)=>{let N=Y._zod.bag;if(N.format=U.format,N.minimum=J,N.maximum=j,z)N.pattern=uJ}),$._zod.check=(Y)=>{let N=Y.value;if(z){if(!Number.isInteger(N)){Y.issues.push({expected:X,format:U.format,code:"invalid_type",continue:!1,input:N,inst:$});return}if(!Number.isSafeInteger(N)){if(N>0)Y.issues.push({input:N,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!U.abort});else Y.issues.push({input:N,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!U.abort});return}}if(N<J)Y.issues.push({origin:"number",input:N,code:"too_small",minimum:J,inclusive:!0,inst:$,continue:!U.abort});if(N>j)Y.issues.push({origin:"number",input:N,code:"too_big",maximum:j,inst:$})}}),aJ=V("$ZodCheckBigIntFormat",($,U)=>{j$.init($,U);let[z,X]=LJ[U.format];$._zod.onattach.push((J)=>{let j=J._zod.bag;j.format=U.format,j.minimum=z,j.maximum=X}),$._zod.check=(J)=>{let j=J.value;if(j<z)J.issues.push({origin:"bigint",input:j,code:"too_small",minimum:z,inclusive:!0,inst:$,continue:!U.abort});if(j>X)J.issues.push({origin:"bigint",input:j,code:"too_big",maximum:X,inst:$})}}),sJ=V("$ZodCheckMaxSize",($,U)=>{var z;j$.init($,U),(z=$._zod.def).when??(z.when=(X)=>{let J=X.value;return!R6(J)&&J.size!==void 0}),$._zod.onattach.push((X)=>{let J=X._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<J)X._zod.bag.maximum=U.maximum}),$._zod.check=(X)=>{let J=X.value;if(J.size<=U.maximum)return;X.issues.push({origin:c4(J),code:"too_big",maximum:U.maximum,inclusive:!0,input:J,inst:$,continue:!U.abort})}}),eJ=V("$ZodCheckMinSize",($,U)=>{var z;j$.init($,U),(z=$._zod.def).when??(z.when=(X)=>{let J=X.value;return!R6(J)&&J.size!==void 0}),$._zod.onattach.push((X)=>{let J=X._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>J)X._zod.bag.minimum=U.minimum}),$._zod.check=(X)=>{let J=X.value;if(J.size>=U.minimum)return;X.issues.push({origin:c4(J),code:"too_small",minimum:U.minimum,inclusive:!0,input:J,inst:$,continue:!U.abort})}}),$z=V("$ZodCheckSizeEquals",($,U)=>{var z;j$.init($,U),(z=$._zod.def).when??(z.when=(X)=>{let J=X.value;return!R6(J)&&J.size!==void 0}),$._zod.onattach.push((X)=>{let J=X._zod.bag;J.minimum=U.size,J.maximum=U.size,J.size=U.size}),$._zod.check=(X)=>{let J=X.value,j=J.size;if(j===U.size)return;let Y=j>U.size;X.issues.push({origin:c4(J),...Y?{code:"too_big",maximum:U.size}:{code:"too_small",minimum:U.size},inclusive:!0,exact:!0,input:X.value,inst:$,continue:!U.abort})}}),Uz=V("$ZodCheckMaxLength",($,U)=>{var z;j$.init($,U),(z=$._zod.def).when??(z.when=(X)=>{let J=X.value;return!R6(J)&&J.length!==void 0}),$._zod.onattach.push((X)=>{let J=X._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<J)X._zod.bag.maximum=U.maximum}),$._zod.check=(X)=>{let J=X.value;if(J.length<=U.maximum)return;let Y=m4(J);X.issues.push({origin:Y,code:"too_big",maximum:U.maximum,inclusive:!0,input:J,inst:$,continue:!U.abort})}}),Jz=V("$ZodCheckMinLength",($,U)=>{var z;j$.init($,U),(z=$._zod.def).when??(z.when=(X)=>{let J=X.value;return!R6(J)&&J.length!==void 0}),$._zod.onattach.push((X)=>{let J=X._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>J)X._zod.bag.minimum=U.minimum}),$._zod.check=(X)=>{let J=X.value;if(J.length>=U.minimum)return;let Y=m4(J);X.issues.push({origin:Y,code:"too_small",minimum:U.minimum,inclusive:!0,input:J,inst:$,continue:!U.abort})}}),zz=V("$ZodCheckLengthEquals",($,U)=>{var z;j$.init($,U),(z=$._zod.def).when??(z.when=(X)=>{let J=X.value;return!R6(J)&&J.length!==void 0}),$._zod.onattach.push((X)=>{let J=X._zod.bag;J.minimum=U.length,J.maximum=U.length,J.length=U.length}),$._zod.check=(X)=>{let J=X.value,j=J.length;if(j===U.length)return;let Y=m4(J),N=j>U.length;X.issues.push({origin:Y,...N?{code:"too_big",maximum:U.length}:{code:"too_small",minimum:U.length},inclusive:!0,exact:!0,input:X.value,inst:$,continue:!U.abort})}}),B4=V("$ZodCheckStringFormat",($,U)=>{var z,X;if(j$.init($,U),$._zod.onattach.push((J)=>{let j=J._zod.bag;if(j.format=U.format,U.pattern)j.patterns??(j.patterns=new Set),j.patterns.add(U.pattern)}),U.pattern)(z=$._zod).check??(z.check=(J)=>{if(U.pattern.lastIndex=0,U.pattern.test(J.value))return;J.issues.push({origin:"string",code:"invalid_format",format:U.format,input:J.value,...U.pattern?{pattern:U.pattern.toString()}:{},inst:$,continue:!U.abort})});else(X=$._zod).check??(X.check=()=>{})}),Xz=V("$ZodCheckRegex",($,U)=>{B4.init($,U),$._zod.check=(z)=>{if(U.pattern.lastIndex=0,U.pattern.test(z.value))return;z.issues.push({origin:"string",code:"invalid_format",format:"regex",input:z.value,pattern:U.pattern.toString(),inst:$,continue:!U.abort})}}),jz=V("$ZodCheckLowerCase",($,U)=>{U.pattern??(U.pattern=pJ),B4.init($,U)}),Yz=V("$ZodCheckUpperCase",($,U)=>{U.pattern??(U.pattern=dJ),B4.init($,U)}),Nz=V("$ZodCheckIncludes",($,U)=>{j$.init($,U);let z=$6(U.includes),X=new RegExp(typeof U.position==="number"?`^.{${U.position}}${z}`:z);U.pattern=X,$._zod.onattach.push((J)=>{let j=J._zod.bag;j.patterns??(j.patterns=new Set),j.patterns.add(X)}),$._zod.check=(J)=>{if(J.value.includes(U.includes,U.position))return;J.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:U.includes,input:J.value,inst:$,continue:!U.abort})}}),Oz=V("$ZodCheckStartsWith",($,U)=>{j$.init($,U);let z=new RegExp(`^${$6(U.prefix)}.*`);U.pattern??(U.pattern=z),$._zod.onattach.push((X)=>{let J=X._zod.bag;J.patterns??(J.patterns=new Set),J.patterns.add(z)}),$._zod.check=(X)=>{if(X.value.startsWith(U.prefix))return;X.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:U.prefix,input:X.value,inst:$,continue:!U.abort})}}),Wz=V("$ZodCheckEndsWith",($,U)=>{j$.init($,U);let z=new RegExp(`.*${$6(U.suffix)}$`);U.pattern??(U.pattern=z),$._zod.onattach.push((X)=>{let J=X._zod.bag;J.patterns??(J.patterns=new Set),J.patterns.add(z)}),$._zod.check=(X)=>{if(X.value.endsWith(U.suffix))return;X.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:U.suffix,input:X.value,inst:$,continue:!U.abort})}});function b9($,U,z){if($.issues.length)U.issues.push(...x$(z,$.issues))}var Gz=V("$ZodCheckProperty",($,U)=>{j$.init($,U),$._zod.check=(z)=>{let X=U.schema._zod.run({value:z.value[U.property],issues:[]},{});if(X instanceof Promise)return X.then((J)=>b9(J,z,U.property));b9(X,z,U.property);return}}),Qz=V("$ZodCheckMimeType",($,U)=>{j$.init($,U);let z=new Set(U.mime);$._zod.onattach.push((X)=>{X._zod.bag.mime=U.mime}),$._zod.check=(X)=>{if(z.has(X.value.type))return;X.issues.push({code:"invalid_value",values:U.mime,input:X.value.type,inst:$,continue:!U.abort})}}),wz=V("$ZodCheckOverwrite",($,U)=>{j$.init($,U),$._zod.check=(z)=>{z.value=U.tx(z.value)}});class DU{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let z=$.split(`
104
- `).filter((j)=>j),X=Math.min(...z.map((j)=>j.length-j.trimStart().length)),J=z.map((j)=>j.slice(X)).map((j)=>" ".repeat(this.indent*2)+j);for(let j of J)this.content.push(j)}compile(){let $=Function,U=this?.args,X=[...(this?.content??[""]).map((J)=>` ${J}`)];return new $(...U,X.join(`
105
- `))}}var Hz={major:4,minor:1,patch:8};var c=V("$ZodType",($,U)=>{var z;$??($={}),$._zod.def=U,$._zod.bag=$._zod.bag||{},$._zod.version=Hz;let X=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))X.unshift($);for(let J of X)for(let j of J._zod.onattach)j($);if(X.length===0)(z=$._zod).deferred??(z.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let J=(Y,N,W)=>{let G=C6(Y),Q;for(let L of N){if(L._zod.def.when){if(!L._zod.def.when(Y))continue}else if(G)continue;let H=Y.issues.length,w=L._zod.check(Y);if(w instanceof Promise&&W?.async===!1)throw new e$;if(Q||w instanceof Promise)Q=(Q??Promise.resolve()).then(async()=>{if(await w,Y.issues.length===H)return;if(!G)G=C6(Y,H)});else{if(Y.issues.length===H)continue;if(!G)G=C6(Y,H)}}if(Q)return Q.then(()=>{return Y});return Y},j=(Y,N,W)=>{if(C6(Y))return Y.aborted=!0,Y;let G=J(N,X,W);if(G instanceof Promise){if(W.async===!1)throw new e$;return G.then((Q)=>$._zod.parse(Q,W))}return $._zod.parse(G,W)};$._zod.run=(Y,N)=>{if(N.skipChecks)return $._zod.parse(Y,N);if(N.direction==="backward"){let G=$._zod.parse({value:Y.value,issues:[]},{...N,skipChecks:!0});if(G instanceof Promise)return G.then((Q)=>{return j(Q,Y,N)});return j(G,Y,N)}let W=$._zod.parse(Y,N);if(W instanceof Promise){if(N.async===!1)throw new e$;return W.then((G)=>J(G,X,N))}return J(W,X,N)}}$["~standard"]={validate:(J)=>{try{let j=KJ($,J);return j.success?{value:j.data}:{issues:j.error?.issues}}catch(j){return qJ($,J).then((Y)=>Y.success?{value:Y.data}:{issues:Y.error?.issues})}},vendor:"zod",version:1}}),p6=V("$ZodString",($,U)=>{c.init($,U),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??cJ($._zod.bag),$._zod.parse=(z,X)=>{if(U.coerce)try{z.value=String(z.value)}catch(J){}if(typeof z.value==="string")return z;return z.issues.push({expected:"string",code:"invalid_type",input:z.value,inst:$}),z}}),J$=V("$ZodStringFormat",($,U)=>{B4.init($,U),p6.init($,U)}),Lz=V("$ZodGUID",($,U)=>{U.pattern??(U.pattern=bJ),J$.init($,U)}),Bz=V("$ZodUUID",($,U)=>{if(U.version){let X={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[U.version];if(X===void 0)throw Error(`Invalid UUID version: "${U.version}"`);U.pattern??(U.pattern=r6(X))}else U.pattern??(U.pattern=r6());J$.init($,U)}),Dz=V("$ZodEmail",($,U)=>{U.pattern??(U.pattern=RJ),J$.init($,U)}),Kz=V("$ZodURL",($,U)=>{J$.init($,U),$._zod.check=(z)=>{try{let X=z.value.trim(),J=new URL(X);if(U.hostname){if(U.hostname.lastIndex=0,!U.hostname.test(J.hostname))z.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:gJ.source,input:z.value,inst:$,continue:!U.abort})}if(U.protocol){if(U.protocol.lastIndex=0,!U.protocol.test(J.protocol.endsWith(":")?J.protocol.slice(0,-1):J.protocol))z.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:U.protocol.source,input:z.value,inst:$,continue:!U.abort})}if(U.normalize)z.value=J.href;else z.value=X;return}catch(X){z.issues.push({code:"invalid_format",format:"url",input:z.value,inst:$,continue:!U.abort})}}}),qz=V("$ZodEmoji",($,U)=>{U.pattern??(U.pattern=IJ()),J$.init($,U)}),_z=V("$ZodNanoID",($,U)=>{U.pattern??(U.pattern=EJ),J$.init($,U)}),vz=V("$ZodCUID",($,U)=>{U.pattern??(U.pattern=_J),J$.init($,U)}),Fz=V("$ZodCUID2",($,U)=>{U.pattern??(U.pattern=vJ),J$.init($,U)}),Pz=V("$ZodULID",($,U)=>{U.pattern??(U.pattern=FJ),J$.init($,U)}),Az=V("$ZodXID",($,U)=>{U.pattern??(U.pattern=PJ),J$.init($,U)}),Ez=V("$ZodKSUID",($,U)=>{U.pattern??(U.pattern=AJ),J$.init($,U)}),Mz=V("$ZodISODateTime",($,U)=>{U.pattern??(U.pattern=yJ(U)),J$.init($,U)}),bz=V("$ZodISODate",($,U)=>{U.pattern??(U.pattern=fJ),J$.init($,U)}),Rz=V("$ZodISOTime",($,U)=>{U.pattern??(U.pattern=hJ(U)),J$.init($,U)}),Iz=V("$ZodISODuration",($,U)=>{U.pattern??(U.pattern=MJ),J$.init($,U)}),Sz=V("$ZodIPv4",($,U)=>{U.pattern??(U.pattern=SJ),J$.init($,U),$._zod.onattach.push((z)=>{let X=z._zod.bag;X.format="ipv4"})}),kz=V("$ZodIPv6",($,U)=>{U.pattern??(U.pattern=kJ),J$.init($,U),$._zod.onattach.push((z)=>{let X=z._zod.bag;X.format="ipv6"}),$._zod.check=(z)=>{try{new URL(`http://[${z.value}]`)}catch{z.issues.push({code:"invalid_format",format:"ipv6",input:z.value,inst:$,continue:!U.abort})}}}),Cz=V("$ZodCIDRv4",($,U)=>{U.pattern??(U.pattern=CJ),J$.init($,U)}),Zz=V("$ZodCIDRv6",($,U)=>{U.pattern??(U.pattern=ZJ),J$.init($,U),$._zod.check=(z)=>{let X=z.value.split("/");try{if(X.length!==2)throw Error();let[J,j]=X;if(!j)throw Error();let Y=Number(j);if(`${Y}`!==j)throw Error();if(Y<0||Y>128)throw Error();new URL(`http://[${J}]`)}catch{z.issues.push({code:"invalid_format",format:"cidrv6",input:z.value,inst:$,continue:!U.abort})}}});function Tz($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var gz=V("$ZodBase64",($,U)=>{U.pattern??(U.pattern=TJ),J$.init($,U),$._zod.onattach.push((z)=>{z._zod.bag.contentEncoding="base64"}),$._zod.check=(z)=>{if(Tz(z.value))return;z.issues.push({code:"invalid_format",format:"base64",input:z.value,inst:$,continue:!U.abort})}});function c9($){if(!VU.test($))return!1;let U=$.replace(/[-_]/g,(X)=>X==="-"?"+":"/"),z=U.padEnd(Math.ceil(U.length/4)*4,"=");return Tz(z)}var xz=V("$ZodBase64URL",($,U)=>{U.pattern??(U.pattern=VU),J$.init($,U),$._zod.onattach.push((z)=>{z._zod.bag.contentEncoding="base64url"}),$._zod.check=(z)=>{if(c9(z.value))return;z.issues.push({code:"invalid_format",format:"base64url",input:z.value,inst:$,continue:!U.abort})}}),fz=V("$ZodE164",($,U)=>{U.pattern??(U.pattern=xJ),J$.init($,U)});function m9($,U=null){try{let z=$.split(".");if(z.length!==3)return!1;let[X]=z;if(!X)return!1;let J=JSON.parse(atob(X));if("typ"in J&&J?.typ!=="JWT")return!1;if(!J.alg)return!1;if(U&&(!("alg"in J)||J.alg!==U))return!1;return!0}catch{return!1}}var hz=V("$ZodJWT",($,U)=>{J$.init($,U),$._zod.check=(z)=>{if(m9(z.value,U.alg))return;z.issues.push({code:"invalid_format",format:"jwt",input:z.value,inst:$,continue:!U.abort})}}),yz=V("$ZodCustomStringFormat",($,U)=>{J$.init($,U),$._zod.check=(z)=>{if(U.fn(z.value))return;z.issues.push({code:"invalid_format",format:U.format,input:z.value,inst:$,continue:!U.abort})}}),PU=V("$ZodNumber",($,U)=>{c.init($,U),$._zod.pattern=$._zod.bag.pattern??iJ,$._zod.parse=(z,X)=>{if(U.coerce)try{z.value=Number(z.value)}catch(Y){}let J=z.value;if(typeof J==="number"&&!Number.isNaN(J)&&Number.isFinite(J))return z;let j=typeof J==="number"?Number.isNaN(J)?"NaN":!Number.isFinite(J)?"Infinity":void 0:void 0;return z.issues.push({expected:"number",code:"invalid_type",input:J,inst:$,...j?{received:j}:{}}),z}}),cz=V("$ZodNumber",($,U)=>{tJ.init($,U),PU.init($,U)}),p4=V("$ZodBoolean",($,U)=>{c.init($,U),$._zod.pattern=lJ,$._zod.parse=(z,X)=>{if(U.coerce)try{z.value=Boolean(z.value)}catch(j){}let J=z.value;if(typeof J==="boolean")return z;return z.issues.push({expected:"boolean",code:"invalid_type",input:J,inst:$}),z}}),AU=V("$ZodBigInt",($,U)=>{c.init($,U),$._zod.pattern=mJ,$._zod.parse=(z,X)=>{if(U.coerce)try{z.value=BigInt(z.value)}catch(J){}if(typeof z.value==="bigint")return z;return z.issues.push({expected:"bigint",code:"invalid_type",input:z.value,inst:$}),z}}),mz=V("$ZodBigInt",($,U)=>{aJ.init($,U),AU.init($,U)}),uz=V("$ZodSymbol",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{let J=z.value;if(typeof J==="symbol")return z;return z.issues.push({expected:"symbol",code:"invalid_type",input:J,inst:$}),z}}),iz=V("$ZodUndefined",($,U)=>{c.init($,U),$._zod.pattern=rJ,$._zod.values=new Set([void 0]),$._zod.optin="optional",$._zod.optout="optional",$._zod.parse=(z,X)=>{let J=z.value;if(typeof J>"u")return z;return z.issues.push({expected:"undefined",code:"invalid_type",input:J,inst:$}),z}}),lz=V("$ZodNull",($,U)=>{c.init($,U),$._zod.pattern=nJ,$._zod.values=new Set([null]),$._zod.parse=(z,X)=>{let J=z.value;if(J===null)return z;return z.issues.push({expected:"null",code:"invalid_type",input:J,inst:$}),z}}),nz=V("$ZodAny",($,U)=>{c.init($,U),$._zod.parse=(z)=>z}),rz=V("$ZodUnknown",($,U)=>{c.init($,U),$._zod.parse=(z)=>z}),pz=V("$ZodNever",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{return z.issues.push({expected:"never",code:"invalid_type",input:z.value,inst:$}),z}}),dz=V("$ZodVoid",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{let J=z.value;if(typeof J>"u")return z;return z.issues.push({expected:"void",code:"invalid_type",input:J,inst:$}),z}}),oz=V("$ZodDate",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{if(U.coerce)try{z.value=new Date(z.value)}catch(N){}let J=z.value,j=J instanceof Date;if(j&&!Number.isNaN(J.getTime()))return z;return z.issues.push({expected:"date",code:"invalid_type",input:J,...j?{received:"Invalid Date"}:{},inst:$}),z}});function S9($,U,z){if($.issues.length)U.issues.push(...x$(z,$.issues));U.value[z]=$.value}var tz=V("$ZodArray",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{let J=z.value;if(!Array.isArray(J))return z.issues.push({expected:"array",code:"invalid_type",input:J,inst:$}),z;z.value=Array(J.length);let j=[];for(let Y=0;Y<J.length;Y++){let N=J[Y],W=U.element._zod.run({value:N,issues:[]},X);if(W instanceof Promise)j.push(W.then((G)=>S9(G,z,Y)));else S9(W,z,Y)}if(j.length)return Promise.all(j).then(()=>z);return z}});function FU($,U,z,X){if($.issues.length)U.issues.push(...x$(z,$.issues));if($.value===void 0){if(z in X)U.value[z]=void 0}else U.value[z]=$.value}function u9($){let U=Object.keys($.shape);for(let X of U)if(!$.shape?.[X]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${X}": expected a Zod schema`);let z=HJ($.shape);return{...$,keys:U,keySet:new Set(U),numKeys:U.length,optionalKeys:new Set(z)}}function i9($,U,z,X,J,j){let Y=[],N=J.keySet,W=J.catchall._zod,G=W.def.type;for(let Q of Object.keys(U)){if(N.has(Q))continue;if(G==="never"){Y.push(Q);continue}let L=W.run({value:U[Q],issues:[]},X);if(L instanceof Promise)$.push(L.then((H)=>FU(H,z,Q,U)));else FU(L,z,Q,U)}if(Y.length)z.issues.push({code:"unrecognized_keys",keys:Y,input:U,inst:j});if(!$.length)return z;return Promise.all($).then(()=>{return z})}var l9=V("$ZodObject",($,U)=>{c.init($,U);let z=G4(()=>u9(U));a($._zod,"propValues",()=>{let Y=U.shape,N={};for(let W in Y){let G=Y[W]._zod;if(G.values){N[W]??(N[W]=new Set);for(let Q of G.values)N[W].add(Q)}}return N});let X=n6,J=U.catchall,j;$._zod.parse=(Y,N)=>{j??(j=z.value);let W=Y.value;if(!X(W))return Y.issues.push({expected:"object",code:"invalid_type",input:W,inst:$}),Y;Y.value={};let G=[],Q=j.shape;for(let L of j.keys){let w=Q[L]._zod.run({value:W[L],issues:[]},N);if(w instanceof Promise)G.push(w.then((B)=>FU(B,Y,L,W)));else FU(w,Y,L,W)}if(!J)return G.length?Promise.all(G).then(()=>Y):Y;return i9(G,W,Y,N,z.value,$)}}),az=V("$ZodObjectJIT",($,U)=>{l9.init($,U);let z=$._zod.parse,X=G4(()=>u9(U)),J=(H)=>{let w=new DU(["shape","payload","ctx"]),B=X.value,q=(y)=>{let Z=JU(y);return`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`};w.write("const input = payload.value;");let T=Object.create(null),b=0;for(let y of B.keys)T[y]=`key_${b++}`;w.write("const newResult = {};");for(let y of B.keys){let Z=T[y],N$=JU(y);w.write(`const ${Z} = ${q(y)};`),w.write(`
106
- if (${Z}.issues.length) {
107
- payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
114
+ `}}function A5(Y){return Y.type==="response.output_item.done"&&_(Y.item)&&Y.item.type==="web_search_call"&&typeof Y.item.id==="string"}function R5(Y){return _(Y)&&Y.type==="function_call"&&Y.name==="web_search"&&typeof Y.call_id==="string"&&Y.call_id.startsWith(EY)}function T5(Y,X){return _(Y)&&Y.type==="function_call_output"&&typeof Y.call_id==="string"&&typeof Y.output==="string"&&Y.call_id.startsWith(EY)&&X.has(Y.call_id)}function C5(Y){return _(Y)&&Y.type==="item_reference"&&typeof Y.id==="string"&&Y.id.startsWith(EY)}function _8(Y,X,J){let Q=_5(X),$=_(Q?.action)?Q.action:I5(J?.arguments);return{type:"web_search_call",status:"completed",...$?{action:$}:{}}}function _5(Y){if(_(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return _(X)?X:void 0}catch{return}}function I5(Y){if(_(Y))return Y;if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return _(X)?X:void 0}catch{return}}import{readFile as S5}from"node:fs/promises";import{homedir as k5}from"node:os";import{join as kX}from"node:path";var b5="https://models.dev/api.json",x5="OPENCODE_OPENAI_AUTH_MODELS_CACHE",v5="OPENCODE_MODELS_PATH",h5="OPENCODE_DISABLE_MODELS_FETCH",g5=1e4,y5=300000;function s0(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)?Y:null}function bX(Y){if(Y===void 0)return 0;return typeof Y==="number"&&Number.isFinite(Y)&&Y>=0?Y:null}function S8(Y){let{input:X,output:J}=Y;if(typeof X!=="number"||!Number.isFinite(X)||X<0)return null;if(typeof J!=="number"||!Number.isFinite(J)||J<0)return null;let Q=bX(Y.cache_read),$=bX(Y.cache_write);if(Q===null||$===null)return null;return{input:X,output:J,cache:{read:Q,write:$}}}function f5(Y){let X=s0(Y);if(!X)return null;let J=S8(X);if(!J)return null;let Q=J;if(Array.isArray(X.tiers)){let W=[];for(let K of X.tiers){let H=s0(K);if(!H)continue;let U=s0(H.tier),N=U?.size;if(U?.type!=="context")continue;if(typeof N!=="number"||!Number.isFinite(N)||N<=0)continue;let O=S8(H);if(!O)continue;W.push({...O,tier:{type:"context",size:N}})}if(W.length>0)Q.tiers=W}let $=s0(X.context_over_200k),G=$?S8($):null;if(G)Q.experimentalOver200K=G;return Q}function xX(Y){let X=s0(Y),J=s0(X?.openai),Q=s0(J?.models);if(!Q)return null;let $={};for(let[G,W]of Object.entries(Q)){let K=s0(W),H=f5(K?.cost);if(H)$[G]=H}return Object.keys($).length>0?$:null}function m5(){let Y=process.env[x5]?.trim();if(Y)return Y;let X=process.env[v5]?.trim();if(X)return X;let J=process.env.XDG_CACHE_HOME?.trim()||(process.platform==="win32"?process.env.LOCALAPPDATA?.trim():void 0)||kX(k5(),".cache");return kX(J,"opencode","models.json")}function c5(){let Y=process.env[h5]?.toLowerCase();return Y==="true"||Y==="1"}async function u5(){try{let Y=xX(JSON.parse(await S5(m5(),"utf8")));if(Y)return Y}catch{}if(c5())return null;try{let Y=await fetch(b5,{signal:AbortSignal.timeout(g5)});if(!Y.ok)return null;return xX(await Y.json())}catch{return null}}var R1;function vX(){let Y=Date.now();if(R1&&R1.expiresAt>Y)return R1.promise;let X={expiresAt:Y+y5,promise:u5()};return R1=X,X.promise.then((J)=>{if(J===null&&R1===X)R1=void 0}),X.promise}function T1(Y){return typeof Y==="object"&&Y!==null}function p5(Y){if(Array.isArray(Y))return Y;if(T1(Y)&&Array.isArray(Y.data))return Y.data;return[]}function l5(Y){if(!T1(Y)||!T1(Y.info))return;return typeof Y.info.role==="string"?Y.info.role:void 0}function hX(Y){if(!T1(Y)||!T1(Y.info))return null;let X=Y.info,J=T1(X.model)?X.model:void 0,Q=typeof X.agent==="string"?X.agent:void 0,$=typeof J?.providerID==="string"?J.providerID:typeof X.providerID==="string"?X.providerID:void 0,G=typeof J?.modelID==="string"?J.modelID:typeof X.modelID==="string"?X.modelID:void 0,W=typeof J?.variant==="string"?J.variant:typeof X.variant==="string"?X.variant:void 0;if(!Q&&(!$||!G)&&!W)return null;let K={};if(Q)K.agent=Q;if($&&G)K.model={providerID:$,modelID:G};if(W)K.variant=W;return K}function gX(Y,X){return{agent:Y.agent??X.agent,model:Y.model??X.model,variant:Y.variant??X.variant}}function yX(Y){return Boolean(Y.agent&&Y.model&&Y.variant)}async function fX(Y,X){if(!Y||!X)return null;let J=Y;if(typeof J.session?.messages!=="function")return null;let Q=[];try{Q=p5(await Promise.resolve(J.session.messages({path:{id:X},query:{limit:100}})))}catch{return null}if(Q.length===0)return null;let $={};for(let G=Q.length-1;G>=0;G--){if(l5(Q[G])!=="assistant")continue;let W=hX(Q[G]);if(!W)continue;if($=gX($,W),yX($))return $}for(let G=Q.length-1;G>=0;G--){let W=hX(Q[G]);if(!W)continue;if($=gX($,W),yX($))return $}if(!$.agent&&!$.model&&!$.variant)return null;return $}var a0=[],d5=1,k8=0,mX=new Map;function b8(Y,X){if(a0.push({id:d5++,type:"open-dialog",payload:Y,sessionId:X}),a0.length>100)a0=a0.slice(a0.length-100)}function cX(Y=0,X){let J=Date.now();if(k8=J,X!==void 0)mX.set(X,J);let Q=($)=>X===void 0||$.sessionId===void 0||$.sessionId===X;if(Y>0)a0=a0.filter(($)=>{if($.id>Y)return!0;if(X===void 0)return!1;return $.sessionId!==X});return a0.filter(($)=>$.id>Y&&Q($))}function uX(Y){let X=Date.now();if(Y!==void 0){let J=mX.get(Y)??0;return J>0&&X-J<3000}return k8>0&&X-k8<3000}import{randomBytes as i5,timingSafeEqual as n5}from"node:crypto";import{unlink as o5}from"node:fs/promises";import{createServer as r5}from"node:http";import{join as s5}from"node:path";var pX=L0("rpc");function a5(Y){return new Promise((X,J)=>{let Q=[],$=0;Y.on("data",(G)=>{if($+=G.length,$>1e6){Y.destroy(),J(Error("body too large"));return}Q.push(G)}),Y.on("end",()=>X(Buffer.concat(Q).toString("utf8"))),Y.on("error",J)})}function t5(Y,X){if(!Y?.startsWith("Bearer "))return!1;let J=Buffer.from(Y.slice(7)),Q=Buffer.from(X);return J.length===Q.length&&n5(J,Q)}async function iX(Y){let X=i5(32).toString("hex"),J=Y.timeoutMs??2000,Q=r5((W,K)=>{W.setTimeout(J,()=>{W.socket.destroy()}),$(W,K)});Q.requestTimeout=J,Q.headersTimeout=J;async function $(W,K){let H=(U,N)=>{if(K.headersSent||K.writableEnded||K.destroyed)return;K.writeHead(U,{"content-type":"application/json"}),K.end(JSON.stringify(N))};try{let U=W.url??"";if(W.method==="GET"&&U==="/health")return H(200,{ok:!0});if(W.method!=="POST"||!U.startsWith("/rpc/"))return H(404,{error:"not found"});if(!t5(W.headers.authorization,X))return H(401,{error:"unauthorized"});let N=U.slice(5),O=await a5(W),B=JSON.parse(O||"{}");if(N==="pending-notifications"){let L=Y.drain(Number(B.lastReceivedId??0),typeof B.sessionId==="string"?B.sessionId:void 0);return H(200,{messages:L})}if(N==="apply"){let L=await Y.apply(B);return H(200,L)}return H(404,{error:"unknown method"})}catch(U){H(500,{error:U instanceof Error?U.message:String(U)})}}let G=await new Promise((W,K)=>{Q.on("error",K),Q.listen(0,"127.0.0.1",()=>{let H=Q.address();if(H&&typeof H==="object")W(H.port);else K(Error("no port"))})});if(Q.unref(),Y.sweepRoot)try{await dX(Y.sweepRoot,Y.dir)}catch(W){pX.warn("rpc state sweep failed",{pid:process.pid,error:W instanceof Error?W.message:String(W)})}try{await lX(Y.dir,{port:G,token:X,pid:process.pid},{secureDir:Y.secureDir}),pX.debug("rpc server pid",{pid:process.pid,rpcPort:G})}catch(W){throw await new Promise((K)=>Q.close(()=>K())),W}return{port:G,token:X,async stop(){await new Promise((W)=>Q.close(()=>W())),await o5(s5(Y.dir,`port-${process.pid}.json`)).catch(()=>{})}}}function u0(Y){return JSON.stringify(x8(Y))??"undefined"}function x8(Y){if(Array.isArray(Y))return Y.map(x8);if(!_(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((X)=>[X,x8(Y[X])]))}function N1(){let Y=crypto.getRandomValues(new Uint8Array(16)),X=Date.now();Y[0]=X/1099511627776&255,Y[1]=X/4294967296&255,Y[2]=X/16777216&255,Y[3]=X/65536&255,Y[4]=X/256&255,Y[5]=X&255,Y[6]=(Y[6]??0)&15|112,Y[8]=(Y[8]??0)&63|128;let J=Array.from(Y,(Q)=>Q.toString(16).padStart(2,"0")).join("");return`${J.slice(0,8)}-${J.slice(8,12)}-${J.slice(12,16)}-${J.slice(16,20)}-${J.slice(20)}`}var $1={};g8($1,{withoutInternalHeaders:()=>xG,sanitizeHttpFallbackBody:()=>F8,orderCodexBody:()=>GY,hasWebSocketResponsesLiteMetadata:()=>O8,createWebSocketFetch:()=>GN,applyTurnId:()=>SG,TITLE_HEADER:()=>k9,QUOTA_ACCOUNT_HEADER:()=>aY,OpenAIWebSocketPool:()=>$1,CODEX_BODY_KEY_ORDER:()=>_G});import{createHash as YN}from"node:crypto";var EJ="vercel.ai.error",e5=Symbol.for(EJ),nX,oX,f=class Y extends(oX=Error,nX=e5,oX){constructor({name:X,message:J,cause:Q}){super(J);this[nX]=!0,this.name=X,this.cause=Q}static isInstance(X){return Y.hasMarker(X,EJ)}static hasMarker(X,J){let Q=Symbol.for(J);return X!=null&&typeof X==="object"&&Q in X&&typeof X[Q]==="boolean"&&X[Q]===!0}},MJ="AI_APICallError",AJ=`vercel.ai.error.${MJ}`,Y2=Symbol.for(AJ),rX,sX,m1=class extends(sX=f,rX=Y2,sX){constructor({message:Y,url:X,requestBodyValues:J,statusCode:Q,responseHeaders:$,responseBody:G,cause:W,isRetryable:K=Q!=null&&(Q===408||Q===409||Q===429||Q>=500),data:H}){super({name:MJ,message:Y,cause:W});this[rX]=!0,this.url=X,this.requestBodyValues=J,this.statusCode=Q,this.responseHeaders=$,this.responseBody=G,this.isRetryable=K,this.data=H}static isInstance(Y){return f.hasMarker(Y,AJ)}},RJ="AI_EmptyResponseBodyError",TJ=`vercel.ai.error.${RJ}`,X2=Symbol.for(TJ),aX,tX,J2=class extends(tX=f,aX=X2,tX){constructor({message:Y="Empty response body"}={}){super({name:RJ,message:Y});this[aX]=!0}static isInstance(Y){return f.hasMarker(Y,TJ)}};function v8(Y){if(Y==null)return"unknown error";if(typeof Y==="string")return Y;if(Y instanceof Error)return Y.toString();return JSON.stringify(Y)}var CJ="AI_InvalidArgumentError",_J=`vercel.ai.error.${CJ}`,Q2=Symbol.for(_J),eX,YJ,IJ=class extends(YJ=f,eX=Q2,YJ){constructor({message:Y,cause:X,argument:J}){super({name:CJ,message:Y,cause:X});this[eX]=!0,this.argument=J}static isInstance(Y){return f.hasMarker(Y,_J)}},SJ="AI_InvalidPromptError",kJ=`vercel.ai.error.${SJ}`,$2=Symbol.for(kJ),XJ,JJ,G2=class extends(JJ=f,XJ=$2,JJ){constructor({prompt:Y,message:X,cause:J}){super({name:SJ,message:`Invalid prompt: ${X}`,cause:J});this[XJ]=!0,this.prompt=Y}static isInstance(Y){return f.hasMarker(Y,kJ)}},bJ="AI_InvalidResponseDataError",xJ=`vercel.ai.error.${bJ}`,W2=Symbol.for(xJ),QJ,$J,z2=class extends($J=f,QJ=W2,$J){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:bJ,message:X});this[QJ]=!0,this.data=Y}static isInstance(Y){return f.hasMarker(Y,xJ)}},vJ="AI_JSONParseError",hJ=`vercel.ai.error.${vJ}`,K2=Symbol.for(hJ),GJ,WJ,MY=class extends(WJ=f,GJ=K2,WJ){constructor({text:Y,cause:X}){super({name:vJ,message:`JSON parsing failed: Text: ${Y}.
115
+ Error message: ${v8(X)}`,cause:X});this[GJ]=!0,this.text=Y}static isInstance(Y){return f.hasMarker(Y,hJ)}},gJ="AI_LoadAPIKeyError",yJ=`vercel.ai.error.${gJ}`,U2=Symbol.for(yJ),zJ,KJ,H2=class extends(KJ=f,zJ=U2,KJ){constructor({message:Y}){super({name:gJ,message:Y});this[zJ]=!0}static isInstance(Y){return f.hasMarker(Y,yJ)}},fJ="AI_LoadSettingError",mJ=`vercel.ai.error.${fJ}`,L2=Symbol.for(mJ),UJ,HJ,N2=class extends(HJ=f,UJ=L2,HJ){constructor({message:Y}){super({name:fJ,message:Y});this[UJ]=!0}static isInstance(Y){return f.hasMarker(Y,mJ)}},cJ="AI_NoContentGeneratedError",uJ=`vercel.ai.error.${cJ}`,V2=Symbol.for(uJ),LJ,NJ,B2=class extends(NJ=f,LJ=V2,NJ){constructor({message:Y="No content generated."}={}){super({name:cJ,message:Y});this[LJ]=!0}static isInstance(Y){return f.hasMarker(Y,uJ)}},pJ="AI_NoSuchModelError",lJ=`vercel.ai.error.${pJ}`,Z2=Symbol.for(lJ),VJ,BJ,O2=class extends(BJ=f,VJ=Z2,BJ){constructor({errorName:Y=pJ,modelId:X,modelType:J,message:Q=`No such ${J}: ${X}`}){super({name:Y,message:Q});this[VJ]=!0,this.modelId=X,this.modelType=J}static isInstance(Y){return f.hasMarker(Y,lJ)}},dJ="AI_NoSuchProviderReferenceError",iJ=`vercel.ai.error.${dJ}`,F2=Symbol.for(iJ),ZJ,OJ,q2=class extends(OJ=f,ZJ=F2,OJ){constructor({provider:Y,reference:X,message:J=`No provider reference found for provider '${Y}'. Available providers: ${Object.keys(X).join(", ")}`}){super({name:dJ,message:J});this[ZJ]=!0,this.provider=Y,this.reference=X}static isInstance(Y){return f.hasMarker(Y,iJ)}},nJ="AI_TooManyEmbeddingValuesForCallError",oJ=`vercel.ai.error.${nJ}`,j2=Symbol.for(oJ),FJ,qJ,D2=class extends(qJ=f,FJ=j2,qJ){constructor(Y){super({name:nJ,message:`Too many values for a single embedding call. The ${Y.provider} model "${Y.modelId}" can only embed up to ${Y.maxEmbeddingsPerCall} values per call, but ${Y.values.length} values were provided.`});this[FJ]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return f.hasMarker(Y,oJ)}},rJ="AI_TypeValidationError",sJ=`vercel.ai.error.${rJ}`,P2=Symbol.for(sJ),jJ,DJ,v0=class Y extends(DJ=f,jJ=P2,DJ){constructor({value:X,cause:J,context:Q}){let $="Type validation failed";if(Q==null?void 0:Q.field)$+=` for ${Q.field}`;if((Q==null?void 0:Q.entityName)||(Q==null?void 0:Q.entityId)){$+=" (";let G=[];if(Q.entityName)G.push(Q.entityName);if(Q.entityId)G.push(`id: "${Q.entityId}"`);$+=G.join(", "),$+=")"}super({name:rJ,message:`${$}: Value: ${JSON.stringify(X)}.
116
+ Error message: ${v8(J)}`,cause:J});this[jJ]=!0,this.value=X,this.context=Q}static isInstance(X){return f.hasMarker(X,sJ)}static wrap({value:X,cause:J,context:Q}){var $,G,W;if(Y.isInstance(J)&&J.value===X&&(($=J.context)==null?void 0:$.field)===(Q==null?void 0:Q.field)&&((G=J.context)==null?void 0:G.entityName)===(Q==null?void 0:Q.entityName)&&((W=J.context)==null?void 0:W.entityId)===(Q==null?void 0:Q.entityId))return J;return new Y({value:X,cause:J,context:Q})}},aJ="AI_UnsupportedFunctionalityError",tJ=`vercel.ai.error.${aJ}`,w2=Symbol.for(tJ),PJ,wJ,E2=class extends(wJ=f,PJ=w2,wJ){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:aJ,message:X});this[PJ]=!0,this.functionality=Y}static isInstance(Y){return f.hasMarker(Y,tJ)}};var OB=Object.freeze({status:"aborted"});function q(Y,X,J){function Q(K,H){var U;Object.defineProperty(K,"_zod",{value:K._zod??{},enumerable:!1}),(U=K._zod).traits??(U.traits=new Set),K._zod.traits.add(Y),X(K,H);for(let N in W.prototype)if(!(N in K))Object.defineProperty(K,N,{value:W.prototype[N].bind(K)});K._zod.constr=W,K._zod.def=H}let $=J?.Parent??Object;class G extends ${}Object.defineProperty(G,"name",{value:Y});function W(K){var H;let U=J?.Parent?new G:this;Q(U,K),(H=U._zod).deferred??(H.deferred=[]);for(let N of U._zod.deferred)N();return U}return Object.defineProperty(W,"init",{value:Q}),Object.defineProperty(W,Symbol.hasInstance,{value:(K)=>{if(J?.Parent&&K instanceof J.Parent)return!0;return K?._zod?.traits?.has(Y)}}),Object.defineProperty(W,"name",{value:Y}),W}var FB=Symbol("zod_brand");class p0 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class c1 extends Error{constructor(Y){super(`Encountered unidirectional transform during encode: ${Y}`);this.name="ZodEncodeError"}}var AY={};function h0(Y){if(Y)Object.assign(AY,Y);return AY}var c={};g8(c,{unwrapMessage:()=>u1,uint8ArrayToHex:()=>r2,uint8ArrayToBase64url:()=>n2,uint8ArrayToBase64:()=>W6,stringifyPrimitive:()=>J6,shallowClone:()=>Y6,safeExtend:()=>c2,required:()=>l2,randomString:()=>x2,propertyKeyTypes:()=>m8,promiseAllObject:()=>b2,primitiveTypes:()=>X6,prefixIssues:()=>d0,pick:()=>y2,partial:()=>p2,optionalKeys:()=>c8,omit:()=>f2,objectClone:()=>I2,numKeys:()=>v2,nullish:()=>l1,normalizeParams:()=>v,mergeDefs:()=>e0,merge:()=>u2,jsonStringifyReplacer:()=>C1,joinValues:()=>_2,issue:()=>I1,isPlainObject:()=>Y1,isObject:()=>V1,hexToUint8Array:()=>o2,getSizableOrigin:()=>$6,getParsedType:()=>h2,getLengthableOrigin:()=>i1,getEnumValues:()=>p1,getElementAtPath:()=>k2,floatSafeRemainder:()=>y8,finalizeIssue:()=>_0,extend:()=>m2,escapeRegex:()=>l0,esc:()=>RY,defineLazy:()=>p,createTransparentProxy:()=>g2,cloneDef:()=>S2,clone:()=>C0,cleanRegex:()=>d1,cleanEnum:()=>d2,captureStackTrace:()=>TY,cached:()=>_1,base64urlToUint8Array:()=>i2,base64ToUint8Array:()=>G6,assignProp:()=>t0,assertNotEqual:()=>A2,assertNever:()=>T2,assertIs:()=>R2,assertEqual:()=>M2,assert:()=>C2,allowsEval:()=>f8,aborted:()=>X1,NUMBER_FORMAT_RANGES:()=>u8,Class:()=>z6,BIGINT_FORMAT_RANGES:()=>Q6});function M2(Y){return Y}function A2(Y){return Y}function R2(Y){}function T2(Y){throw Error()}function C2(Y){}function p1(Y){let X=Object.values(Y).filter((Q)=>typeof Q==="number");return Object.entries(Y).filter(([Q,$])=>X.indexOf(+Q)===-1).map(([Q,$])=>$)}function _2(Y,X="|"){return Y.map((J)=>J6(J)).join(X)}function C1(Y,X){if(typeof X==="bigint")return X.toString();return X}function _1(Y){return{get value(){{let J=Y();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function l1(Y){return Y===null||Y===void 0}function d1(Y){let X=Y.startsWith("^")?1:0,J=Y.endsWith("$")?Y.length-1:Y.length;return Y.slice(X,J)}function y8(Y,X){let J=(Y.toString().split(".")[1]||"").length,Q=X.toString(),$=(Q.split(".")[1]||"").length;if($===0&&/\d?e-\d?/.test(Q)){let H=Q.match(/\d?e-(\d?)/);if(H?.[1])$=Number.parseInt(H[1])}let G=J>$?J:$,W=Number.parseInt(Y.toFixed(G).replace(".","")),K=Number.parseInt(X.toFixed(G).replace(".",""));return W%K/10**G}var eJ=Symbol("evaluating");function p(Y,X,J){let Q=void 0;Object.defineProperty(Y,X,{get(){if(Q===eJ)return;if(Q===void 0)Q=eJ,Q=J();return Q},set($){Object.defineProperty(Y,X,{value:$})},configurable:!0})}function I2(Y){return Object.create(Object.getPrototypeOf(Y),Object.getOwnPropertyDescriptors(Y))}function t0(Y,X,J){Object.defineProperty(Y,X,{value:J,writable:!0,enumerable:!0,configurable:!0})}function e0(...Y){let X={};for(let J of Y){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(X,Q)}return Object.defineProperties({},X)}function S2(Y){return e0(Y._zod.def)}function k2(Y,X){if(!X)return Y;return X.reduce((J,Q)=>J?.[Q],Y)}function b2(Y){let X=Object.keys(Y),J=X.map((Q)=>Y[Q]);return Promise.all(J).then((Q)=>{let $={};for(let G=0;G<X.length;G++)$[X[G]]=Q[G];return $})}function x2(Y=10){let J="";for(let Q=0;Q<Y;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function RY(Y){return JSON.stringify(Y)}var TY="captureStackTrace"in Error?Error.captureStackTrace:(...Y)=>{};function V1(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}var f8=_1(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Y){return!1}});function Y1(Y){if(V1(Y)===!1)return!1;let X=Y.constructor;if(X===void 0)return!0;let J=X.prototype;if(V1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function Y6(Y){if(Y1(Y))return{...Y};if(Array.isArray(Y))return[...Y];return Y}function v2(Y){let X=0;for(let J in Y)if(Object.prototype.hasOwnProperty.call(Y,J))X++;return X}var h2=(Y)=>{let X=typeof Y;switch(X){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Y)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Y))return"array";if(Y===null)return"null";if(Y.then&&typeof Y.then==="function"&&Y.catch&&typeof Y.catch==="function")return"promise";if(typeof Map<"u"&&Y instanceof Map)return"map";if(typeof Set<"u"&&Y instanceof Set)return"set";if(typeof Date<"u"&&Y instanceof Date)return"date";if(typeof File<"u"&&Y instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${X}`)}},m8=new Set(["string","number","symbol"]),X6=new Set(["string","number","bigint","boolean","symbol","undefined"]);function l0(Y){return Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function C0(Y,X,J){let Q=new Y._zod.constr(X??Y._zod.def);if(!X||J?.parent)Q._zod.parent=Y;return Q}function v(Y){let X=Y;if(!X)return{};if(typeof X==="string")return{error:()=>X};if(X?.message!==void 0){if(X?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");X.error=X.message}if(delete X.message,typeof X.error==="string")return{...X,error:()=>X.error};return X}function g2(Y){let X;return new Proxy({},{get(J,Q,$){return X??(X=Y()),Reflect.get(X,Q,$)},set(J,Q,$,G){return X??(X=Y()),Reflect.set(X,Q,$,G)},has(J,Q){return X??(X=Y()),Reflect.has(X,Q)},deleteProperty(J,Q){return X??(X=Y()),Reflect.deleteProperty(X,Q)},ownKeys(J){return X??(X=Y()),Reflect.ownKeys(X)},getOwnPropertyDescriptor(J,Q){return X??(X=Y()),Reflect.getOwnPropertyDescriptor(X,Q)},defineProperty(J,Q,$){return X??(X=Y()),Reflect.defineProperty(X,Q,$)}})}function J6(Y){if(typeof Y==="bigint")return Y.toString()+"n";if(typeof Y==="string")return`"${Y}"`;return`${Y}`}function c8(Y){return Object.keys(Y).filter((X)=>{return Y[X]._zod.optin==="optional"&&Y[X]._zod.optout==="optional"})}var u8={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Q6={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function y2(Y,X){let J=Y._zod.def,Q=e0(Y._zod.def,{get shape(){let $={};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;$[G]=J.shape[G]}return t0(this,"shape",$),$},checks:[]});return C0(Y,Q)}function f2(Y,X){let J=Y._zod.def,Q=e0(Y._zod.def,{get shape(){let $={...Y._zod.def.shape};for(let G in X){if(!(G in J.shape))throw Error(`Unrecognized key: "${G}"`);if(!X[G])continue;delete $[G]}return t0(this,"shape",$),$},checks:[]});return C0(Y,Q)}function m2(Y,X){if(!Y1(X))throw Error("Invalid input to extend: expected a plain object");let J=Y._zod.def.checks;if(J&&J.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let $=e0(Y._zod.def,{get shape(){let G={...Y._zod.def.shape,...X};return t0(this,"shape",G),G},checks:[]});return C0(Y,$)}function c2(Y,X){if(!Y1(X))throw Error("Invalid input to safeExtend: expected a plain object");let J={...Y._zod.def,get shape(){let Q={...Y._zod.def.shape,...X};return t0(this,"shape",Q),Q},checks:Y._zod.def.checks};return C0(Y,J)}function u2(Y,X){let J=e0(Y._zod.def,{get shape(){let Q={...Y._zod.def.shape,...X._zod.def.shape};return t0(this,"shape",Q),Q},get catchall(){return X._zod.def.catchall},checks:[]});return C0(Y,J)}function p2(Y,X,J){let Q=e0(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in $))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W]}else for(let W in $)G[W]=Y?new Y({type:"optional",innerType:$[W]}):$[W];return t0(this,"shape",G),G},checks:[]});return C0(X,Q)}function l2(Y,X,J){let Q=e0(X._zod.def,{get shape(){let $=X._zod.def.shape,G={...$};if(J)for(let W in J){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!J[W])continue;G[W]=new Y({type:"nonoptional",innerType:$[W]})}else for(let W in $)G[W]=new Y({type:"nonoptional",innerType:$[W]});return t0(this,"shape",G),G},checks:[]});return C0(X,Q)}function X1(Y,X=0){if(Y.aborted===!0)return!0;for(let J=X;J<Y.issues.length;J++)if(Y.issues[J]?.continue!==!0)return!0;return!1}function d0(Y,X){return X.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift(Y),J})}function u1(Y){return typeof Y==="string"?Y:Y?.message}function _0(Y,X,J){let Q={...Y,path:Y.path??[]};if(!Y.message){let $=u1(Y.inst?._zod.def?.error?.(Y))??u1(X?.error?.(Y))??u1(J.customError?.(Y))??u1(J.localeError?.(Y))??"Invalid input";Q.message=$}if(delete Q.inst,delete Q.continue,!X?.reportInput)delete Q.input;return Q}function $6(Y){if(Y instanceof Set)return"set";if(Y instanceof Map)return"map";if(Y instanceof File)return"file";return"unknown"}function i1(Y){if(Array.isArray(Y))return"array";if(typeof Y==="string")return"string";return"unknown"}function I1(...Y){let[X,J,Q]=Y;if(typeof X==="string")return{message:X,code:"custom",input:J,inst:Q};return{...X}}function d2(Y){return Object.entries(Y).filter(([X,J])=>{return Number.isNaN(Number.parseInt(X,10))}).map((X)=>X[1])}function G6(Y){let X=atob(Y),J=new Uint8Array(X.length);for(let Q=0;Q<X.length;Q++)J[Q]=X.charCodeAt(Q);return J}function W6(Y){let X="";for(let J=0;J<Y.length;J++)X+=String.fromCharCode(Y[J]);return btoa(X)}function i2(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-X.length%4)%4);return G6(X+J)}function n2(Y){return W6(Y).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function o2(Y){let X=Y.replace(/^0x/,"");if(X.length%2!==0)throw Error("Invalid hex string length");let J=new Uint8Array(X.length/2);for(let Q=0;Q<X.length;Q+=2)J[Q/2]=Number.parseInt(X.slice(Q,Q+2),16);return J}function r2(Y){return Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}class z6{constructor(...Y){}}var K6=(Y,X)=>{Y.name="$ZodError",Object.defineProperty(Y,"_zod",{value:Y._zod,enumerable:!1}),Object.defineProperty(Y,"issues",{value:X,enumerable:!1}),Y.message=JSON.stringify(X,C1,2),Object.defineProperty(Y,"toString",{value:()=>Y.message,enumerable:!1})},CY=q("$ZodError",K6),p8=q("$ZodError",K6,{Parent:Error});function U6(Y,X=(J)=>J.message){let J={},Q=[];for(let $ of Y.issues)if($.path.length>0)J[$.path[0]]=J[$.path[0]]||[],J[$.path[0]].push(X($));else Q.push(X($));return{formErrors:Q,fieldErrors:J}}function H6(Y,X){let J=X||function(G){return G.message},Q={_errors:[]},$=(G)=>{for(let W of G.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((K)=>$({issues:K}));else if(W.code==="invalid_key")$({issues:W.issues});else if(W.code==="invalid_element")$({issues:W.issues});else if(W.path.length===0)Q._errors.push(J(W));else{let K=Q,H=0;while(H<W.path.length){let U=W.path[H];if(H!==W.path.length-1)K[U]=K[U]||{_errors:[]};else K[U]=K[U]||{_errors:[]},K[U]._errors.push(J(W));K=K[U],H++}}};return $(Y),Q}var _Y=(Y)=>(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!1}):{async:!1},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)throw new p0;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((H)=>_0(H,G,h0())));throw TY(K,$?.callee),K}return W.value};var IY=(Y)=>async(X,J,Q,$)=>{let G=Q?Object.assign(Q,{async:!0}):{async:!0},W=X._zod.run({value:J,issues:[]},G);if(W instanceof Promise)W=await W;if(W.issues.length){let K=new($?.Err??Y)(W.issues.map((H)=>_0(H,G,h0())));throw TY(K,$?.callee),K}return W.value};var n1=(Y)=>(X,J,Q)=>{let $=Q?{...Q,async:!1}:{async:!1},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)throw new p0;return G.issues.length?{success:!1,error:new(Y??CY)(G.issues.map((W)=>_0(W,$,h0())))}:{success:!0,data:G.value}},L6=n1(p8),o1=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{async:!0}):{async:!0},G=X._zod.run({value:J,issues:[]},$);if(G instanceof Promise)G=await G;return G.issues.length?{success:!1,error:new Y(G.issues.map((W)=>_0(W,$,h0())))}:{success:!0,data:G.value}},N6=o1(p8),V6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return _Y(Y)(X,J,$)};var B6=(Y)=>(X,J,Q)=>{return _Y(Y)(X,J,Q)};var Z6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return IY(Y)(X,J,$)};var O6=(Y)=>async(X,J,Q)=>{return IY(Y)(X,J,Q)};var F6=(Y)=>(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return n1(Y)(X,J,$)};var q6=(Y)=>(X,J,Q)=>{return n1(Y)(X,J,Q)};var j6=(Y)=>async(X,J,Q)=>{let $=Q?Object.assign(Q,{direction:"backward"}):{direction:"backward"};return o1(Y)(X,J,$)};var D6=(Y)=>async(X,J,Q)=>{return o1(Y)(X,J,Q)};var P6=/^[cC][^\s-]{8,}$/,w6=/^[0-9a-z]+$/,E6=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,M6=/^[0-9a-vA-V]{20}$/,A6=/^[A-Za-z0-9]{27}$/,R6=/^[a-zA-Z0-9_-]{21}$/,T6=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var C6=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,l8=(Y)=>{if(!Y)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${Y}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var _6=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function I6(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var S6=/^(?:(?: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])$/,k6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,b6=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,x6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,v6=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,d8=/^[A-Za-z0-9_-]*$/,h6=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var g6=/^\+(?:[0-9]){6,14}[0-9]$/,y6="(?:(?:\\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])))",f6=new RegExp(`^${y6}$`);function m6(Y){return typeof Y.precision==="number"?Y.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":Y.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${Y.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function c6(Y){return new RegExp(`^${m6(Y)}$`)}function u6(Y){let X=m6({precision:Y.precision}),J=["Z"];if(Y.local)J.push("");if(Y.offset)J.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${X}(?:${J.join("|")})`;return new RegExp(`^${y6}T(?:${Q})$`)}var p6=(Y)=>{let X=Y?`[\\s\\S]{${Y?.minimum??0},${Y?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${X}$`)};var l6=/^-?\d+$/,d6=/^-?\d+(?:\.\d+)?/,i6=/^(?:true|false)$/i,n6=/^null$/i;var o6=/^[^A-Z]*$/,r6=/^[^a-z]*$/;var N0=q("$ZodCheck",(Y,X)=>{var J;Y._zod??(Y._zod={}),Y._zod.def=X,(J=Y._zod).onattach??(J.onattach=[])}),s6={number:"number",bigint:"bigint",object:"date"},i8=q("$ZodCheckLessThan",(Y,X)=>{N0.init(Y,X);let J=s6[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.maximum:$.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(X.value<G)if(X.inclusive)$.maximum=X.value;else $.exclusiveMaximum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value<=X.value:Q.value<X.value)return;Q.issues.push({origin:J,code:"too_big",maximum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),n8=q("$ZodCheckGreaterThan",(Y,X)=>{N0.init(Y,X);let J=s6[typeof X.value];Y._zod.onattach.push((Q)=>{let $=Q._zod.bag,G=(X.inclusive?$.minimum:$.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(X.value>G)if(X.inclusive)$.minimum=X.value;else $.exclusiveMinimum=X.value}),Y._zod.check=(Q)=>{if(X.inclusive?Q.value>=X.value:Q.value>X.value)return;Q.issues.push({origin:J,code:"too_small",minimum:X.value,input:Q.value,inclusive:X.inclusive,inst:Y,continue:!X.abort})}}),a6=q("$ZodCheckMultipleOf",(Y,X)=>{N0.init(Y,X),Y._zod.onattach.push((J)=>{var Q;(Q=J._zod.bag).multipleOf??(Q.multipleOf=X.value)}),Y._zod.check=(J)=>{if(typeof J.value!==typeof X.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%X.value===BigInt(0):y8(J.value,X.value)===0)return;J.issues.push({origin:typeof J.value,code:"not_multiple_of",divisor:X.value,input:J.value,inst:Y,continue:!X.abort})}}),t6=q("$ZodCheckNumberFormat",(Y,X)=>{N0.init(Y,X),X.format=X.format||"float64";let J=X.format?.includes("int"),Q=J?"int":"number",[$,G]=u8[X.format];Y._zod.onattach.push((W)=>{let K=W._zod.bag;if(K.format=X.format,K.minimum=$,K.maximum=G,J)K.pattern=l6}),Y._zod.check=(W)=>{let K=W.value;if(J){if(!Number.isInteger(K)){W.issues.push({expected:Q,format:X.format,code:"invalid_type",continue:!1,input:K,inst:Y});return}if(!Number.isSafeInteger(K)){if(K>0)W.issues.push({input:K,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});else W.issues.push({input:K,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Y,origin:Q,continue:!X.abort});return}}if(K<$)W.issues.push({origin:"number",input:K,code:"too_small",minimum:$,inclusive:!0,inst:Y,continue:!X.abort});if(K>G)W.issues.push({origin:"number",input:K,code:"too_big",maximum:G,inst:Y})}});var e6=q("$ZodCheckMaxLength",(Y,X)=>{var J;N0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!l1($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(X.maximum<$)Q._zod.bag.maximum=X.maximum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length<=X.maximum)return;let W=i1($);Q.issues.push({origin:W,code:"too_big",maximum:X.maximum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),YQ=q("$ZodCheckMinLength",(Y,X)=>{var J;N0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!l1($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(X.minimum>$)Q._zod.bag.minimum=X.minimum}),Y._zod.check=(Q)=>{let $=Q.value;if($.length>=X.minimum)return;let W=i1($);Q.issues.push({origin:W,code:"too_small",minimum:X.minimum,inclusive:!0,input:$,inst:Y,continue:!X.abort})}}),XQ=q("$ZodCheckLengthEquals",(Y,X)=>{var J;N0.init(Y,X),(J=Y._zod.def).when??(J.when=(Q)=>{let $=Q.value;return!l1($)&&$.length!==void 0}),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.minimum=X.length,$.maximum=X.length,$.length=X.length}),Y._zod.check=(Q)=>{let $=Q.value,G=$.length;if(G===X.length)return;let W=i1($),K=G>X.length;Q.issues.push({origin:W,...K?{code:"too_big",maximum:X.length}:{code:"too_small",minimum:X.length},inclusive:!0,exact:!0,input:Q.value,inst:Y,continue:!X.abort})}}),r1=q("$ZodCheckStringFormat",(Y,X)=>{var J,Q;if(N0.init(Y,X),Y._zod.onattach.push(($)=>{let G=$._zod.bag;if(G.format=X.format,X.pattern)G.patterns??(G.patterns=new Set),G.patterns.add(X.pattern)}),X.pattern)(J=Y._zod).check??(J.check=($)=>{if(X.pattern.lastIndex=0,X.pattern.test($.value))return;$.issues.push({origin:"string",code:"invalid_format",format:X.format,input:$.value,...X.pattern?{pattern:X.pattern.toString()}:{},inst:Y,continue:!X.abort})});else(Q=Y._zod).check??(Q.check=()=>{})}),JQ=q("$ZodCheckRegex",(Y,X)=>{r1.init(Y,X),Y._zod.check=(J)=>{if(X.pattern.lastIndex=0,X.pattern.test(J.value))return;J.issues.push({origin:"string",code:"invalid_format",format:"regex",input:J.value,pattern:X.pattern.toString(),inst:Y,continue:!X.abort})}}),QQ=q("$ZodCheckLowerCase",(Y,X)=>{X.pattern??(X.pattern=o6),r1.init(Y,X)}),$Q=q("$ZodCheckUpperCase",(Y,X)=>{X.pattern??(X.pattern=r6),r1.init(Y,X)}),GQ=q("$ZodCheckIncludes",(Y,X)=>{N0.init(Y,X);let J=l0(X.includes),Q=new RegExp(typeof X.position==="number"?`^.{${X.position}}${J}`:J);X.pattern=Q,Y._zod.onattach.push(($)=>{let G=$._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),Y._zod.check=($)=>{if($.value.includes(X.includes,X.position))return;$.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:X.includes,input:$.value,inst:Y,continue:!X.abort})}}),WQ=q("$ZodCheckStartsWith",(Y,X)=>{N0.init(Y,X);let J=new RegExp(`^${l0(X.prefix)}.*`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.startsWith(X.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:X.prefix,input:Q.value,inst:Y,continue:!X.abort})}}),zQ=q("$ZodCheckEndsWith",(Y,X)=>{N0.init(Y,X);let J=new RegExp(`.*${l0(X.suffix)}$`);X.pattern??(X.pattern=J),Y._zod.onattach.push((Q)=>{let $=Q._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(J)}),Y._zod.check=(Q)=>{if(Q.value.endsWith(X.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:X.suffix,input:Q.value,inst:Y,continue:!X.abort})}});var KQ=q("$ZodCheckOverwrite",(Y,X)=>{N0.init(Y,X),Y._zod.check=(J)=>{J.value=X.tx(J.value)}});class o8{constructor(Y=[]){if(this.content=[],this.indent=0,this)this.args=Y}indented(Y){this.indent+=1,Y(this),this.indent-=1}write(Y){if(typeof Y==="function"){Y(this,{execution:"sync"}),Y(this,{execution:"async"});return}let J=Y.split(`
117
+ `).filter((G)=>G),Q=Math.min(...J.map((G)=>G.length-G.trimStart().length)),$=J.map((G)=>G.slice(Q)).map((G)=>" ".repeat(this.indent*2)+G);for(let G of $)this.content.push(G)}compile(){let Y=Function,X=this?.args,Q=[...(this?.content??[""]).map(($)=>` ${$}`)];return new Y(...X,Q.join(`
118
+ `))}}var HQ={major:4,minor:1,patch:8};var i=q("$ZodType",(Y,X)=>{var J;Y??(Y={}),Y._zod.def=X,Y._zod.bag=Y._zod.bag||{},Y._zod.version=HQ;let Q=[...Y._zod.def.checks??[]];if(Y._zod.traits.has("$ZodCheck"))Q.unshift(Y);for(let $ of Q)for(let G of $._zod.onattach)G(Y);if(Q.length===0)(J=Y._zod).deferred??(J.deferred=[]),Y._zod.deferred?.push(()=>{Y._zod.run=Y._zod.parse});else{let $=(W,K,H)=>{let U=X1(W),N;for(let O of K){if(O._zod.def.when){if(!O._zod.def.when(W))continue}else if(U)continue;let B=W.issues.length,L=O._zod.check(W);if(L instanceof Promise&&H?.async===!1)throw new p0;if(N||L instanceof Promise)N=(N??Promise.resolve()).then(async()=>{if(await L,W.issues.length===B)return;if(!U)U=X1(W,B)});else{if(W.issues.length===B)continue;if(!U)U=X1(W,B)}}if(N)return N.then(()=>{return W});return W},G=(W,K,H)=>{if(X1(W))return W.aborted=!0,W;let U=$(K,Q,H);if(U instanceof Promise){if(H.async===!1)throw new p0;return U.then((N)=>Y._zod.parse(N,H))}return Y._zod.parse(U,H)};Y._zod.run=(W,K)=>{if(K.skipChecks)return Y._zod.parse(W,K);if(K.direction==="backward"){let U=Y._zod.parse({value:W.value,issues:[]},{...K,skipChecks:!0});if(U instanceof Promise)return U.then((N)=>{return G(N,W,K)});return G(U,W,K)}let H=Y._zod.parse(W,K);if(H instanceof Promise){if(K.async===!1)throw new p0;return H.then((U)=>$(U,Q,K))}return $(H,Q,K)}}Y["~standard"]={validate:($)=>{try{let G=L6(Y,$);return G.success?{value:G.data}:{issues:G.error?.issues}}catch(G){return N6(Y,$).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}}),xY=q("$ZodString",(Y,X)=>{i.init(Y,X),Y._zod.pattern=[...Y?._zod.bag?.patterns??[]].pop()??p6(Y._zod.bag),Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=String(J.value)}catch($){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:Y}),J}}),n=q("$ZodStringFormat",(Y,X)=>{r1.init(Y,X),xY.init(Y,X)}),jQ=q("$ZodGUID",(Y,X)=>{X.pattern??(X.pattern=C6),n.init(Y,X)}),DQ=q("$ZodUUID",(Y,X)=>{if(X.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[X.version];if(Q===void 0)throw Error(`Invalid UUID version: "${X.version}"`);X.pattern??(X.pattern=l8(Q))}else X.pattern??(X.pattern=l8());n.init(Y,X)}),PQ=q("$ZodEmail",(Y,X)=>{X.pattern??(X.pattern=_6),n.init(Y,X)}),wQ=q("$ZodURL",(Y,X)=>{n.init(Y,X),Y._zod.check=(J)=>{try{let Q=J.value.trim(),$=new URL(Q);if(X.hostname){if(X.hostname.lastIndex=0,!X.hostname.test($.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:h6.source,input:J.value,inst:Y,continue:!X.abort})}if(X.protocol){if(X.protocol.lastIndex=0,!X.protocol.test($.protocol.endsWith(":")?$.protocol.slice(0,-1):$.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:X.protocol.source,input:J.value,inst:Y,continue:!X.abort})}if(X.normalize)J.value=$.href;else J.value=Q;return}catch(Q){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:Y,continue:!X.abort})}}}),EQ=q("$ZodEmoji",(Y,X)=>{X.pattern??(X.pattern=I6()),n.init(Y,X)}),MQ=q("$ZodNanoID",(Y,X)=>{X.pattern??(X.pattern=R6),n.init(Y,X)}),AQ=q("$ZodCUID",(Y,X)=>{X.pattern??(X.pattern=P6),n.init(Y,X)}),RQ=q("$ZodCUID2",(Y,X)=>{X.pattern??(X.pattern=w6),n.init(Y,X)}),TQ=q("$ZodULID",(Y,X)=>{X.pattern??(X.pattern=E6),n.init(Y,X)}),CQ=q("$ZodXID",(Y,X)=>{X.pattern??(X.pattern=M6),n.init(Y,X)}),_Q=q("$ZodKSUID",(Y,X)=>{X.pattern??(X.pattern=A6),n.init(Y,X)}),IQ=q("$ZodISODateTime",(Y,X)=>{X.pattern??(X.pattern=u6(X)),n.init(Y,X)}),SQ=q("$ZodISODate",(Y,X)=>{X.pattern??(X.pattern=f6),n.init(Y,X)}),kQ=q("$ZodISOTime",(Y,X)=>{X.pattern??(X.pattern=c6(X)),n.init(Y,X)}),bQ=q("$ZodISODuration",(Y,X)=>{X.pattern??(X.pattern=T6),n.init(Y,X)}),xQ=q("$ZodIPv4",(Y,X)=>{X.pattern??(X.pattern=S6),n.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv4"})}),vQ=q("$ZodIPv6",(Y,X)=>{X.pattern??(X.pattern=k6),n.init(Y,X),Y._zod.onattach.push((J)=>{let Q=J._zod.bag;Q.format="ipv6"}),Y._zod.check=(J)=>{try{new URL(`http://[${J.value}]`)}catch{J.issues.push({code:"invalid_format",format:"ipv6",input:J.value,inst:Y,continue:!X.abort})}}}),hQ=q("$ZodCIDRv4",(Y,X)=>{X.pattern??(X.pattern=b6),n.init(Y,X)}),gQ=q("$ZodCIDRv6",(Y,X)=>{X.pattern??(X.pattern=x6),n.init(Y,X),Y._zod.check=(J)=>{let Q=J.value.split("/");try{if(Q.length!==2)throw Error();let[$,G]=Q;if(!G)throw Error();let W=Number(G);if(`${W}`!==G)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${$}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:Y,continue:!X.abort})}}});function yQ(Y){if(Y==="")return!0;if(Y.length%4!==0)return!1;try{return atob(Y),!0}catch{return!1}}var fQ=q("$ZodBase64",(Y,X)=>{X.pattern??(X.pattern=v6),n.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64"}),Y._zod.check=(J)=>{if(yQ(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:Y,continue:!X.abort})}});function a2(Y){if(!d8.test(Y))return!1;let X=Y.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=X.padEnd(Math.ceil(X.length/4)*4,"=");return yQ(J)}var mQ=q("$ZodBase64URL",(Y,X)=>{X.pattern??(X.pattern=d8),n.init(Y,X),Y._zod.onattach.push((J)=>{J._zod.bag.contentEncoding="base64url"}),Y._zod.check=(J)=>{if(a2(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:Y,continue:!X.abort})}}),cQ=q("$ZodE164",(Y,X)=>{X.pattern??(X.pattern=g6),n.init(Y,X)});function t2(Y,X=null){try{let J=Y.split(".");if(J.length!==3)return!1;let[Q]=J;if(!Q)return!1;let $=JSON.parse(atob(Q));if("typ"in $&&$?.typ!=="JWT")return!1;if(!$.alg)return!1;if(X&&(!("alg"in $)||$.alg!==X))return!1;return!0}catch{return!1}}var uQ=q("$ZodJWT",(Y,X)=>{n.init(Y,X),Y._zod.check=(J)=>{if(t2(J.value,X.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:Y,continue:!X.abort})}});var s8=q("$ZodNumber",(Y,X)=>{i.init(Y,X),Y._zod.pattern=Y._zod.bag.pattern??d6,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Number(J.value)}catch(W){}let $=J.value;if(typeof $==="number"&&!Number.isNaN($)&&Number.isFinite($))return J;let G=typeof $==="number"?Number.isNaN($)?"NaN":!Number.isFinite($)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:$,inst:Y,...G?{received:G}:{}}),J}}),pQ=q("$ZodNumber",(Y,X)=>{t6.init(Y,X),s8.init(Y,X)}),lQ=q("$ZodBoolean",(Y,X)=>{i.init(Y,X),Y._zod.pattern=i6,Y._zod.parse=(J,Q)=>{if(X.coerce)try{J.value=Boolean(J.value)}catch(G){}let $=J.value;if(typeof $==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:$,inst:Y}),J}});var dQ=q("$ZodNull",(Y,X)=>{i.init(Y,X),Y._zod.pattern=n6,Y._zod.values=new Set([null]),Y._zod.parse=(J,Q)=>{let $=J.value;if($===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:$,inst:Y}),J}});var iQ=q("$ZodUnknown",(Y,X)=>{i.init(Y,X),Y._zod.parse=(J)=>J}),nQ=q("$ZodNever",(Y,X)=>{i.init(Y,X),Y._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:Y}),J}});function LQ(Y,X,J){if(Y.issues.length)X.issues.push(...d0(J,Y.issues));X.value[J]=Y.value}var oQ=q("$ZodArray",(Y,X)=>{i.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Array.isArray($))return J.issues.push({expected:"array",code:"invalid_type",input:$,inst:Y}),J;J.value=Array($.length);let G=[];for(let W=0;W<$.length;W++){let K=$[W],H=X.element._zod.run({value:K,issues:[]},Q);if(H instanceof Promise)G.push(H.then((U)=>LQ(U,J,W)));else LQ(H,J,W)}if(G.length)return Promise.all(G).then(()=>J);return J}});function bY(Y,X,J,Q){if(Y.issues.length)X.issues.push(...d0(J,Y.issues));if(Y.value===void 0){if(J in Q)X.value[J]=void 0}else X.value[J]=Y.value}function rQ(Y){let X=Object.keys(Y.shape);for(let Q of X)if(!Y.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let J=c8(Y.shape);return{...Y,keys:X,keySet:new Set(X),numKeys:X.length,optionalKeys:new Set(J)}}function sQ(Y,X,J,Q,$,G){let W=[],K=$.keySet,H=$.catchall._zod,U=H.def.type;for(let N of Object.keys(X)){if(K.has(N))continue;if(U==="never"){W.push(N);continue}let O=H.run({value:X[N],issues:[]},Q);if(O instanceof Promise)Y.push(O.then((B)=>bY(B,J,N,X)));else bY(O,J,N,X)}if(W.length)J.issues.push({code:"unrecognized_keys",keys:W,input:X,inst:G});if(!Y.length)return J;return Promise.all(Y).then(()=>{return J})}var e2=q("$ZodObject",(Y,X)=>{i.init(Y,X);let J=_1(()=>rQ(X));p(Y._zod,"propValues",()=>{let W=X.shape,K={};for(let H in W){let U=W[H]._zod;if(U.values){K[H]??(K[H]=new Set);for(let N of U.values)K[H].add(N)}}return K});let Q=V1,$=X.catchall,G;Y._zod.parse=(W,K)=>{G??(G=J.value);let H=W.value;if(!Q(H))return W.issues.push({expected:"object",code:"invalid_type",input:H,inst:Y}),W;W.value={};let U=[],N=G.shape;for(let O of G.keys){let L=N[O]._zod.run({value:H[O],issues:[]},K);if(L instanceof Promise)U.push(L.then((Z)=>bY(Z,W,O,H)));else bY(L,W,O,H)}if(!$)return U.length?Promise.all(U).then(()=>W):W;return sQ(U,H,W,K,J.value,Y)}}),aQ=q("$ZodObjectJIT",(Y,X)=>{e2.init(Y,X);let J=Y._zod.parse,Q=_1(()=>rQ(X)),$=(B)=>{let L=new o8(["shape","payload","ctx"]),Z=Q.value,j=(x)=>{let S=RY(x);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};L.write("const input = payload.value;");let w=Object.create(null),P=0;for(let x of Z.keys)w[x]=`key_${P++}`;L.write("const newResult = {};");for(let x of Z.keys){let S=w[x],d=RY(x);L.write(`const ${S} = ${j(x)};`),L.write(`
119
+ if (${S}.issues.length) {
120
+ payload.issues = payload.issues.concat(${S}.issues.map(iss => ({
108
121
  ...iss,
109
- path: iss.path ? [${N$}, ...iss.path] : [${N$}]
122
+ path: iss.path ? [${d}, ...iss.path] : [${d}]
110
123
  })));
111
124
  }
112
125
 
113
126
 
114
- if (${Z}.value === undefined) {
115
- if (${N$} in input) {
116
- newResult[${N$}] = undefined;
127
+ if (${S}.value === undefined) {
128
+ if (${d} in input) {
129
+ newResult[${d}] = undefined;
117
130
  }
118
131
  } else {
119
- newResult[${N$}] = ${Z}.value;
132
+ newResult[${d}] = ${S}.value;
120
133
  }
121
134
 
122
- `)}w.write("payload.value = newResult;"),w.write("return payload;");let g=w.compile();return(y,Z)=>g(H,y,Z)},j,Y=n6,N=!g4.jitless,G=N&&GJ.value,Q=U.catchall,L;$._zod.parse=(H,w)=>{L??(L=X.value);let B=H.value;if(!Y(B))return H.issues.push({expected:"object",code:"invalid_type",input:B,inst:$}),H;if(N&&G&&w?.async===!1&&w.jitless!==!0){if(!j)j=J(U.shape);if(H=j(H,w),!Q)return H;return i9([],B,H,w,L,$)}return z(H,w)}});function k9($,U,z,X){for(let j of $)if(j.issues.length===0)return U.value=j.value,U;let J=$.filter((j)=>!C6(j));if(J.length===1)return U.value=J[0].value,J[0];return U.issues.push({code:"invalid_union",input:U.value,inst:z,errors:$.map((j)=>j.issues.map((Y)=>f$(Y,X,H$())))}),U}var EU=V("$ZodUnion",($,U)=>{c.init($,U),a($._zod,"optin",()=>U.options.some((J)=>J._zod.optin==="optional")?"optional":void 0),a($._zod,"optout",()=>U.options.some((J)=>J._zod.optout==="optional")?"optional":void 0),a($._zod,"values",()=>{if(U.options.every((J)=>J._zod.values))return new Set(U.options.flatMap((J)=>Array.from(J._zod.values)));return}),a($._zod,"pattern",()=>{if(U.options.every((J)=>J._zod.pattern)){let J=U.options.map((j)=>j._zod.pattern);return new RegExp(`^(${J.map((j)=>h4(j.source)).join("|")})$`)}return});let z=U.options.length===1,X=U.options[0]._zod.run;$._zod.parse=(J,j)=>{if(z)return X(J,j);let Y=!1,N=[];for(let W of U.options){let G=W._zod.run({value:J.value,issues:[]},j);if(G instanceof Promise)N.push(G),Y=!0;else{if(G.issues.length===0)return G;N.push(G)}}if(!Y)return k9(N,J,$,j);return Promise.all(N).then((W)=>{return k9(W,J,$,j)})}}),sz=V("$ZodDiscriminatedUnion",($,U)=>{EU.init($,U);let z=$._zod.parse;a($._zod,"propValues",()=>{let J={};for(let j of U.options){let Y=j._zod.propValues;if(!Y||Object.keys(Y).length===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(j)}"`);for(let[N,W]of Object.entries(Y)){if(!J[N])J[N]=new Set;for(let G of W)J[N].add(G)}}return J});let X=G4(()=>{let J=U.options,j=new Map;for(let Y of J){let N=Y._zod.propValues?.[U.discriminator];if(!N||N.size===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(Y)}"`);for(let W of N){if(j.has(W))throw Error(`Duplicate discriminator value "${String(W)}"`);j.set(W,Y)}}return j});$._zod.parse=(J,j)=>{let Y=J.value;if(!n6(Y))return J.issues.push({code:"invalid_type",expected:"object",input:Y,inst:$}),J;let N=X.value.get(Y?.[U.discriminator]);if(N)return N._zod.run(J,j);if(U.unionFallback)return z(J,j);return J.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:U.discriminator,input:Y,path:[U.discriminator],inst:$}),J}}),ez=V("$ZodIntersection",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{let J=z.value,j=U.left._zod.run({value:J,issues:[]},X),Y=U.right._zod.run({value:J,issues:[]},X);if(j instanceof Promise||Y instanceof Promise)return Promise.all([j,Y]).then(([W,G])=>{return C9(z,W,G)});return C9(z,j,Y)}});function Vz($,U){if($===U)return{valid:!0,data:$};if($ instanceof Date&&U instanceof Date&&+$===+U)return{valid:!0,data:$};if(k6($)&&k6(U)){let z=Object.keys(U),X=Object.keys($).filter((j)=>z.indexOf(j)!==-1),J={...$,...U};for(let j of X){let Y=Vz($[j],U[j]);if(!Y.valid)return{valid:!1,mergeErrorPath:[j,...Y.mergeErrorPath]};J[j]=Y.data}return{valid:!0,data:J}}if(Array.isArray($)&&Array.isArray(U)){if($.length!==U.length)return{valid:!1,mergeErrorPath:[]};let z=[];for(let X=0;X<$.length;X++){let J=$[X],j=U[X],Y=Vz(J,j);if(!Y.valid)return{valid:!1,mergeErrorPath:[X,...Y.mergeErrorPath]};z.push(Y.data)}return{valid:!0,data:z}}return{valid:!1,mergeErrorPath:[]}}function C9($,U,z){if(U.issues.length)$.issues.push(...U.issues);if(z.issues.length)$.issues.push(...z.issues);if(C6($))return $;let X=Vz(U.value,z.value);if(!X.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(X.mergeErrorPath)}`);return $.value=X.data,$}var MU=V("$ZodTuple",($,U)=>{c.init($,U);let z=U.items,X=z.length-[...z].reverse().findIndex((J)=>J._zod.optin!=="optional");$._zod.parse=(J,j)=>{let Y=J.value;if(!Array.isArray(Y))return J.issues.push({input:Y,inst:$,expected:"tuple",code:"invalid_type"}),J;J.value=[];let N=[];if(!U.rest){let G=Y.length>z.length,Q=Y.length<X-1;if(G||Q)return J.issues.push({...G?{code:"too_big",maximum:z.length}:{code:"too_small",minimum:z.length},input:Y,inst:$,origin:"array"}),J}let W=-1;for(let G of z){if(W++,W>=Y.length){if(W>=X)continue}let Q=G._zod.run({value:Y[W],issues:[]},j);if(Q instanceof Promise)N.push(Q.then((L)=>KU(L,J,W)));else KU(Q,J,W)}if(U.rest){let G=Y.slice(z.length);for(let Q of G){W++;let L=U.rest._zod.run({value:Q,issues:[]},j);if(L instanceof Promise)N.push(L.then((H)=>KU(H,J,W)));else KU(L,J,W)}}if(N.length)return Promise.all(N).then(()=>J);return J}});function KU($,U,z){if($.issues.length)U.issues.push(...x$(z,$.issues));U.value[z]=$.value}var $X=V("$ZodRecord",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{let J=z.value;if(!k6(J))return z.issues.push({expected:"record",code:"invalid_type",input:J,inst:$}),z;let j=[];if(U.keyType._zod.values){let Y=U.keyType._zod.values;z.value={};for(let W of Y)if(typeof W==="string"||typeof W==="number"||typeof W==="symbol"){let G=U.valueType._zod.run({value:J[W],issues:[]},X);if(G instanceof Promise)j.push(G.then((Q)=>{if(Q.issues.length)z.issues.push(...x$(W,Q.issues));z.value[W]=Q.value}));else{if(G.issues.length)z.issues.push(...x$(W,G.issues));z.value[W]=G.value}}let N;for(let W in J)if(!Y.has(W))N=N??[],N.push(W);if(N&&N.length>0)z.issues.push({code:"unrecognized_keys",input:J,inst:$,keys:N})}else{z.value={};for(let Y of Reflect.ownKeys(J)){if(Y==="__proto__")continue;let N=U.keyType._zod.run({value:Y,issues:[]},X);if(N instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(N.issues.length){z.issues.push({code:"invalid_key",origin:"record",issues:N.issues.map((G)=>f$(G,X,H$())),input:Y,path:[Y],inst:$}),z.value[N.value]=N.value;continue}let W=U.valueType._zod.run({value:J[Y],issues:[]},X);if(W instanceof Promise)j.push(W.then((G)=>{if(G.issues.length)z.issues.push(...x$(Y,G.issues));z.value[N.value]=G.value}));else{if(W.issues.length)z.issues.push(...x$(Y,W.issues));z.value[N.value]=W.value}}}if(j.length)return Promise.all(j).then(()=>z);return z}}),UX=V("$ZodMap",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{let J=z.value;if(!(J instanceof Map))return z.issues.push({expected:"map",code:"invalid_type",input:J,inst:$}),z;let j=[];z.value=new Map;for(let[Y,N]of J){let W=U.keyType._zod.run({value:Y,issues:[]},X),G=U.valueType._zod.run({value:N,issues:[]},X);if(W instanceof Promise||G instanceof Promise)j.push(Promise.all([W,G]).then(([Q,L])=>{Z9(Q,L,z,Y,J,$,X)}));else Z9(W,G,z,Y,J,$,X)}if(j.length)return Promise.all(j).then(()=>z);return z}});function Z9($,U,z,X,J,j,Y){if($.issues.length)if(y4.has(typeof X))z.issues.push(...x$(X,$.issues));else z.issues.push({code:"invalid_key",origin:"map",input:J,inst:j,issues:$.issues.map((N)=>f$(N,Y,H$()))});if(U.issues.length)if(y4.has(typeof X))z.issues.push(...x$(X,U.issues));else z.issues.push({origin:"map",code:"invalid_element",input:J,inst:j,key:X,issues:U.issues.map((N)=>f$(N,Y,H$()))});z.value.set($.value,U.value)}var JX=V("$ZodSet",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{let J=z.value;if(!(J instanceof Set))return z.issues.push({input:J,inst:$,expected:"set",code:"invalid_type"}),z;let j=[];z.value=new Set;for(let Y of J){let N=U.valueType._zod.run({value:Y,issues:[]},X);if(N instanceof Promise)j.push(N.then((W)=>T9(W,z)));else T9(N,z)}if(j.length)return Promise.all(j).then(()=>z);return z}});function T9($,U){if($.issues.length)U.issues.push(...$.issues);U.value.add($.value)}var zX=V("$ZodEnum",($,U)=>{c.init($,U);let z=f4(U.entries),X=new Set(z);$._zod.values=X,$._zod.pattern=new RegExp(`^(${z.filter((J)=>y4.has(typeof J)).map((J)=>typeof J==="string"?$6(J):J.toString()).join("|")})$`),$._zod.parse=(J,j)=>{let Y=J.value;if(X.has(Y))return J;return J.issues.push({code:"invalid_value",values:z,input:Y,inst:$}),J}}),XX=V("$ZodLiteral",($,U)=>{if(c.init($,U),U.values.length===0)throw Error("Cannot create literal schema with no valid values");$._zod.values=new Set(U.values),$._zod.pattern=new RegExp(`^(${U.values.map((z)=>typeof z==="string"?$6(z):z?$6(z.toString()):String(z)).join("|")})$`),$._zod.parse=(z,X)=>{let J=z.value;if($._zod.values.has(J))return z;return z.issues.push({code:"invalid_value",values:U.values,input:J,inst:$}),z}}),jX=V("$ZodFile",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{let J=z.value;if(J instanceof File)return z;return z.issues.push({expected:"file",code:"invalid_type",input:J,inst:$}),z}}),YX=V("$ZodTransform",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{if(X.direction==="backward")throw new l6($.constructor.name);let J=U.transform(z.value,z);if(X.async)return(J instanceof Promise?J:Promise.resolve(J)).then((Y)=>{return z.value=Y,z});if(J instanceof Promise)throw new e$;return z.value=J,z}});function g9($,U){if($.issues.length&&U===void 0)return{issues:[],value:void 0};return $}var NX=V("$ZodOptional",($,U)=>{c.init($,U),$._zod.optin="optional",$._zod.optout="optional",a($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,void 0]):void 0}),a($._zod,"pattern",()=>{let z=U.innerType._zod.pattern;return z?new RegExp(`^(${h4(z.source)})?$`):void 0}),$._zod.parse=(z,X)=>{if(U.innerType._zod.optin==="optional"){let J=U.innerType._zod.run(z,X);if(J instanceof Promise)return J.then((j)=>g9(j,z.value));return g9(J,z.value)}if(z.value===void 0)return z;return U.innerType._zod.run(z,X)}}),OX=V("$ZodNullable",($,U)=>{c.init($,U),a($._zod,"optin",()=>U.innerType._zod.optin),a($._zod,"optout",()=>U.innerType._zod.optout),a($._zod,"pattern",()=>{let z=U.innerType._zod.pattern;return z?new RegExp(`^(${h4(z.source)}|null)$`):void 0}),a($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,null]):void 0}),$._zod.parse=(z,X)=>{if(z.value===null)return z;return U.innerType._zod.run(z,X)}}),WX=V("$ZodDefault",($,U)=>{c.init($,U),$._zod.optin="optional",a($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(z,X)=>{if(X.direction==="backward")return U.innerType._zod.run(z,X);if(z.value===void 0)return z.value=U.defaultValue,z;let J=U.innerType._zod.run(z,X);if(J instanceof Promise)return J.then((j)=>x9(j,U));return x9(J,U)}});function x9($,U){if($.value===void 0)$.value=U.defaultValue;return $}var GX=V("$ZodPrefault",($,U)=>{c.init($,U),$._zod.optin="optional",a($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(z,X)=>{if(X.direction==="backward")return U.innerType._zod.run(z,X);if(z.value===void 0)z.value=U.defaultValue;return U.innerType._zod.run(z,X)}}),QX=V("$ZodNonOptional",($,U)=>{c.init($,U),a($._zod,"values",()=>{let z=U.innerType._zod.values;return z?new Set([...z].filter((X)=>X!==void 0)):void 0}),$._zod.parse=(z,X)=>{let J=U.innerType._zod.run(z,X);if(J instanceof Promise)return J.then((j)=>f9(j,$));return f9(J,$)}});function f9($,U){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:U});return $}var wX=V("$ZodSuccess",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{if(X.direction==="backward")throw new l6("ZodSuccess");let J=U.innerType._zod.run(z,X);if(J instanceof Promise)return J.then((j)=>{return z.value=j.issues.length===0,z});return z.value=J.issues.length===0,z}}),HX=V("$ZodCatch",($,U)=>{c.init($,U),a($._zod,"optin",()=>U.innerType._zod.optin),a($._zod,"optout",()=>U.innerType._zod.optout),a($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(z,X)=>{if(X.direction==="backward")return U.innerType._zod.run(z,X);let J=U.innerType._zod.run(z,X);if(J instanceof Promise)return J.then((j)=>{if(z.value=j.value,j.issues.length)z.value=U.catchValue({...z,error:{issues:j.issues.map((Y)=>f$(Y,X,H$()))},input:z.value}),z.issues=[];return z});if(z.value=J.value,J.issues.length)z.value=U.catchValue({...z,error:{issues:J.issues.map((j)=>f$(j,X,H$()))},input:z.value}),z.issues=[];return z}}),VX=V("$ZodNaN",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{if(typeof z.value!=="number"||!Number.isNaN(z.value))return z.issues.push({input:z.value,inst:$,expected:"nan",code:"invalid_type"}),z;return z}}),LX=V("$ZodPipe",($,U)=>{c.init($,U),a($._zod,"values",()=>U.in._zod.values),a($._zod,"optin",()=>U.in._zod.optin),a($._zod,"optout",()=>U.out._zod.optout),a($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(z,X)=>{if(X.direction==="backward"){let j=U.out._zod.run(z,X);if(j instanceof Promise)return j.then((Y)=>qU(Y,U.in,X));return qU(j,U.in,X)}let J=U.in._zod.run(z,X);if(J instanceof Promise)return J.then((j)=>qU(j,U.out,X));return qU(J,U.out,X)}});function qU($,U,z){if($.issues.length)return $.aborted=!0,$;return U._zod.run({value:$.value,issues:$.issues},z)}var d4=V("$ZodCodec",($,U)=>{c.init($,U),a($._zod,"values",()=>U.in._zod.values),a($._zod,"optin",()=>U.in._zod.optin),a($._zod,"optout",()=>U.out._zod.optout),a($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(z,X)=>{if((X.direction||"forward")==="forward"){let j=U.in._zod.run(z,X);if(j instanceof Promise)return j.then((Y)=>_U(Y,U,X));return _U(j,U,X)}else{let j=U.out._zod.run(z,X);if(j instanceof Promise)return j.then((Y)=>_U(Y,U,X));return _U(j,U,X)}}});function _U($,U,z){if($.issues.length)return $.aborted=!0,$;if((z.direction||"forward")==="forward"){let J=U.transform($.value,$);if(J instanceof Promise)return J.then((j)=>vU($,j,U.out,z));return vU($,J,U.out,z)}else{let J=U.reverseTransform($.value,$);if(J instanceof Promise)return J.then((j)=>vU($,j,U.in,z));return vU($,J,U.in,z)}}function vU($,U,z,X){if($.issues.length)return $.aborted=!0,$;return z._zod.run({value:U,issues:$.issues},X)}var BX=V("$ZodReadonly",($,U)=>{c.init($,U),a($._zod,"propValues",()=>U.innerType._zod.propValues),a($._zod,"values",()=>U.innerType._zod.values),a($._zod,"optin",()=>U.innerType._zod.optin),a($._zod,"optout",()=>U.innerType._zod.optout),$._zod.parse=(z,X)=>{if(X.direction==="backward")return U.innerType._zod.run(z,X);let J=U.innerType._zod.run(z,X);if(J instanceof Promise)return J.then(h9);return h9(J)}});function h9($){return $.value=Object.freeze($.value),$}var DX=V("$ZodTemplateLiteral",($,U)=>{c.init($,U);let z=[];for(let X of U.parts)if(typeof X==="object"&&X!==null){if(!X._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...X._zod.traits].shift()}`);let J=X._zod.pattern instanceof RegExp?X._zod.pattern.source:X._zod.pattern;if(!J)throw Error(`Invalid template literal part: ${X._zod.traits}`);let j=J.startsWith("^")?1:0,Y=J.endsWith("$")?J.length-1:J.length;z.push(J.slice(j,Y))}else if(X===null||wJ.has(typeof X))z.push($6(`${X}`));else throw Error(`Invalid template literal part: ${X}`);$._zod.pattern=new RegExp(`^${z.join("")}$`),$._zod.parse=(X,J)=>{if(typeof X.value!=="string")return X.issues.push({input:X.value,inst:$,expected:"template_literal",code:"invalid_type"}),X;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(X.value))return X.issues.push({input:X.value,inst:$,code:"invalid_format",format:U.format??"template_literal",pattern:$._zod.pattern.source}),X;return X}}),KX=V("$ZodFunction",($,U)=>{return c.init($,U),$._def=U,$._zod.def=U,$.implement=(z)=>{if(typeof z!=="function")throw Error("implement() must be called with a function");return function(...X){let J=$._def.input?XU($._def.input,X):X,j=Reflect.apply(z,this,J);if($._def.output)return XU($._def.output,j);return j}},$.implementAsync=(z)=>{if(typeof z!=="function")throw Error("implementAsync() must be called with a function");return async function(...X){let J=$._def.input?await jU($._def.input,X):X,j=await Reflect.apply(z,this,J);if($._def.output)return await jU($._def.output,j);return j}},$._zod.parse=(z,X)=>{if(typeof z.value!=="function")return z.issues.push({code:"invalid_type",expected:"function",input:z.value,inst:$}),z;if($._def.output&&$._def.output._zod.def.type==="promise")z.value=$.implementAsync(z.value);else z.value=$.implement(z.value);return z},$.input=(...z)=>{let X=$.constructor;if(Array.isArray(z[0]))return new X({type:"function",input:new MU({type:"tuple",items:z[0],rest:z[1]}),output:$._def.output});return new X({type:"function",input:z[0],output:$._def.output})},$.output=(z)=>{return new $.constructor({type:"function",input:$._def.input,output:z})},$}),qX=V("$ZodPromise",($,U)=>{c.init($,U),$._zod.parse=(z,X)=>{return Promise.resolve(z.value).then((J)=>U.innerType._zod.run({value:J,issues:[]},X))}}),_X=V("$ZodLazy",($,U)=>{c.init($,U),a($._zod,"innerType",()=>U.getter()),a($._zod,"pattern",()=>$._zod.innerType._zod.pattern),a($._zod,"propValues",()=>$._zod.innerType._zod.propValues),a($._zod,"optin",()=>$._zod.innerType._zod.optin??void 0),a($._zod,"optout",()=>$._zod.innerType._zod.optout??void 0),$._zod.parse=(z,X)=>{return $._zod.innerType._zod.run(z,X)}}),vX=V("$ZodCustom",($,U)=>{j$.init($,U),c.init($,U),$._zod.parse=(z,X)=>{return z},$._zod.check=(z)=>{let X=z.value,J=U.fn(X);if(J instanceof Promise)return J.then((j)=>y9(j,z,X,$));y9(J,z,X,$);return}});function y9($,U,z,X){if(!$){let J={code:"custom",input:z,inst:X,path:[...X._zod.def.path??[]],continue:!X._zod.def.abort};if(X._zod.def.params)J.params=X._zod.def.params;U.issues.push(Q4(J))}}var $1={};w6($1,{zhTW:()=>Wj,zhCN:()=>Oj,yo:()=>Gj,vi:()=>Nj,ur:()=>Yj,uk:()=>e4,ua:()=>jj,tr:()=>Xj,th:()=>zj,ta:()=>Jj,sv:()=>Uj,sl:()=>$j,ru:()=>eX,pt:()=>sX,ps:()=>tX,pl:()=>aX,ota:()=>oX,no:()=>dX,nl:()=>pX,ms:()=>rX,mk:()=>nX,lt:()=>lX,ko:()=>iX,km:()=>t4,kh:()=>uX,ka:()=>mX,ja:()=>cX,it:()=>yX,is:()=>hX,id:()=>fX,hu:()=>xX,he:()=>gX,frCA:()=>TX,fr:()=>ZX,fi:()=>CX,fa:()=>kX,es:()=>SX,eo:()=>IX,en:()=>o4,de:()=>RX,da:()=>bX,cs:()=>MX,ca:()=>EX,be:()=>AX,az:()=>PX,ar:()=>FX});var Vw=()=>{let $={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"number";case"object":{if(Array.isArray(J))return"array";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"};return(J)=>{switch(J.code){case"invalid_type":return`مدخلات غير مقبولة: يفترض إدخال ${J.expected}، ولكن تم إدخال ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${P(J.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return` أكبر من اللازم: يفترض أن تكون ${J.origin??"القيمة"} ${j} ${J.maximum.toString()} ${Y.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${J.origin??"القيمة"} ${j} ${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`أصغر من اللازم: يفترض لـ ${J.origin} أن يكون ${j} ${J.minimum.toString()} ${Y.unit}`;return`أصغر من اللازم: يفترض لـ ${J.origin} أن يكون ${j} ${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${J.prefix}"`;if(j.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${j.suffix}"`;if(j.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${j.includes}"`;if(j.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${j.pattern}`;return`${X[j.format]??J.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${J.divisor}`;case"unrecognized_keys":return`معرف${J.keys.length>1?"ات":""} غريب${J.keys.length>1?"ة":""}: ${D(J.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${J.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${J.origin}`;default:return"مدخل غير مقبول"}}};function FX(){return{localeError:Vw()}}var Lw=()=>{let $={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"number";case"object":{if(Array.isArray(J))return"array";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(J)=>{switch(J.code){case"invalid_type":return`Yanlış dəyər: gözlənilən ${J.expected}, daxil olan ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Yanlış dəyər: gözlənilən ${P(J.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Çox böyük: gözlənilən ${J.origin??"dəyər"} ${j}${J.maximum.toString()} ${Y.unit??"element"}`;return`Çox böyük: gözlənilən ${J.origin??"dəyər"} ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Çox kiçik: gözlənilən ${J.origin} ${j}${J.minimum.toString()} ${Y.unit}`;return`Çox kiçik: gözlənilən ${J.origin} ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Yanlış mətn: "${j.prefix}" ilə başlamalıdır`;if(j.format==="ends_with")return`Yanlış mətn: "${j.suffix}" ilə bitməlidir`;if(j.format==="includes")return`Yanlış mətn: "${j.includes}" daxil olmalıdır`;if(j.format==="regex")return`Yanlış mətn: ${j.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${X[j.format]??J.format}`}case"not_multiple_of":return`Yanlış ədəd: ${J.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${J.keys.length>1?"lar":""}: ${D(J.keys,", ")}`;case"invalid_key":return`${J.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${J.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function PX(){return{localeError:Lw()}}function n9($,U,z,X){let J=Math.abs($),j=J%10,Y=J%100;if(Y>=11&&Y<=19)return X;if(j===1)return U;if(j>=2&&j<=4)return z;return X}var Bw=()=>{let $={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"лік";case"object":{if(Array.isArray(J))return"масіў";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"};return(J)=>{switch(J.code){case"invalid_type":return`Няправільны ўвод: чакаўся ${J.expected}, атрымана ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Няправільны ўвод: чакалася ${P(J.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y){let N=Number(J.maximum),W=n9(N,Y.unit.one,Y.unit.few,Y.unit.many);return`Занадта вялікі: чакалася, што ${J.origin??"значэнне"} павінна ${Y.verb} ${j}${J.maximum.toString()} ${W}`}return`Занадта вялікі: чакалася, што ${J.origin??"значэнне"} павінна быць ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y){let N=Number(J.minimum),W=n9(N,Y.unit.one,Y.unit.few,Y.unit.many);return`Занадта малы: чакалася, што ${J.origin} павінна ${Y.verb} ${j}${J.minimum.toString()} ${W}`}return`Занадта малы: чакалася, што ${J.origin} павінна быць ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${j.prefix}"`;if(j.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${j.suffix}"`;if(j.format==="includes")return`Няправільны радок: павінен змяшчаць "${j.includes}"`;if(j.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${j.pattern}`;return`Няправільны ${X[j.format]??J.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${J.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${J.keys.length>1?"ключы":"ключ"}: ${D(J.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${J.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${J.origin}`;default:return"Няправільны ўвод"}}};function AX(){return{localeError:Bw()}}var Dw=()=>{let $={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"number";case"object":{if(Array.isArray(J))return"array";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return(J)=>{switch(J.code){case"invalid_type":return`Tipus invàlid: s'esperava ${J.expected}, s'ha rebut ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Valor invàlid: s'esperava ${P(J.values[0])}`;return`Opció invàlida: s'esperava una de ${D(J.values," o ")}`;case"too_big":{let j=J.inclusive?"com a màxim":"menys de",Y=U(J.origin);if(Y)return`Massa gran: s'esperava que ${J.origin??"el valor"} contingués ${j} ${J.maximum.toString()} ${Y.unit??"elements"}`;return`Massa gran: s'esperava que ${J.origin??"el valor"} fos ${j} ${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?"com a mínim":"més de",Y=U(J.origin);if(Y)return`Massa petit: s'esperava que ${J.origin} contingués ${j} ${J.minimum.toString()} ${Y.unit}`;return`Massa petit: s'esperava que ${J.origin} fos ${j} ${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Format invàlid: ha de començar amb "${j.prefix}"`;if(j.format==="ends_with")return`Format invàlid: ha d'acabar amb "${j.suffix}"`;if(j.format==="includes")return`Format invàlid: ha d'incloure "${j.includes}"`;if(j.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${j.pattern}`;return`Format invàlid per a ${X[j.format]??J.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${J.divisor}`;case"unrecognized_keys":return`Clau${J.keys.length>1?"s":""} no reconeguda${J.keys.length>1?"s":""}: ${D(J.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${J.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${J.origin}`;default:return"Entrada invàlida"}}};function EX(){return{localeError:Dw()}}var Kw=()=>{let $={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"číslo";case"string":return"řetězec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray(J))return"pole";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"};return(J)=>{switch(J.code){case"invalid_type":return`Neplatný vstup: očekáváno ${J.expected}, obdrženo ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Neplatný vstup: očekáváno ${P(J.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Hodnota je příliš velká: ${J.origin??"hodnota"} musí mít ${j}${J.maximum.toString()} ${Y.unit??"prvků"}`;return`Hodnota je příliš velká: ${J.origin??"hodnota"} musí být ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Hodnota je příliš malá: ${J.origin??"hodnota"} musí mít ${j}${J.minimum.toString()} ${Y.unit??"prvků"}`;return`Hodnota je příliš malá: ${J.origin??"hodnota"} musí být ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Neplatný řetězec: musí začínat na "${j.prefix}"`;if(j.format==="ends_with")return`Neplatný řetězec: musí končit na "${j.suffix}"`;if(j.format==="includes")return`Neplatný řetězec: musí obsahovat "${j.includes}"`;if(j.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${j.pattern}`;return`Neplatný formát ${X[j.format]??J.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${J.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${D(J.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${J.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${J.origin}`;default:return"Neplatný vstup"}}};function MX(){return{localeError:Kw()}}var qw=()=>{let $={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}},U={string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};function z(Y){return $[Y]??null}function X(Y){return U[Y]??Y}let J=(Y)=>{let N=typeof Y;switch(N){case"number":return Number.isNaN(Y)?"NaN":"tal";case"object":{if(Array.isArray(Y))return"liste";if(Y===null)return"null";if(Object.getPrototypeOf(Y)!==Object.prototype&&Y.constructor)return Y.constructor.name;return"objekt"}}return N},j={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return(Y)=>{switch(Y.code){case"invalid_type":return`Ugyldigt input: forventede ${X(Y.expected)}, fik ${X(J(Y.input))}`;case"invalid_value":if(Y.values.length===1)return`Ugyldig værdi: forventede ${P(Y.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${D(Y.values,"|")}`;case"too_big":{let N=Y.inclusive?"<=":"<",W=z(Y.origin),G=X(Y.origin);if(W)return`For stor: forventede ${G??"value"} ${W.verb} ${N} ${Y.maximum.toString()} ${W.unit??"elementer"}`;return`For stor: forventede ${G??"value"} havde ${N} ${Y.maximum.toString()}`}case"too_small":{let N=Y.inclusive?">=":">",W=z(Y.origin),G=X(Y.origin);if(W)return`For lille: forventede ${G} ${W.verb} ${N} ${Y.minimum.toString()} ${W.unit}`;return`For lille: forventede ${G} havde ${N} ${Y.minimum.toString()}`}case"invalid_format":{let N=Y;if(N.format==="starts_with")return`Ugyldig streng: skal starte med "${N.prefix}"`;if(N.format==="ends_with")return`Ugyldig streng: skal ende med "${N.suffix}"`;if(N.format==="includes")return`Ugyldig streng: skal indeholde "${N.includes}"`;if(N.format==="regex")return`Ugyldig streng: skal matche mønsteret ${N.pattern}`;return`Ugyldig ${j[N.format]??Y.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${Y.divisor}`;case"unrecognized_keys":return`${Y.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${D(Y.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${Y.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${Y.origin}`;default:return"Ugyldigt input"}}};function bX(){return{localeError:qw()}}var _w=()=>{let $={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"Zahl";case"object":{if(Array.isArray(J))return"Array";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return(J)=>{switch(J.code){case"invalid_type":return`Ungültige Eingabe: erwartet ${J.expected}, erhalten ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Ungültige Eingabe: erwartet ${P(J.values[0])}`;return`Ungültige Option: erwartet eine von ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Zu groß: erwartet, dass ${J.origin??"Wert"} ${j}${J.maximum.toString()} ${Y.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${J.origin??"Wert"} ${j}${J.maximum.toString()} ist`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Zu klein: erwartet, dass ${J.origin} ${j}${J.minimum.toString()} ${Y.unit} hat`;return`Zu klein: erwartet, dass ${J.origin} ${j}${J.minimum.toString()} ist`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Ungültiger String: muss mit "${j.prefix}" beginnen`;if(j.format==="ends_with")return`Ungültiger String: muss mit "${j.suffix}" enden`;if(j.format==="includes")return`Ungültiger String: muss "${j.includes}" enthalten`;if(j.format==="regex")return`Ungültiger String: muss dem Muster ${j.pattern} entsprechen`;return`Ungültig: ${X[j.format]??J.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${J.divisor} sein`;case"unrecognized_keys":return`${J.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${D(J.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${J.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${J.origin}`;default:return"Ungültige Eingabe"}}};function RX(){return{localeError:_w()}}var vw=($)=>{let U=typeof $;switch(U){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return U},Fw=()=>{let $={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function U(X){return $[X]??null}let z={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(X)=>{switch(X.code){case"invalid_type":return`Invalid input: expected ${X.expected}, received ${vw(X.input)}`;case"invalid_value":if(X.values.length===1)return`Invalid input: expected ${P(X.values[0])}`;return`Invalid option: expected one of ${D(X.values,"|")}`;case"too_big":{let J=X.inclusive?"<=":"<",j=U(X.origin);if(j)return`Too big: expected ${X.origin??"value"} to have ${J}${X.maximum.toString()} ${j.unit??"elements"}`;return`Too big: expected ${X.origin??"value"} to be ${J}${X.maximum.toString()}`}case"too_small":{let J=X.inclusive?">=":">",j=U(X.origin);if(j)return`Too small: expected ${X.origin} to have ${J}${X.minimum.toString()} ${j.unit}`;return`Too small: expected ${X.origin} to be ${J}${X.minimum.toString()}`}case"invalid_format":{let J=X;if(J.format==="starts_with")return`Invalid string: must start with "${J.prefix}"`;if(J.format==="ends_with")return`Invalid string: must end with "${J.suffix}"`;if(J.format==="includes")return`Invalid string: must include "${J.includes}"`;if(J.format==="regex")return`Invalid string: must match pattern ${J.pattern}`;return`Invalid ${z[J.format]??X.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${X.divisor}`;case"unrecognized_keys":return`Unrecognized key${X.keys.length>1?"s":""}: ${D(X.keys,", ")}`;case"invalid_key":return`Invalid key in ${X.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${X.origin}`;default:return"Invalid input"}}};function o4(){return{localeError:Fw()}}var Pw=($)=>{let U=typeof $;switch(U){case"number":return Number.isNaN($)?"NaN":"nombro";case"object":{if(Array.isArray($))return"tabelo";if($===null)return"senvalora";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return U},Aw=()=>{let $={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function U(X){return $[X]??null}let z={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return(X)=>{switch(X.code){case"invalid_type":return`Nevalida enigo: atendiĝis ${X.expected}, riceviĝis ${Pw(X.input)}`;case"invalid_value":if(X.values.length===1)return`Nevalida enigo: atendiĝis ${P(X.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${D(X.values,"|")}`;case"too_big":{let J=X.inclusive?"<=":"<",j=U(X.origin);if(j)return`Tro granda: atendiĝis ke ${X.origin??"valoro"} havu ${J}${X.maximum.toString()} ${j.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${X.origin??"valoro"} havu ${J}${X.maximum.toString()}`}case"too_small":{let J=X.inclusive?">=":">",j=U(X.origin);if(j)return`Tro malgranda: atendiĝis ke ${X.origin} havu ${J}${X.minimum.toString()} ${j.unit}`;return`Tro malgranda: atendiĝis ke ${X.origin} estu ${J}${X.minimum.toString()}`}case"invalid_format":{let J=X;if(J.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${J.prefix}"`;if(J.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${J.suffix}"`;if(J.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${J.includes}"`;if(J.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${J.pattern}`;return`Nevalida ${z[J.format]??X.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${X.divisor}`;case"unrecognized_keys":return`Nekonata${X.keys.length>1?"j":""} ŝlosilo${X.keys.length>1?"j":""}: ${D(X.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${X.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${X.origin}`;default:return"Nevalida enigo"}}};function IX(){return{localeError:Aw()}}var Ew=()=>{let $={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}},U={string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};function z(Y){return $[Y]??null}function X(Y){return U[Y]??Y}let J=(Y)=>{let N=typeof Y;switch(N){case"number":return Number.isNaN(Y)?"NaN":"number";case"object":{if(Array.isArray(Y))return"array";if(Y===null)return"null";if(Object.getPrototypeOf(Y)!==Object.prototype)return Y.constructor.name;return"object"}}return N},j={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return(Y)=>{switch(Y.code){case"invalid_type":return`Entrada inválida: se esperaba ${X(Y.expected)}, recibido ${X(J(Y.input))}`;case"invalid_value":if(Y.values.length===1)return`Entrada inválida: se esperaba ${P(Y.values[0])}`;return`Opción inválida: se esperaba una de ${D(Y.values,"|")}`;case"too_big":{let N=Y.inclusive?"<=":"<",W=z(Y.origin),G=X(Y.origin);if(W)return`Demasiado grande: se esperaba que ${G??"valor"} tuviera ${N}${Y.maximum.toString()} ${W.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${G??"valor"} fuera ${N}${Y.maximum.toString()}`}case"too_small":{let N=Y.inclusive?">=":">",W=z(Y.origin),G=X(Y.origin);if(W)return`Demasiado pequeño: se esperaba que ${G} tuviera ${N}${Y.minimum.toString()} ${W.unit}`;return`Demasiado pequeño: se esperaba que ${G} fuera ${N}${Y.minimum.toString()}`}case"invalid_format":{let N=Y;if(N.format==="starts_with")return`Cadena inválida: debe comenzar con "${N.prefix}"`;if(N.format==="ends_with")return`Cadena inválida: debe terminar en "${N.suffix}"`;if(N.format==="includes")return`Cadena inválida: debe incluir "${N.includes}"`;if(N.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${N.pattern}`;return`Inválido ${j[N.format]??Y.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${Y.divisor}`;case"unrecognized_keys":return`Llave${Y.keys.length>1?"s":""} desconocida${Y.keys.length>1?"s":""}: ${D(Y.keys,", ")}`;case"invalid_key":return`Llave inválida en ${X(Y.origin)}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${X(Y.origin)}`;default:return"Entrada inválida"}}};function SX(){return{localeError:Ew()}}var Mw=()=>{let $={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"عدد";case"object":{if(Array.isArray(J))return"آرایه";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"};return(J)=>{switch(J.code){case"invalid_type":return`ورودی نامعتبر: می‌بایست ${J.expected} می‌بود، ${z(J.input)} دریافت شد`;case"invalid_value":if(J.values.length===1)return`ورودی نامعتبر: می‌بایست ${P(J.values[0])} می‌بود`;return`گزینه نامعتبر: می‌بایست یکی از ${D(J.values,"|")} می‌بود`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`خیلی بزرگ: ${J.origin??"مقدار"} باید ${j}${J.maximum.toString()} ${Y.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${J.origin??"مقدار"} باید ${j}${J.maximum.toString()} باشد`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`خیلی کوچک: ${J.origin} باید ${j}${J.minimum.toString()} ${Y.unit} باشد`;return`خیلی کوچک: ${J.origin} باید ${j}${J.minimum.toString()} باشد`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`رشته نامعتبر: باید با "${j.prefix}" شروع شود`;if(j.format==="ends_with")return`رشته نامعتبر: باید با "${j.suffix}" تمام شود`;if(j.format==="includes")return`رشته نامعتبر: باید شامل "${j.includes}" باشد`;if(j.format==="regex")return`رشته نامعتبر: باید با الگوی ${j.pattern} مطابقت داشته باشد`;return`${X[j.format]??J.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${J.divisor} باشد`;case"unrecognized_keys":return`کلید${J.keys.length>1?"های":""} ناشناس: ${D(J.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${J.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${J.origin}`;default:return"ورودی نامعتبر"}}};function kX(){return{localeError:Mw()}}var bw=()=>{let $={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"number";case"object":{if(Array.isArray(J))return"array";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return(J)=>{switch(J.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${J.expected}, oli ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Virheellinen syöte: täytyy olla ${P(J.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Liian suuri: ${Y.subject} täytyy olla ${j}${J.maximum.toString()} ${Y.unit}`.trim();return`Liian suuri: arvon täytyy olla ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Liian pieni: ${Y.subject} täytyy olla ${j}${J.minimum.toString()} ${Y.unit}`.trim();return`Liian pieni: arvon täytyy olla ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${j.prefix}"`;if(j.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${j.suffix}"`;if(j.format==="includes")return`Virheellinen syöte: täytyy sisältää "${j.includes}"`;if(j.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${j.pattern}`;return`Virheellinen ${X[j.format]??J.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${J.divisor} monikerta`;case"unrecognized_keys":return`${J.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${D(J.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function CX(){return{localeError:bw()}}var Rw=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"nombre";case"object":{if(Array.isArray(J))return"tableau";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return(J)=>{switch(J.code){case"invalid_type":return`Entrée invalide : ${J.expected} attendu, ${z(J.input)} reçu`;case"invalid_value":if(J.values.length===1)return`Entrée invalide : ${P(J.values[0])} attendu`;return`Option invalide : une valeur parmi ${D(J.values,"|")} attendue`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Trop grand : ${J.origin??"valeur"} doit ${Y.verb} ${j}${J.maximum.toString()} ${Y.unit??"élément(s)"}`;return`Trop grand : ${J.origin??"valeur"} doit être ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Trop petit : ${J.origin} doit ${Y.verb} ${j}${J.minimum.toString()} ${Y.unit}`;return`Trop petit : ${J.origin} doit être ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Chaîne invalide : doit commencer par "${j.prefix}"`;if(j.format==="ends_with")return`Chaîne invalide : doit se terminer par "${j.suffix}"`;if(j.format==="includes")return`Chaîne invalide : doit inclure "${j.includes}"`;if(j.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${j.pattern}`;return`${X[j.format]??J.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${J.divisor}`;case"unrecognized_keys":return`Clé${J.keys.length>1?"s":""} non reconnue${J.keys.length>1?"s":""} : ${D(J.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${J.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${J.origin}`;default:return"Entrée invalide"}}};function ZX(){return{localeError:Rw()}}var Iw=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"number";case"object":{if(Array.isArray(J))return"array";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return(J)=>{switch(J.code){case"invalid_type":return`Entrée invalide : attendu ${J.expected}, reçu ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Entrée invalide : attendu ${P(J.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"≤":"<",Y=U(J.origin);if(Y)return`Trop grand : attendu que ${J.origin??"la valeur"} ait ${j}${J.maximum.toString()} ${Y.unit}`;return`Trop grand : attendu que ${J.origin??"la valeur"} soit ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?"≥":">",Y=U(J.origin);if(Y)return`Trop petit : attendu que ${J.origin} ait ${j}${J.minimum.toString()} ${Y.unit}`;return`Trop petit : attendu que ${J.origin} soit ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Chaîne invalide : doit commencer par "${j.prefix}"`;if(j.format==="ends_with")return`Chaîne invalide : doit se terminer par "${j.suffix}"`;if(j.format==="includes")return`Chaîne invalide : doit inclure "${j.includes}"`;if(j.format==="regex")return`Chaîne invalide : doit correspondre au motif ${j.pattern}`;return`${X[j.format]??J.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${J.divisor}`;case"unrecognized_keys":return`Clé${J.keys.length>1?"s":""} non reconnue${J.keys.length>1?"s":""} : ${D(J.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${J.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${J.origin}`;default:return"Entrée invalide"}}};function TX(){return{localeError:Iw()}}var Sw=()=>{let $={string:{unit:"אותיות",verb:"לכלול"},file:{unit:"בייטים",verb:"לכלול"},array:{unit:"פריטים",verb:"לכלול"},set:{unit:"פריטים",verb:"לכלול"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"number";case"object":{if(Array.isArray(J))return"array";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"קלט",email:"כתובת אימייל",url:"כתובת רשת",emoji:"אימוג'י",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"תאריך וזמן ISO",date:"תאריך ISO",time:"זמן ISO",duration:"משך זמן ISO",ipv4:"כתובת IPv4",ipv6:"כתובת IPv6",cidrv4:"טווח IPv4",cidrv6:"טווח IPv6",base64:"מחרוזת בבסיס 64",base64url:"מחרוזת בבסיס 64 לכתובות רשת",json_string:"מחרוזת JSON",e164:"מספר E.164",jwt:"JWT",template_literal:"קלט"};return(J)=>{switch(J.code){case"invalid_type":return`קלט לא תקין: צריך ${J.expected}, התקבל ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`קלט לא תקין: צריך ${P(J.values[0])}`;return`קלט לא תקין: צריך אחת מהאפשרויות ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`גדול מדי: ${J.origin??"value"} צריך להיות ${j}${J.maximum.toString()} ${Y.unit??"elements"}`;return`גדול מדי: ${J.origin??"value"} צריך להיות ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`קטן מדי: ${J.origin} צריך להיות ${j}${J.minimum.toString()} ${Y.unit}`;return`קטן מדי: ${J.origin} צריך להיות ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`מחרוזת לא תקינה: חייבת להתחיל ב"${j.prefix}"`;if(j.format==="ends_with")return`מחרוזת לא תקינה: חייבת להסתיים ב "${j.suffix}"`;if(j.format==="includes")return`מחרוזת לא תקינה: חייבת לכלול "${j.includes}"`;if(j.format==="regex")return`מחרוזת לא תקינה: חייבת להתאים לתבנית ${j.pattern}`;return`${X[j.format]??J.format} לא תקין`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${J.divisor}`;case"unrecognized_keys":return`מפתח${J.keys.length>1?"ות":""} לא מזוה${J.keys.length>1?"ים":"ה"}: ${D(J.keys,", ")}`;case"invalid_key":return`מפתח לא תקין ב${J.origin}`;case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${J.origin}`;default:return"קלט לא תקין"}}};function gX(){return{localeError:Sw()}}var kw=()=>{let $={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"szám";case"object":{if(Array.isArray(J))return"tömb";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"};return(J)=>{switch(J.code){case"invalid_type":return`Érvénytelen bemenet: a várt érték ${J.expected}, a kapott érték ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Érvénytelen bemenet: a várt érték ${P(J.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Túl nagy: ${J.origin??"érték"} mérete túl nagy ${j}${J.maximum.toString()} ${Y.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${J.origin??"érték"} túl nagy: ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Túl kicsi: a bemeneti érték ${J.origin} mérete túl kicsi ${j}${J.minimum.toString()} ${Y.unit}`;return`Túl kicsi: a bemeneti érték ${J.origin} túl kicsi ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Érvénytelen string: "${j.prefix}" értékkel kell kezdődnie`;if(j.format==="ends_with")return`Érvénytelen string: "${j.suffix}" értékkel kell végződnie`;if(j.format==="includes")return`Érvénytelen string: "${j.includes}" értéket kell tartalmaznia`;if(j.format==="regex")return`Érvénytelen string: ${j.pattern} mintának kell megfelelnie`;return`Érvénytelen ${X[j.format]??J.format}`}case"not_multiple_of":return`Érvénytelen szám: ${J.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${J.keys.length>1?"s":""}: ${D(J.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${J.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${J.origin}`;default:return"Érvénytelen bemenet"}}};function xX(){return{localeError:kw()}}var Cw=()=>{let $={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"number";case"object":{if(Array.isArray(J))return"array";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return(J)=>{switch(J.code){case"invalid_type":return`Input tidak valid: diharapkan ${J.expected}, diterima ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Input tidak valid: diharapkan ${P(J.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Terlalu besar: diharapkan ${J.origin??"value"} memiliki ${j}${J.maximum.toString()} ${Y.unit??"elemen"}`;return`Terlalu besar: diharapkan ${J.origin??"value"} menjadi ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Terlalu kecil: diharapkan ${J.origin} memiliki ${j}${J.minimum.toString()} ${Y.unit}`;return`Terlalu kecil: diharapkan ${J.origin} menjadi ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`String tidak valid: harus dimulai dengan "${j.prefix}"`;if(j.format==="ends_with")return`String tidak valid: harus berakhir dengan "${j.suffix}"`;if(j.format==="includes")return`String tidak valid: harus menyertakan "${j.includes}"`;if(j.format==="regex")return`String tidak valid: harus sesuai pola ${j.pattern}`;return`${X[j.format]??J.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${J.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${J.keys.length>1?"s":""}: ${D(J.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${J.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${J.origin}`;default:return"Input tidak valid"}}};function fX(){return{localeError:Cw()}}var Zw=($)=>{let U=typeof $;switch(U){case"number":return Number.isNaN($)?"NaN":"númer";case"object":{if(Array.isArray($))return"fylki";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return U},Tw=()=>{let $={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function U(X){return $[X]??null}let z={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"};return(X)=>{switch(X.code){case"invalid_type":return`Rangt gildi: Þú slóst inn ${Zw(X.input)} þar sem á að vera ${X.expected}`;case"invalid_value":if(X.values.length===1)return`Rangt gildi: gert ráð fyrir ${P(X.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${D(X.values,"|")}`;case"too_big":{let J=X.inclusive?"<=":"<",j=U(X.origin);if(j)return`Of stórt: gert er ráð fyrir að ${X.origin??"gildi"} hafi ${J}${X.maximum.toString()} ${j.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${X.origin??"gildi"} sé ${J}${X.maximum.toString()}`}case"too_small":{let J=X.inclusive?">=":">",j=U(X.origin);if(j)return`Of lítið: gert er ráð fyrir að ${X.origin} hafi ${J}${X.minimum.toString()} ${j.unit}`;return`Of lítið: gert er ráð fyrir að ${X.origin} sé ${J}${X.minimum.toString()}`}case"invalid_format":{let J=X;if(J.format==="starts_with")return`Ógildur strengur: verður að byrja á "${J.prefix}"`;if(J.format==="ends_with")return`Ógildur strengur: verður að enda á "${J.suffix}"`;if(J.format==="includes")return`Ógildur strengur: verður að innihalda "${J.includes}"`;if(J.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${J.pattern}`;return`Rangt ${z[J.format]??X.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${X.divisor}`;case"unrecognized_keys":return`Óþekkt ${X.keys.length>1?"ir lyklar":"ur lykill"}: ${D(X.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${X.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${X.origin}`;default:return"Rangt gildi"}}};function hX(){return{localeError:Tw()}}var gw=()=>{let $={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"numero";case"object":{if(Array.isArray(J))return"vettore";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return(J)=>{switch(J.code){case"invalid_type":return`Input non valido: atteso ${J.expected}, ricevuto ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Input non valido: atteso ${P(J.values[0])}`;return`Opzione non valida: atteso uno tra ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Troppo grande: ${J.origin??"valore"} deve avere ${j}${J.maximum.toString()} ${Y.unit??"elementi"}`;return`Troppo grande: ${J.origin??"valore"} deve essere ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Troppo piccolo: ${J.origin} deve avere ${j}${J.minimum.toString()} ${Y.unit}`;return`Troppo piccolo: ${J.origin} deve essere ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Stringa non valida: deve iniziare con "${j.prefix}"`;if(j.format==="ends_with")return`Stringa non valida: deve terminare con "${j.suffix}"`;if(j.format==="includes")return`Stringa non valida: deve includere "${j.includes}"`;if(j.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${j.pattern}`;return`Invalid ${X[j.format]??J.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${J.divisor}`;case"unrecognized_keys":return`Chiav${J.keys.length>1?"i":"e"} non riconosciut${J.keys.length>1?"e":"a"}: ${D(J.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${J.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${J.origin}`;default:return"Input non valido"}}};function yX(){return{localeError:gw()}}var xw=()=>{let $={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"数値";case"object":{if(Array.isArray(J))return"配列";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"};return(J)=>{switch(J.code){case"invalid_type":return`無効な入力: ${J.expected}が期待されましたが、${z(J.input)}が入力されました`;case"invalid_value":if(J.values.length===1)return`無効な入力: ${P(J.values[0])}が期待されました`;return`無効な選択: ${D(J.values,"、")}のいずれかである必要があります`;case"too_big":{let j=J.inclusive?"以下である":"より小さい",Y=U(J.origin);if(Y)return`大きすぎる値: ${J.origin??"値"}は${J.maximum.toString()}${Y.unit??"要素"}${j}必要があります`;return`大きすぎる値: ${J.origin??"値"}は${J.maximum.toString()}${j}必要があります`}case"too_small":{let j=J.inclusive?"以上である":"より大きい",Y=U(J.origin);if(Y)return`小さすぎる値: ${J.origin}は${J.minimum.toString()}${Y.unit}${j}必要があります`;return`小さすぎる値: ${J.origin}は${J.minimum.toString()}${j}必要があります`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`無効な文字列: "${j.prefix}"で始まる必要があります`;if(j.format==="ends_with")return`無効な文字列: "${j.suffix}"で終わる必要があります`;if(j.format==="includes")return`無効な文字列: "${j.includes}"を含む必要があります`;if(j.format==="regex")return`無効な文字列: パターン${j.pattern}に一致する必要があります`;return`無効な${X[j.format]??J.format}`}case"not_multiple_of":return`無効な数値: ${J.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${J.keys.length>1?"群":""}: ${D(J.keys,"、")}`;case"invalid_key":return`${J.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${J.origin}内の無効な値`;default:return"無効な入力"}}};function cX(){return{localeError:xw()}}var fw=($)=>{let U=typeof $;switch(U){case"number":return Number.isNaN($)?"NaN":"რიცხვი";case"object":{if(Array.isArray($))return"მასივი";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return{string:"სტრინგი",boolean:"ბულეანი",undefined:"undefined",bigint:"bigint",symbol:"symbol",function:"ფუნქცია"}[U]??U},hw=()=>{let $={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function U(X){return $[X]??null}let z={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული სტრინგი",base64url:"base64url-კოდირებული სტრინგი",json_string:"JSON სტრინგი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"};return(X)=>{switch(X.code){case"invalid_type":return`არასწორი შეყვანა: მოსალოდნელი ${X.expected}, მიღებული ${fw(X.input)}`;case"invalid_value":if(X.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${P(X.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${D(X.values,"|")}-დან`;case"too_big":{let J=X.inclusive?"<=":"<",j=U(X.origin);if(j)return`ზედმეტად დიდი: მოსალოდნელი ${X.origin??"მნიშვნელობა"} ${j.verb} ${J}${X.maximum.toString()} ${j.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${X.origin??"მნიშვნელობა"} იყოს ${J}${X.maximum.toString()}`}case"too_small":{let J=X.inclusive?">=":">",j=U(X.origin);if(j)return`ზედმეტად პატარა: მოსალოდნელი ${X.origin} ${j.verb} ${J}${X.minimum.toString()} ${j.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${X.origin} იყოს ${J}${X.minimum.toString()}`}case"invalid_format":{let J=X;if(J.format==="starts_with")return`არასწორი სტრინგი: უნდა იწყებოდეს "${J.prefix}"-ით`;if(J.format==="ends_with")return`არასწორი სტრინგი: უნდა მთავრდებოდეს "${J.suffix}"-ით`;if(J.format==="includes")return`არასწორი სტრინგი: უნდა შეიცავდეს "${J.includes}"-ს`;if(J.format==="regex")return`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${J.pattern}`;return`არასწორი ${z[J.format]??X.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${X.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${X.keys.length>1?"ები":"ი"}: ${D(X.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${X.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${X.origin}-ში`;default:return"არასწორი შეყვანა"}}};function mX(){return{localeError:hw()}}var yw=()=>{let $={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"មិនមែនជាលេខ (NaN)":"លេខ";case"object":{if(Array.isArray(J))return"អារេ (Array)";if(J===null)return"គ្មានតម្លៃ (null)";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"};return(J)=>{switch(J.code){case"invalid_type":return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${J.expected} ប៉ុន្តែទទួលបាន ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${P(J.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`ធំពេក៖ ត្រូវការ ${J.origin??"តម្លៃ"} ${j} ${J.maximum.toString()} ${Y.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${J.origin??"តម្លៃ"} ${j} ${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`តូចពេក៖ ត្រូវការ ${J.origin} ${j} ${J.minimum.toString()} ${Y.unit}`;return`តូចពេក៖ ត្រូវការ ${J.origin} ${j} ${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${j.prefix}"`;if(j.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${j.suffix}"`;if(j.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${j.includes}"`;if(j.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${j.pattern}`;return`មិនត្រឹមត្រូវ៖ ${X[j.format]??J.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${J.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${D(J.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${J.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${J.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function t4(){return{localeError:yw()}}function uX(){return t4()}var cw=()=>{let $={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"number";case"object":{if(Array.isArray(J))return"array";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"};return(J)=>{switch(J.code){case"invalid_type":return`잘못된 입력: 예상 타입은 ${J.expected}, 받은 타입은 ${z(J.input)}입니다`;case"invalid_value":if(J.values.length===1)return`잘못된 입력: 값은 ${P(J.values[0])} 이어야 합니다`;return`잘못된 옵션: ${D(J.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let j=J.inclusive?"이하":"미만",Y=j==="미만"?"이어야 합니다":"여야 합니다",N=U(J.origin),W=N?.unit??"요소";if(N)return`${J.origin??"값"}이 너무 큽니다: ${J.maximum.toString()}${W} ${j}${Y}`;return`${J.origin??"값"}이 너무 큽니다: ${J.maximum.toString()} ${j}${Y}`}case"too_small":{let j=J.inclusive?"이상":"초과",Y=j==="이상"?"이어야 합니다":"여야 합니다",N=U(J.origin),W=N?.unit??"요소";if(N)return`${J.origin??"값"}이 너무 작습니다: ${J.minimum.toString()}${W} ${j}${Y}`;return`${J.origin??"값"}이 너무 작습니다: ${J.minimum.toString()} ${j}${Y}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`잘못된 문자열: "${j.prefix}"(으)로 시작해야 합니다`;if(j.format==="ends_with")return`잘못된 문자열: "${j.suffix}"(으)로 끝나야 합니다`;if(j.format==="includes")return`잘못된 문자열: "${j.includes}"을(를) 포함해야 합니다`;if(j.format==="regex")return`잘못된 문자열: 정규식 ${j.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${X[j.format]??J.format}`}case"not_multiple_of":return`잘못된 숫자: ${J.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${D(J.keys,", ")}`;case"invalid_key":return`잘못된 키: ${J.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${J.origin}`;default:return"잘못된 입력"}}};function iX(){return{localeError:cw()}}var mw=($)=>{return s4(typeof $,$)},s4=($,U=void 0)=>{switch($){case"number":return Number.isNaN(U)?"NaN":"skaičius";case"bigint":return"sveikasis skaičius";case"string":return"eilutė";case"boolean":return"loginė reikšmė";case"undefined":case"void":return"neapibrėžta reikšmė";case"function":return"funkcija";case"symbol":return"simbolis";case"object":{if(U===void 0)return"nežinomas objektas";if(U===null)return"nulinė reikšmė";if(Array.isArray(U))return"masyvas";if(Object.getPrototypeOf(U)!==Object.prototype&&U.constructor)return U.constructor.name;return"objektas"}case"null":return"nulinė reikšmė"}return $},a4=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)};function r9($){let U=Math.abs($),z=U%10,X=U%100;if(X>=11&&X<=19||z===0)return"many";if(z===1)return"one";return"few"}var uw=()=>{let $={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function U(X,J,j,Y){let N=$[X]??null;if(N===null)return N;return{unit:N.unit[J],verb:N.verb[Y][j?"inclusive":"notInclusive"]}}let z={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"};return(X)=>{switch(X.code){case"invalid_type":return`Gautas tipas ${mw(X.input)}, o tikėtasi - ${s4(X.expected)}`;case"invalid_value":if(X.values.length===1)return`Privalo būti ${P(X.values[0])}`;return`Privalo būti vienas iš ${D(X.values,"|")} pasirinkimų`;case"too_big":{let J=s4(X.origin),j=U(X.origin,r9(Number(X.maximum)),X.inclusive??!1,"smaller");if(j?.verb)return`${a4(J??X.origin??"reikšmė")} ${j.verb} ${X.maximum.toString()} ${j.unit??"elementų"}`;let Y=X.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${a4(J??X.origin??"reikšmė")} turi būti ${Y} ${X.maximum.toString()} ${j?.unit}`}case"too_small":{let J=s4(X.origin),j=U(X.origin,r9(Number(X.minimum)),X.inclusive??!1,"bigger");if(j?.verb)return`${a4(J??X.origin??"reikšmė")} ${j.verb} ${X.minimum.toString()} ${j.unit??"elementų"}`;let Y=X.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${a4(J??X.origin??"reikšmė")} turi būti ${Y} ${X.minimum.toString()} ${j?.unit}`}case"invalid_format":{let J=X;if(J.format==="starts_with")return`Eilutė privalo prasidėti "${J.prefix}"`;if(J.format==="ends_with")return`Eilutė privalo pasibaigti "${J.suffix}"`;if(J.format==="includes")return`Eilutė privalo įtraukti "${J.includes}"`;if(J.format==="regex")return`Eilutė privalo atitikti ${J.pattern}`;return`Neteisingas ${z[J.format]??X.format}`}case"not_multiple_of":return`Skaičius privalo būti ${X.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${X.keys.length>1?"i":"as"} rakt${X.keys.length>1?"ai":"as"}: ${D(X.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let J=s4(X.origin);return`${a4(J??X.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function lX(){return{localeError:uw()}}var iw=()=>{let $={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"број";case"object":{if(Array.isArray(J))return"низа";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"};return(J)=>{switch(J.code){case"invalid_type":return`Грешен внес: се очекува ${J.expected}, примено ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Invalid input: expected ${P(J.values[0])}`;return`Грешана опција: се очекува една ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Премногу голем: се очекува ${J.origin??"вредноста"} да има ${j}${J.maximum.toString()} ${Y.unit??"елементи"}`;return`Премногу голем: се очекува ${J.origin??"вредноста"} да биде ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Премногу мал: се очекува ${J.origin} да има ${j}${J.minimum.toString()} ${Y.unit}`;return`Премногу мал: се очекува ${J.origin} да биде ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Неважечка низа: мора да започнува со "${j.prefix}"`;if(j.format==="ends_with")return`Неважечка низа: мора да завршува со "${j.suffix}"`;if(j.format==="includes")return`Неважечка низа: мора да вклучува "${j.includes}"`;if(j.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${j.pattern}`;return`Invalid ${X[j.format]??J.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${J.divisor}`;case"unrecognized_keys":return`${J.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${D(J.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${J.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${J.origin}`;default:return"Грешен внес"}}};function nX(){return{localeError:iw()}}var lw=()=>{let $={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"nombor";case"object":{if(Array.isArray(J))return"array";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return(J)=>{switch(J.code){case"invalid_type":return`Input tidak sah: dijangka ${J.expected}, diterima ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Input tidak sah: dijangka ${P(J.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Terlalu besar: dijangka ${J.origin??"nilai"} ${Y.verb} ${j}${J.maximum.toString()} ${Y.unit??"elemen"}`;return`Terlalu besar: dijangka ${J.origin??"nilai"} adalah ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Terlalu kecil: dijangka ${J.origin} ${Y.verb} ${j}${J.minimum.toString()} ${Y.unit}`;return`Terlalu kecil: dijangka ${J.origin} adalah ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`String tidak sah: mesti bermula dengan "${j.prefix}"`;if(j.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${j.suffix}"`;if(j.format==="includes")return`String tidak sah: mesti mengandungi "${j.includes}"`;if(j.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${j.pattern}`;return`${X[j.format]??J.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${J.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${D(J.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${J.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${J.origin}`;default:return"Input tidak sah"}}};function rX(){return{localeError:lw()}}var nw=()=>{let $={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"getal";case"object":{if(Array.isArray(J))return"array";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return(J)=>{switch(J.code){case"invalid_type":return`Ongeldige invoer: verwacht ${J.expected}, ontving ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Ongeldige invoer: verwacht ${P(J.values[0])}`;return`Ongeldige optie: verwacht één van ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Te lang: verwacht dat ${J.origin??"waarde"} ${j}${J.maximum.toString()} ${Y.unit??"elementen"} bevat`;return`Te lang: verwacht dat ${J.origin??"waarde"} ${j}${J.maximum.toString()} is`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Te kort: verwacht dat ${J.origin} ${j}${J.minimum.toString()} ${Y.unit} bevat`;return`Te kort: verwacht dat ${J.origin} ${j}${J.minimum.toString()} is`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Ongeldige tekst: moet met "${j.prefix}" beginnen`;if(j.format==="ends_with")return`Ongeldige tekst: moet op "${j.suffix}" eindigen`;if(j.format==="includes")return`Ongeldige tekst: moet "${j.includes}" bevatten`;if(j.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${j.pattern}`;return`Ongeldig: ${X[j.format]??J.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${J.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${J.keys.length>1?"s":""}: ${D(J.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${J.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${J.origin}`;default:return"Ongeldige invoer"}}};function pX(){return{localeError:nw()}}var rw=()=>{let $={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"tall";case"object":{if(Array.isArray(J))return"liste";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return(J)=>{switch(J.code){case"invalid_type":return`Ugyldig input: forventet ${J.expected}, fikk ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Ugyldig verdi: forventet ${P(J.values[0])}`;return`Ugyldig valg: forventet en av ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`For stor(t): forventet ${J.origin??"value"} til å ha ${j}${J.maximum.toString()} ${Y.unit??"elementer"}`;return`For stor(t): forventet ${J.origin??"value"} til å ha ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`For lite(n): forventet ${J.origin} til å ha ${j}${J.minimum.toString()} ${Y.unit}`;return`For lite(n): forventet ${J.origin} til å ha ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Ugyldig streng: må starte med "${j.prefix}"`;if(j.format==="ends_with")return`Ugyldig streng: må ende med "${j.suffix}"`;if(j.format==="includes")return`Ugyldig streng: må inneholde "${j.includes}"`;if(j.format==="regex")return`Ugyldig streng: må matche mønsteret ${j.pattern}`;return`Ugyldig ${X[j.format]??J.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${J.divisor}`;case"unrecognized_keys":return`${J.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${D(J.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${J.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${J.origin}`;default:return"Ugyldig input"}}};function dX(){return{localeError:rw()}}var pw=()=>{let $={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"numara";case"object":{if(Array.isArray(J))return"saf";if(J===null)return"gayb";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"};return(J)=>{switch(J.code){case"invalid_type":return`Fâsit giren: umulan ${J.expected}, alınan ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Fâsit giren: umulan ${P(J.values[0])}`;return`Fâsit tercih: mûteberler ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Fazla büyük: ${J.origin??"value"}, ${j}${J.maximum.toString()} ${Y.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${J.origin??"value"}, ${j}${J.maximum.toString()} olmalıydı.`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Fazla küçük: ${J.origin}, ${j}${J.minimum.toString()} ${Y.unit} sahip olmalıydı.`;return`Fazla küçük: ${J.origin}, ${j}${J.minimum.toString()} olmalıydı.`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Fâsit metin: "${j.prefix}" ile başlamalı.`;if(j.format==="ends_with")return`Fâsit metin: "${j.suffix}" ile bitmeli.`;if(j.format==="includes")return`Fâsit metin: "${j.includes}" ihtivâ etmeli.`;if(j.format==="regex")return`Fâsit metin: ${j.pattern} nakşına uymalı.`;return`Fâsit ${X[j.format]??J.format}`}case"not_multiple_of":return`Fâsit sayı: ${J.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${J.keys.length>1?"s":""}: ${D(J.keys,", ")}`;case"invalid_key":return`${J.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${J.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function oX(){return{localeError:pw()}}var dw=()=>{let $={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"عدد";case"object":{if(Array.isArray(J))return"ارې";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"};return(J)=>{switch(J.code){case"invalid_type":return`ناسم ورودي: باید ${J.expected} وای, مګر ${z(J.input)} ترلاسه شو`;case"invalid_value":if(J.values.length===1)return`ناسم ورودي: باید ${P(J.values[0])} وای`;return`ناسم انتخاب: باید یو له ${D(J.values,"|")} څخه وای`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`ډیر لوی: ${J.origin??"ارزښت"} باید ${j}${J.maximum.toString()} ${Y.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${J.origin??"ارزښت"} باید ${j}${J.maximum.toString()} وي`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`ډیر کوچنی: ${J.origin} باید ${j}${J.minimum.toString()} ${Y.unit} ولري`;return`ډیر کوچنی: ${J.origin} باید ${j}${J.minimum.toString()} وي`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`ناسم متن: باید د "${j.prefix}" سره پیل شي`;if(j.format==="ends_with")return`ناسم متن: باید د "${j.suffix}" سره پای ته ورسيږي`;if(j.format==="includes")return`ناسم متن: باید "${j.includes}" ولري`;if(j.format==="regex")return`ناسم متن: باید د ${j.pattern} سره مطابقت ولري`;return`${X[j.format]??J.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${J.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${J.keys.length>1?"کلیډونه":"کلیډ"}: ${D(J.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${J.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${J.origin} کې`;default:return"ناسمه ورودي"}}};function tX(){return{localeError:dw()}}var ow=()=>{let $={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"liczba";case"object":{if(Array.isArray(J))return"tablica";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"};return(J)=>{switch(J.code){case"invalid_type":return`Nieprawidłowe dane wejściowe: oczekiwano ${J.expected}, otrzymano ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${P(J.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Za duża wartość: oczekiwano, że ${J.origin??"wartość"} będzie mieć ${j}${J.maximum.toString()} ${Y.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${J.origin??"wartość"} będzie wynosić ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Za mała wartość: oczekiwano, że ${J.origin??"wartość"} będzie mieć ${j}${J.minimum.toString()} ${Y.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${J.origin??"wartość"} będzie wynosić ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${j.prefix}"`;if(j.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${j.suffix}"`;if(j.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${j.includes}"`;if(j.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${j.pattern}`;return`Nieprawidłow(y/a/e) ${X[j.format]??J.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${J.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${J.keys.length>1?"s":""}: ${D(J.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${J.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${J.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function aX(){return{localeError:ow()}}var tw=()=>{let $={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"número";case"object":{if(Array.isArray(J))return"array";if(J===null)return"nulo";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return(J)=>{switch(J.code){case"invalid_type":return`Tipo inválido: esperado ${J.expected}, recebido ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Entrada inválida: esperado ${P(J.values[0])}`;return`Opção inválida: esperada uma das ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Muito grande: esperado que ${J.origin??"valor"} tivesse ${j}${J.maximum.toString()} ${Y.unit??"elementos"}`;return`Muito grande: esperado que ${J.origin??"valor"} fosse ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Muito pequeno: esperado que ${J.origin} tivesse ${j}${J.minimum.toString()} ${Y.unit}`;return`Muito pequeno: esperado que ${J.origin} fosse ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Texto inválido: deve começar com "${j.prefix}"`;if(j.format==="ends_with")return`Texto inválido: deve terminar com "${j.suffix}"`;if(j.format==="includes")return`Texto inválido: deve incluir "${j.includes}"`;if(j.format==="regex")return`Texto inválido: deve corresponder ao padrão ${j.pattern}`;return`${X[j.format]??J.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${J.divisor}`;case"unrecognized_keys":return`Chave${J.keys.length>1?"s":""} desconhecida${J.keys.length>1?"s":""}: ${D(J.keys,", ")}`;case"invalid_key":return`Chave inválida em ${J.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${J.origin}`;default:return"Campo inválido"}}};function sX(){return{localeError:tw()}}function p9($,U,z,X){let J=Math.abs($),j=J%10,Y=J%100;if(Y>=11&&Y<=19)return X;if(j===1)return U;if(j>=2&&j<=4)return z;return X}var aw=()=>{let $={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"число";case"object":{if(Array.isArray(J))return"массив";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"};return(J)=>{switch(J.code){case"invalid_type":return`Неверный ввод: ожидалось ${J.expected}, получено ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Неверный ввод: ожидалось ${P(J.values[0])}`;return`Неверный вариант: ожидалось одно из ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y){let N=Number(J.maximum),W=p9(N,Y.unit.one,Y.unit.few,Y.unit.many);return`Слишком большое значение: ожидалось, что ${J.origin??"значение"} будет иметь ${j}${J.maximum.toString()} ${W}`}return`Слишком большое значение: ожидалось, что ${J.origin??"значение"} будет ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y){let N=Number(J.minimum),W=p9(N,Y.unit.one,Y.unit.few,Y.unit.many);return`Слишком маленькое значение: ожидалось, что ${J.origin} будет иметь ${j}${J.minimum.toString()} ${W}`}return`Слишком маленькое значение: ожидалось, что ${J.origin} будет ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Неверная строка: должна начинаться с "${j.prefix}"`;if(j.format==="ends_with")return`Неверная строка: должна заканчиваться на "${j.suffix}"`;if(j.format==="includes")return`Неверная строка: должна содержать "${j.includes}"`;if(j.format==="regex")return`Неверная строка: должна соответствовать шаблону ${j.pattern}`;return`Неверный ${X[j.format]??J.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${J.divisor}`;case"unrecognized_keys":return`Нераспознанн${J.keys.length>1?"ые":"ый"} ключ${J.keys.length>1?"и":""}: ${D(J.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${J.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${J.origin}`;default:return"Неверные входные данные"}}};function eX(){return{localeError:aw()}}var sw=()=>{let $={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"število";case"object":{if(Array.isArray(J))return"tabela";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"};return(J)=>{switch(J.code){case"invalid_type":return`Neveljaven vnos: pričakovano ${J.expected}, prejeto ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Neveljaven vnos: pričakovano ${P(J.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Preveliko: pričakovano, da bo ${J.origin??"vrednost"} imelo ${j}${J.maximum.toString()} ${Y.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${J.origin??"vrednost"} ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Premajhno: pričakovano, da bo ${J.origin} imelo ${j}${J.minimum.toString()} ${Y.unit}`;return`Premajhno: pričakovano, da bo ${J.origin} ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Neveljaven niz: mora se začeti z "${j.prefix}"`;if(j.format==="ends_with")return`Neveljaven niz: mora se končati z "${j.suffix}"`;if(j.format==="includes")return`Neveljaven niz: mora vsebovati "${j.includes}"`;if(j.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${j.pattern}`;return`Neveljaven ${X[j.format]??J.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${J.divisor}`;case"unrecognized_keys":return`Neprepoznan${J.keys.length>1?"i ključi":" ključ"}: ${D(J.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${J.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${J.origin}`;default:return"Neveljaven vnos"}}};function $j(){return{localeError:sw()}}var ew=()=>{let $={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"antal";case"object":{if(Array.isArray(J))return"lista";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return(J)=>{switch(J.code){case"invalid_type":return`Ogiltig inmatning: förväntat ${J.expected}, fick ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Ogiltig inmatning: förväntat ${P(J.values[0])}`;return`Ogiltigt val: förväntade en av ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`För stor(t): förväntade ${J.origin??"värdet"} att ha ${j}${J.maximum.toString()} ${Y.unit??"element"}`;return`För stor(t): förväntat ${J.origin??"värdet"} att ha ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`För lite(t): förväntade ${J.origin??"värdet"} att ha ${j}${J.minimum.toString()} ${Y.unit}`;return`För lite(t): förväntade ${J.origin??"värdet"} att ha ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Ogiltig sträng: måste börja med "${j.prefix}"`;if(j.format==="ends_with")return`Ogiltig sträng: måste sluta med "${j.suffix}"`;if(j.format==="includes")return`Ogiltig sträng: måste innehålla "${j.includes}"`;if(j.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${j.pattern}"`;return`Ogiltig(t) ${X[j.format]??J.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${J.divisor}`;case"unrecognized_keys":return`${J.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${D(J.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${J.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${J.origin??"värdet"}`;default:return"Ogiltig input"}}};function Uj(){return{localeError:ew()}}var $7=()=>{let $={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"எண் அல்லாதது":"எண்";case"object":{if(Array.isArray(J))return"அணி";if(J===null)return"வெறுமை";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"};return(J)=>{switch(J.code){case"invalid_type":return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${J.expected}, பெறப்பட்டது ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${P(J.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${D(J.values,"|")} இல் ஒன்று`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${J.origin??"மதிப்பு"} ${j}${J.maximum.toString()} ${Y.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${J.origin??"மதிப்பு"} ${j}${J.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${J.origin} ${j}${J.minimum.toString()} ${Y.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${J.origin} ${j}${J.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`தவறான சரம்: "${j.prefix}" இல் தொடங்க வேண்டும்`;if(j.format==="ends_with")return`தவறான சரம்: "${j.suffix}" இல் முடிவடைய வேண்டும்`;if(j.format==="includes")return`தவறான சரம்: "${j.includes}" ஐ உள்ளடக்க வேண்டும்`;if(j.format==="regex")return`தவறான சரம்: ${j.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${X[j.format]??J.format}`}case"not_multiple_of":return`தவறான எண்: ${J.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${J.keys.length>1?"கள்":""}: ${D(J.keys,", ")}`;case"invalid_key":return`${J.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${J.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function Jj(){return{localeError:$7()}}var U7=()=>{let $={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"ไม่ใช่ตัวเลข (NaN)":"ตัวเลข";case"object":{if(Array.isArray(J))return"อาร์เรย์ (Array)";if(J===null)return"ไม่มีค่า (null)";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"};return(J)=>{switch(J.code){case"invalid_type":return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${J.expected} แต่ได้รับ ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${P(J.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"ไม่เกิน":"น้อยกว่า",Y=U(J.origin);if(Y)return`เกินกำหนด: ${J.origin??"ค่า"} ควรมี${j} ${J.maximum.toString()} ${Y.unit??"รายการ"}`;return`เกินกำหนด: ${J.origin??"ค่า"} ควรมี${j} ${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?"อย่างน้อย":"มากกว่า",Y=U(J.origin);if(Y)return`น้อยกว่ากำหนด: ${J.origin} ควรมี${j} ${J.minimum.toString()} ${Y.unit}`;return`น้อยกว่ากำหนด: ${J.origin} ควรมี${j} ${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${j.prefix}"`;if(j.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${j.suffix}"`;if(j.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${j.includes}" อยู่ในข้อความ`;if(j.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${j.pattern}`;return`รูปแบบไม่ถูกต้อง: ${X[j.format]??J.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${J.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${D(J.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${J.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${J.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function zj(){return{localeError:U7()}}var J7=($)=>{let U=typeof $;switch(U){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return U},z7=()=>{let $={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function U(X){return $[X]??null}let z={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"};return(X)=>{switch(X.code){case"invalid_type":return`Geçersiz değer: beklenen ${X.expected}, alınan ${J7(X.input)}`;case"invalid_value":if(X.values.length===1)return`Geçersiz değer: beklenen ${P(X.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${D(X.values,"|")}`;case"too_big":{let J=X.inclusive?"<=":"<",j=U(X.origin);if(j)return`Çok büyük: beklenen ${X.origin??"değer"} ${J}${X.maximum.toString()} ${j.unit??"öğe"}`;return`Çok büyük: beklenen ${X.origin??"değer"} ${J}${X.maximum.toString()}`}case"too_small":{let J=X.inclusive?">=":">",j=U(X.origin);if(j)return`Çok küçük: beklenen ${X.origin} ${J}${X.minimum.toString()} ${j.unit}`;return`Çok küçük: beklenen ${X.origin} ${J}${X.minimum.toString()}`}case"invalid_format":{let J=X;if(J.format==="starts_with")return`Geçersiz metin: "${J.prefix}" ile başlamalı`;if(J.format==="ends_with")return`Geçersiz metin: "${J.suffix}" ile bitmeli`;if(J.format==="includes")return`Geçersiz metin: "${J.includes}" içermeli`;if(J.format==="regex")return`Geçersiz metin: ${J.pattern} desenine uymalı`;return`Geçersiz ${z[J.format]??X.format}`}case"not_multiple_of":return`Geçersiz sayı: ${X.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${X.keys.length>1?"lar":""}: ${D(X.keys,", ")}`;case"invalid_key":return`${X.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${X.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function Xj(){return{localeError:z7()}}var X7=()=>{let $={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"число";case"object":{if(Array.isArray(J))return"масив";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"};return(J)=>{switch(J.code){case"invalid_type":return`Неправильні вхідні дані: очікується ${J.expected}, отримано ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Неправильні вхідні дані: очікується ${P(J.values[0])}`;return`Неправильна опція: очікується одне з ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Занадто велике: очікується, що ${J.origin??"значення"} ${Y.verb} ${j}${J.maximum.toString()} ${Y.unit??"елементів"}`;return`Занадто велике: очікується, що ${J.origin??"значення"} буде ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Занадто мале: очікується, що ${J.origin} ${Y.verb} ${j}${J.minimum.toString()} ${Y.unit}`;return`Занадто мале: очікується, що ${J.origin} буде ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Неправильний рядок: повинен починатися з "${j.prefix}"`;if(j.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${j.suffix}"`;if(j.format==="includes")return`Неправильний рядок: повинен містити "${j.includes}"`;if(j.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${j.pattern}`;return`Неправильний ${X[j.format]??J.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${J.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${J.keys.length>1?"і":""}: ${D(J.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${J.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${J.origin}`;default:return"Неправильні вхідні дані"}}};function e4(){return{localeError:X7()}}function jj(){return e4()}var j7=()=>{let $={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"نمبر";case"object":{if(Array.isArray(J))return"آرے";if(J===null)return"نل";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"};return(J)=>{switch(J.code){case"invalid_type":return`غلط ان پٹ: ${J.expected} متوقع تھا، ${z(J.input)} موصول ہوا`;case"invalid_value":if(J.values.length===1)return`غلط ان پٹ: ${P(J.values[0])} متوقع تھا`;return`غلط آپشن: ${D(J.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`بہت بڑا: ${J.origin??"ویلیو"} کے ${j}${J.maximum.toString()} ${Y.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${J.origin??"ویلیو"} کا ${j}${J.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`بہت چھوٹا: ${J.origin} کے ${j}${J.minimum.toString()} ${Y.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${J.origin} کا ${j}${J.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`غلط سٹرنگ: "${j.prefix}" سے شروع ہونا چاہیے`;if(j.format==="ends_with")return`غلط سٹرنگ: "${j.suffix}" پر ختم ہونا چاہیے`;if(j.format==="includes")return`غلط سٹرنگ: "${j.includes}" شامل ہونا چاہیے`;if(j.format==="regex")return`غلط سٹرنگ: پیٹرن ${j.pattern} سے میچ ہونا چاہیے`;return`غلط ${X[j.format]??J.format}`}case"not_multiple_of":return`غلط نمبر: ${J.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${J.keys.length>1?"ز":""}: ${D(J.keys,"، ")}`;case"invalid_key":return`${J.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${J.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function Yj(){return{localeError:j7()}}var Y7=()=>{let $={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"số";case"object":{if(Array.isArray(J))return"mảng";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"};return(J)=>{switch(J.code){case"invalid_type":return`Đầu vào không hợp lệ: mong đợi ${J.expected}, nhận được ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${P(J.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Quá lớn: mong đợi ${J.origin??"giá trị"} ${Y.verb} ${j}${J.maximum.toString()} ${Y.unit??"phần tử"}`;return`Quá lớn: mong đợi ${J.origin??"giá trị"} ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Quá nhỏ: mong đợi ${J.origin} ${Y.verb} ${j}${J.minimum.toString()} ${Y.unit}`;return`Quá nhỏ: mong đợi ${J.origin} ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${j.prefix}"`;if(j.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${j.suffix}"`;if(j.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${j.includes}"`;if(j.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${j.pattern}`;return`${X[j.format]??J.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${J.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${D(J.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${J.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${J.origin}`;default:return"Đầu vào không hợp lệ"}}};function Nj(){return{localeError:Y7()}}var N7=()=>{let $={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"非数字(NaN)":"数字";case"object":{if(Array.isArray(J))return"数组";if(J===null)return"空值(null)";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"};return(J)=>{switch(J.code){case"invalid_type":return`无效输入:期望 ${J.expected},实际接收 ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`无效输入:期望 ${P(J.values[0])}`;return`无效选项:期望以下之一 ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`数值过大:期望 ${J.origin??"值"} ${j}${J.maximum.toString()} ${Y.unit??"个元素"}`;return`数值过大:期望 ${J.origin??"值"} ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`数值过小:期望 ${J.origin} ${j}${J.minimum.toString()} ${Y.unit}`;return`数值过小:期望 ${J.origin} ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`无效字符串:必须以 "${j.prefix}" 开头`;if(j.format==="ends_with")return`无效字符串:必须以 "${j.suffix}" 结尾`;if(j.format==="includes")return`无效字符串:必须包含 "${j.includes}"`;if(j.format==="regex")return`无效字符串:必须满足正则表达式 ${j.pattern}`;return`无效${X[j.format]??J.format}`}case"not_multiple_of":return`无效数字:必须是 ${J.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${D(J.keys,", ")}`;case"invalid_key":return`${J.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${J.origin} 中包含无效值(value)`;default:return"无效输入"}}};function Oj(){return{localeError:N7()}}var O7=()=>{let $={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"number";case"object":{if(Array.isArray(J))return"array";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"};return(J)=>{switch(J.code){case"invalid_type":return`無效的輸入值:預期為 ${J.expected},但收到 ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`無效的輸入值:預期為 ${P(J.values[0])}`;return`無效的選項:預期為以下其中之一 ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`數值過大:預期 ${J.origin??"值"} 應為 ${j}${J.maximum.toString()} ${Y.unit??"個元素"}`;return`數值過大:預期 ${J.origin??"值"} 應為 ${j}${J.maximum.toString()}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`數值過小:預期 ${J.origin} 應為 ${j}${J.minimum.toString()} ${Y.unit}`;return`數值過小:預期 ${J.origin} 應為 ${j}${J.minimum.toString()}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`無效的字串:必須以 "${j.prefix}" 開頭`;if(j.format==="ends_with")return`無效的字串:必須以 "${j.suffix}" 結尾`;if(j.format==="includes")return`無效的字串:必須包含 "${j.includes}"`;if(j.format==="regex")return`無效的字串:必須符合格式 ${j.pattern}`;return`無效的 ${X[j.format]??J.format}`}case"not_multiple_of":return`無效的數字:必須為 ${J.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${J.keys.length>1?"們":""}:${D(J.keys,"、")}`;case"invalid_key":return`${J.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${J.origin} 中有無效的值`;default:return"無效的輸入值"}}};function Wj(){return{localeError:O7()}}var W7=()=>{let $={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function U(J){return $[J]??null}let z=(J)=>{let j=typeof J;switch(j){case"number":return Number.isNaN(J)?"NaN":"nọ́mbà";case"object":{if(Array.isArray(J))return"akopọ";if(J===null)return"null";if(Object.getPrototypeOf(J)!==Object.prototype&&J.constructor)return J.constructor.name}}return j},X={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"};return(J)=>{switch(J.code){case"invalid_type":return`Ìbáwọlé aṣìṣe: a ní láti fi ${J.expected}, àmọ̀ a rí ${z(J.input)}`;case"invalid_value":if(J.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${P(J.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${D(J.values,"|")}`;case"too_big":{let j=J.inclusive?"<=":"<",Y=U(J.origin);if(Y)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${J.origin??"iye"} ${Y.verb} ${j}${J.maximum} ${Y.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${j}${J.maximum}`}case"too_small":{let j=J.inclusive?">=":">",Y=U(J.origin);if(Y)return`Kéré ju: a ní láti jẹ́ pé ${J.origin} ${Y.verb} ${j}${J.minimum} ${Y.unit}`;return`Kéré ju: a ní láti jẹ́ ${j}${J.minimum}`}case"invalid_format":{let j=J;if(j.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${j.prefix}"`;if(j.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${j.suffix}"`;if(j.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${j.includes}"`;if(j.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${j.pattern}`;return`Aṣìṣe: ${X[j.format]??J.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${J.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${D(J.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${J.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${J.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function Gj(){return{localeError:W7()}}var Qj=Symbol("ZodOutput"),wj=Symbol("ZodInput");class U1{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,...U){let z=U[0];if(this._map.set($,z),z&&typeof z==="object"&&"id"in z){if(this._idmap.has(z.id))throw Error(`ID ${z.id} already exists in the registry`);this._idmap.set(z.id,$)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove($){let U=this._map.get($);if(U&&typeof U==="object"&&"id"in U)this._idmap.delete(U.id);return this._map.delete($),this}get($){let U=$._zod.parent;if(U){let z={...this.get(U)??{}};delete z.id;let X={...z,...this._map.get($)};return Object.keys(X).length?X:void 0}return this._map.get($)}has($){return this._map.has($)}}function bU(){return new U1}var U6=bU();function Hj($,U){return new $({type:"string",...A(U)})}function Vj($,U){return new $({type:"string",coerce:!0,...A(U)})}function RU($,U){return new $({type:"string",format:"email",check:"string_format",abort:!1,...A(U)})}function J1($,U){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...A(U)})}function IU($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...A(U)})}function SU($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(U)})}function kU($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(U)})}function CU($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(U)})}function z1($,U){return new $({type:"string",format:"url",check:"string_format",abort:!1,...A(U)})}function ZU($,U){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...A(U)})}function TU($,U){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(U)})}function gU($,U){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...A(U)})}function xU($,U){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(U)})}function fU($,U){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...A(U)})}function hU($,U){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...A(U)})}function yU($,U){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(U)})}function cU($,U){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(U)})}function mU($,U){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(U)})}function uU($,U){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(U)})}function iU($,U){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(U)})}function lU($,U){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...A(U)})}function nU($,U){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...A(U)})}function rU($,U){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...A(U)})}function pU($,U){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...A(U)})}var Lj={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Bj($,U){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(U)})}function Dj($,U){return new $({type:"string",format:"date",check:"string_format",...A(U)})}function Kj($,U){return new $({type:"string",format:"time",check:"string_format",precision:null,...A(U)})}function qj($,U){return new $({type:"string",format:"duration",check:"string_format",...A(U)})}function _j($,U){return new $({type:"number",checks:[],...A(U)})}function vj($,U){return new $({type:"number",coerce:!0,checks:[],...A(U)})}function Fj($,U){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...A(U)})}function Pj($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...A(U)})}function Aj($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...A(U)})}function Ej($,U){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...A(U)})}function Mj($,U){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...A(U)})}function bj($,U){return new $({type:"boolean",...A(U)})}function Rj($,U){return new $({type:"boolean",coerce:!0,...A(U)})}function Ij($,U){return new $({type:"bigint",...A(U)})}function Sj($,U){return new $({type:"bigint",coerce:!0,...A(U)})}function kj($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...A(U)})}function Cj($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...A(U)})}function Zj($,U){return new $({type:"symbol",...A(U)})}function Tj($,U){return new $({type:"undefined",...A(U)})}function gj($,U){return new $({type:"null",...A(U)})}function xj($){return new $({type:"any"})}function fj($){return new $({type:"unknown"})}function hj($,U){return new $({type:"never",...A(U)})}function yj($,U){return new $({type:"void",...A(U)})}function cj($,U){return new $({type:"date",...A(U)})}function mj($,U){return new $({type:"date",coerce:!0,...A(U)})}function uj($,U){return new $({type:"nan",...A(U)})}function H6($,U){return new LU({check:"less_than",...A(U),value:$,inclusive:!1})}function l$($,U){return new LU({check:"less_than",...A(U),value:$,inclusive:!0})}function V6($,U){return new BU({check:"greater_than",...A(U),value:$,inclusive:!1})}function I$($,U){return new BU({check:"greater_than",...A(U),value:$,inclusive:!0})}function ij($){return V6(0,$)}function lj($){return H6(0,$)}function nj($){return l$(0,$)}function rj($){return I$(0,$)}function d6($,U){return new oJ({check:"multiple_of",...A(U),value:$})}function D4($,U){return new sJ({check:"max_size",...A(U),maximum:$})}function o6($,U){return new eJ({check:"min_size",...A(U),minimum:$})}function X1($,U){return new $z({check:"size_equals",...A(U),size:$})}function K4($,U){return new Uz({check:"max_length",...A(U),maximum:$})}function Z6($,U){return new Jz({check:"min_length",...A(U),minimum:$})}function q4($,U){return new zz({check:"length_equals",...A(U),length:$})}function j1($,U){return new Xz({check:"string_format",format:"regex",...A(U),pattern:$})}function Y1($){return new jz({check:"string_format",format:"lowercase",...A($)})}function N1($){return new Yz({check:"string_format",format:"uppercase",...A($)})}function O1($,U){return new Nz({check:"string_format",format:"includes",...A(U),includes:$})}function W1($,U){return new Oz({check:"string_format",format:"starts_with",...A(U),prefix:$})}function G1($,U){return new Wz({check:"string_format",format:"ends_with",...A(U),suffix:$})}function pj($,U,z){return new Gz({check:"property",property:$,schema:U,...A(z)})}function Q1($,U){return new Qz({check:"mime_type",mime:$,...A(U)})}function L6($){return new wz({check:"overwrite",tx:$})}function w1($){return L6((U)=>U.normalize($))}function H1(){return L6(($)=>$.trim())}function V1(){return L6(($)=>$.toLowerCase())}function L1(){return L6(($)=>$.toUpperCase())}function dj($,U,z){return new $({type:"array",element:U,...A(z)})}function G7($,U,z){return new $({type:"union",options:U,...A(z)})}function Q7($,U,z,X){return new $({type:"union",options:z,discriminator:U,...A(X)})}function w7($,U,z){return new $({type:"intersection",left:U,right:z})}function H7($,U,z,X){let J=z instanceof c;return new $({type:"tuple",items:U,rest:J?z:null,...A(J?X:z)})}function V7($,U,z,X){return new $({type:"record",keyType:U,valueType:z,...A(X)})}function L7($,U,z,X){return new $({type:"map",keyType:U,valueType:z,...A(X)})}function B7($,U,z){return new $({type:"set",valueType:U,...A(z)})}function D7($,U,z){let X=Array.isArray(U)?Object.fromEntries(U.map((J)=>[J,J])):U;return new $({type:"enum",entries:X,...A(z)})}function K7($,U,z){return new $({type:"enum",entries:U,...A(z)})}function q7($,U,z){return new $({type:"literal",values:Array.isArray(U)?U:[U],...A(z)})}function oj($,U){return new $({type:"file",...A(U)})}function _7($,U){return new $({type:"transform",transform:U})}function v7($,U){return new $({type:"optional",innerType:U})}function F7($,U){return new $({type:"nullable",innerType:U})}function P7($,U,z){return new $({type:"default",innerType:U,get defaultValue(){return typeof z==="function"?z():QJ(z)}})}function A7($,U,z){return new $({type:"nonoptional",innerType:U,...A(z)})}function E7($,U){return new $({type:"success",innerType:U})}function M7($,U,z){return new $({type:"catch",innerType:U,catchValue:typeof z==="function"?z:()=>z})}function b7($,U,z){return new $({type:"pipe",in:U,out:z})}function R7($,U){return new $({type:"readonly",innerType:U})}function I7($,U,z){return new $({type:"template_literal",parts:U,...A(z)})}function S7($,U){return new $({type:"lazy",getter:U})}function k7($,U){return new $({type:"promise",innerType:U})}function tj($,U,z){let X=A(z);return X.abort??(X.abort=!0),new $({type:"custom",check:"custom",fn:U,...X})}function aj($,U,z){return new $({type:"custom",check:"custom",fn:U,...A(z)})}function sj($){let U=d9((z)=>{return z.addIssue=(X)=>{if(typeof X==="string")z.issues.push(Q4(X,z.value,U._zod.def));else{let J=X;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=z.value),J.inst??(J.inst=U),J.continue??(J.continue=!U._zod.def.abort),z.issues.push(Q4(J))}},$(z.value,z)});return U}function d9($,U){let z=new j$({check:"custom",...A(U)});return z._zod.check=$,z}function ej($,U){let z=A(U),X=z.truthy??["true","1","yes","on","y","enabled"],J=z.falsy??["false","0","no","off","n","disabled"];if(z.case!=="sensitive")X=X.map((w)=>typeof w==="string"?w.toLowerCase():w),J=J.map((w)=>typeof w==="string"?w.toLowerCase():w);let j=new Set(X),Y=new Set(J),N=$.Codec??d4,W=$.Boolean??p4,Q=new($.String??p6)({type:"string",error:z.error}),L=new W({type:"boolean",error:z.error}),H=new N({type:"pipe",in:Q,out:L,transform:(w,B)=>{let q=w;if(z.case!=="sensitive")q=q.toLowerCase();if(j.has(q))return!0;else if(Y.has(q))return!1;else return B.issues.push({code:"invalid_value",expected:"stringbool",values:[...j,...Y],input:B.value,inst:H,continue:!1}),{}},reverseTransform:(w,B)=>{if(w===!0)return X[0]||"true";else return J[0]||"false"},error:z.error});return H}function _4($,U,z,X={}){let J=A(X),j={...A(X),check:"string_format",type:"string",format:U,fn:typeof z==="function"?z:(N)=>z.test(N),...J};if(z instanceof RegExp)j.pattern=z;return new $(j)}class dU{constructor($){this.counter=0,this.metadataRegistry=$?.metadata??U6,this.target=$?.target??"draft-2020-12",this.unrepresentable=$?.unrepresentable??"throw",this.override=$?.override??(()=>{}),this.io=$?.io??"output",this.seen=new Map}process($,U={path:[],schemaPath:[]}){var z;let X=$._zod.def,J={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},j=this.seen.get($);if(j){if(j.count++,U.schemaPath.includes($))j.cycle=U.path;return j.schema}let Y={schema:{},count:1,cycle:void 0,path:U.path};this.seen.set($,Y);let N=$._zod.toJSONSchema?.();if(N)Y.schema=N;else{let Q={...U,schemaPath:[...U.schemaPath,$],path:U.path},L=$._zod.parent;if(L)Y.ref=L,this.process(L,Q),this.seen.get(L).isParent=!0;else{let H=Y.schema;switch(X.type){case"string":{let w=H;w.type="string";let{minimum:B,maximum:q,format:T,patterns:b,contentEncoding:g}=$._zod.bag;if(typeof B==="number")w.minLength=B;if(typeof q==="number")w.maxLength=q;if(T){if(w.format=J[T]??T,w.format==="")delete w.format}if(g)w.contentEncoding=g;if(b&&b.size>0){let y=[...b];if(y.length===1)w.pattern=y[0].source;else if(y.length>1)Y.schema.allOf=[...y.map((Z)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:Z.source}))]}break}case"number":{let w=H,{minimum:B,maximum:q,format:T,multipleOf:b,exclusiveMaximum:g,exclusiveMinimum:y}=$._zod.bag;if(typeof T==="string"&&T.includes("int"))w.type="integer";else w.type="number";if(typeof y==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")w.minimum=y,w.exclusiveMinimum=!0;else w.exclusiveMinimum=y;if(typeof B==="number"){if(w.minimum=B,typeof y==="number"&&this.target!=="draft-4")if(y>=B)delete w.minimum;else delete w.exclusiveMinimum}if(typeof g==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")w.maximum=g,w.exclusiveMaximum=!0;else w.exclusiveMaximum=g;if(typeof q==="number"){if(w.maximum=q,typeof g==="number"&&this.target!=="draft-4")if(g<=q)delete w.maximum;else delete w.exclusiveMaximum}if(typeof b==="number")w.multipleOf=b;break}case"boolean":{let w=H;w.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")H.type="string",H.nullable=!0,H.enum=[null];else H.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{H.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let w=H,{minimum:B,maximum:q}=$._zod.bag;if(typeof B==="number")w.minItems=B;if(typeof q==="number")w.maxItems=q;w.type="array",w.items=this.process(X.element,{...Q,path:[...Q.path,"items"]});break}case"object":{let w=H;w.type="object",w.properties={};let B=X.shape;for(let b in B)w.properties[b]=this.process(B[b],{...Q,path:[...Q.path,"properties",b]});let q=new Set(Object.keys(B)),T=new Set([...q].filter((b)=>{let g=X.shape[b]._zod;if(this.io==="input")return g.optin===void 0;else return g.optout===void 0}));if(T.size>0)w.required=Array.from(T);if(X.catchall?._zod.def.type==="never")w.additionalProperties=!1;else if(!X.catchall){if(this.io==="output")w.additionalProperties=!1}else if(X.catchall)w.additionalProperties=this.process(X.catchall,{...Q,path:[...Q.path,"additionalProperties"]});break}case"union":{let w=H,B=X.options.map((q,T)=>this.process(q,{...Q,path:[...Q.path,"anyOf",T]}));w.anyOf=B;break}case"intersection":{let w=H,B=this.process(X.left,{...Q,path:[...Q.path,"allOf",0]}),q=this.process(X.right,{...Q,path:[...Q.path,"allOf",1]}),T=(g)=>("allOf"in g)&&Object.keys(g).length===1,b=[...T(B)?B.allOf:[B],...T(q)?q.allOf:[q]];w.allOf=b;break}case"tuple":{let w=H;w.type="array";let B=this.target==="draft-2020-12"?"prefixItems":"items",q=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",T=X.items.map((Z,N$)=>this.process(Z,{...Q,path:[...Q.path,B,N$]})),b=X.rest?this.process(X.rest,{...Q,path:[...Q.path,q,...this.target==="openapi-3.0"?[X.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(w.prefixItems=T,b)w.items=b}else if(this.target==="openapi-3.0"){if(w.items={anyOf:T},b)w.items.anyOf.push(b);if(w.minItems=T.length,!b)w.maxItems=T.length}else if(w.items=T,b)w.additionalItems=b;let{minimum:g,maximum:y}=$._zod.bag;if(typeof g==="number")w.minItems=g;if(typeof y==="number")w.maxItems=y;break}case"record":{let w=H;if(w.type="object",this.target==="draft-7"||this.target==="draft-2020-12")w.propertyNames=this.process(X.keyType,{...Q,path:[...Q.path,"propertyNames"]});w.additionalProperties=this.process(X.valueType,{...Q,path:[...Q.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let w=H,B=f4(X.entries);if(B.every((q)=>typeof q==="number"))w.type="number";if(B.every((q)=>typeof q==="string"))w.type="string";w.enum=B;break}case"literal":{let w=H,B=[];for(let q of X.values)if(q===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof q==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else B.push(Number(q));else B.push(q);if(B.length===0);else if(B.length===1){let q=B[0];if(w.type=q===null?"null":typeof q,this.target==="draft-4"||this.target==="openapi-3.0")w.enum=[q];else w.const=q}else{if(B.every((q)=>typeof q==="number"))w.type="number";if(B.every((q)=>typeof q==="string"))w.type="string";if(B.every((q)=>typeof q==="boolean"))w.type="string";if(B.every((q)=>q===null))w.type="null";w.enum=B}break}case"file":{let w=H,B={type:"string",format:"binary",contentEncoding:"binary"},{minimum:q,maximum:T,mime:b}=$._zod.bag;if(q!==void 0)B.minLength=q;if(T!==void 0)B.maxLength=T;if(b)if(b.length===1)B.contentMediaType=b[0],Object.assign(w,B);else w.anyOf=b.map((g)=>{return{...B,contentMediaType:g}});else Object.assign(w,B);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let w=this.process(X.innerType,Q);if(this.target==="openapi-3.0")Y.ref=X.innerType,H.nullable=!0;else H.anyOf=[w,{type:"null"}];break}case"nonoptional":{this.process(X.innerType,Q),Y.ref=X.innerType;break}case"success":{let w=H;w.type="boolean";break}case"default":{this.process(X.innerType,Q),Y.ref=X.innerType,H.default=JSON.parse(JSON.stringify(X.defaultValue));break}case"prefault":{if(this.process(X.innerType,Q),Y.ref=X.innerType,this.io==="input")H._prefault=JSON.parse(JSON.stringify(X.defaultValue));break}case"catch":{this.process(X.innerType,Q),Y.ref=X.innerType;let w;try{w=X.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}H.default=w;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let w=H,B=$._zod.pattern;if(!B)throw Error("Pattern not found in template literal");w.type="string",w.pattern=B.source;break}case"pipe":{let w=this.io==="input"?X.in._zod.def.type==="transform"?X.out:X.in:X.out;this.process(w,Q),Y.ref=w;break}case"readonly":{this.process(X.innerType,Q),Y.ref=X.innerType,H.readOnly=!0;break}case"promise":{this.process(X.innerType,Q),Y.ref=X.innerType;break}case"optional":{this.process(X.innerType,Q),Y.ref=X.innerType;break}case"lazy":{let w=$._zod.innerType;this.process(w,Q),Y.ref=w;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let W=this.metadataRegistry.get($);if(W)Object.assign(Y.schema,W);if(this.io==="input"&&B$($))delete Y.schema.examples,delete Y.schema.default;if(this.io==="input"&&Y.schema._prefault)(z=Y.schema).default??(z.default=Y.schema._prefault);return delete Y.schema._prefault,this.seen.get($).schema}emit($,U){let z={cycles:U?.cycles??"ref",reused:U?.reused??"inline",external:U?.external??void 0},X=this.seen.get($);if(!X)throw Error("Unprocessed schema. This is a bug in Zod.");let J=(G)=>{let Q=this.target==="draft-2020-12"?"$defs":"definitions";if(z.external){let B=z.external.registry.get(G[0])?.id,q=z.external.uri??((b)=>b);if(B)return{ref:q(B)};let T=G[1].defId??G[1].schema.id??`schema${this.counter++}`;return G[1].defId=T,{defId:T,ref:`${q("__shared")}#/${Q}/${T}`}}if(G[1]===X)return{ref:"#"};let H=`${"#"}/${Q}/`,w=G[1].schema.id??`__schema${this.counter++}`;return{defId:w,ref:H+w}},j=(G)=>{if(G[1].schema.$ref)return;let Q=G[1],{ref:L,defId:H}=J(G);if(Q.def={...Q.schema},H)Q.defId=H;let w=Q.schema;for(let B in w)delete w[B];w.$ref=L};if(z.cycles==="throw")for(let G of this.seen.entries()){let Q=G[1];if(Q.cycle)throw Error(`Cycle detected: #/${Q.cycle?.join("/")}/<root>
135
+ `)}L.write("payload.value = newResult;"),L.write("return payload;");let k=L.compile();return(x,S)=>k(B,x,S)},G,W=V1,K=!AY.jitless,U=K&&f8.value,N=X.catchall,O;Y._zod.parse=(B,L)=>{O??(O=Q.value);let Z=B.value;if(!W(Z))return B.issues.push({expected:"object",code:"invalid_type",input:Z,inst:Y}),B;if(K&&U&&L?.async===!1&&L.jitless!==!0){if(!G)G=$(X.shape);if(B=G(B,L),!N)return B;return sQ([],Z,B,L,O,Y)}return J(B,L)}});function NQ(Y,X,J,Q){for(let G of Y)if(G.issues.length===0)return X.value=G.value,X;let $=Y.filter((G)=>!X1(G));if($.length===1)return X.value=$[0].value,$[0];return X.issues.push({code:"invalid_union",input:X.value,inst:J,errors:Y.map((G)=>G.issues.map((W)=>_0(W,Q,h0())))}),X}var a8=q("$ZodUnion",(Y,X)=>{i.init(Y,X),p(Y._zod,"optin",()=>X.options.some(($)=>$._zod.optin==="optional")?"optional":void 0),p(Y._zod,"optout",()=>X.options.some(($)=>$._zod.optout==="optional")?"optional":void 0),p(Y._zod,"values",()=>{if(X.options.every(($)=>$._zod.values))return new Set(X.options.flatMap(($)=>Array.from($._zod.values)));return}),p(Y._zod,"pattern",()=>{if(X.options.every(($)=>$._zod.pattern)){let $=X.options.map((G)=>G._zod.pattern);return new RegExp(`^(${$.map((G)=>d1(G.source)).join("|")})$`)}return});let J=X.options.length===1,Q=X.options[0]._zod.run;Y._zod.parse=($,G)=>{if(J)return Q($,G);let W=!1,K=[];for(let H of X.options){let U=H._zod.run({value:$.value,issues:[]},G);if(U instanceof Promise)K.push(U),W=!0;else{if(U.issues.length===0)return U;K.push(U)}}if(!W)return NQ(K,$,Y,G);return Promise.all(K).then((H)=>{return NQ(H,$,Y,G)})}}),tQ=q("$ZodDiscriminatedUnion",(Y,X)=>{a8.init(Y,X);let J=Y._zod.parse;p(Y._zod,"propValues",()=>{let $={};for(let G of X.options){let W=G._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(G)}"`);for(let[K,H]of Object.entries(W)){if(!$[K])$[K]=new Set;for(let U of H)$[K].add(U)}}return $});let Q=_1(()=>{let $=X.options,G=new Map;for(let W of $){let K=W._zod.propValues?.[X.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);for(let H of K){if(G.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);G.set(H,W)}}return G});Y._zod.parse=($,G)=>{let W=$.value;if(!V1(W))return $.issues.push({code:"invalid_type",expected:"object",input:W,inst:Y}),$;let K=Q.value.get(W?.[X.discriminator]);if(K)return K._zod.run($,G);if(X.unionFallback)return J($,G);return $.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:X.discriminator,input:W,path:[X.discriminator],inst:Y}),$}}),eQ=q("$ZodIntersection",(Y,X)=>{i.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value,G=X.left._zod.run({value:$,issues:[]},Q),W=X.right._zod.run({value:$,issues:[]},Q);if(G instanceof Promise||W instanceof Promise)return Promise.all([G,W]).then(([H,U])=>{return VQ(J,H,U)});return VQ(J,G,W)}});function r8(Y,X){if(Y===X)return{valid:!0,data:Y};if(Y instanceof Date&&X instanceof Date&&+Y===+X)return{valid:!0,data:Y};if(Y1(Y)&&Y1(X)){let J=Object.keys(X),Q=Object.keys(Y).filter((G)=>J.indexOf(G)!==-1),$={...Y,...X};for(let G of Q){let W=r8(Y[G],X[G]);if(!W.valid)return{valid:!1,mergeErrorPath:[G,...W.mergeErrorPath]};$[G]=W.data}return{valid:!0,data:$}}if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<Y.length;Q++){let $=Y[Q],G=X[Q],W=r8($,G);if(!W.valid)return{valid:!1,mergeErrorPath:[Q,...W.mergeErrorPath]};J.push(W.data)}return{valid:!0,data:J}}return{valid:!1,mergeErrorPath:[]}}function VQ(Y,X,J){if(X.issues.length)Y.issues.push(...X.issues);if(J.issues.length)Y.issues.push(...J.issues);if(X1(Y))return Y;let Q=r8(X.value,J.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return Y.value=Q.data,Y}var Y7=q("$ZodRecord",(Y,X)=>{i.init(Y,X),Y._zod.parse=(J,Q)=>{let $=J.value;if(!Y1($))return J.issues.push({expected:"record",code:"invalid_type",input:$,inst:Y}),J;let G=[];if(X.keyType._zod.values){let W=X.keyType._zod.values;J.value={};for(let H of W)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=X.valueType._zod.run({value:$[H],issues:[]},Q);if(U instanceof Promise)G.push(U.then((N)=>{if(N.issues.length)J.issues.push(...d0(H,N.issues));J.value[H]=N.value}));else{if(U.issues.length)J.issues.push(...d0(H,U.issues));J.value[H]=U.value}}let K;for(let H in $)if(!W.has(H))K=K??[],K.push(H);if(K&&K.length>0)J.issues.push({code:"unrecognized_keys",input:$,inst:Y,keys:K})}else{J.value={};for(let W of Reflect.ownKeys($)){if(W==="__proto__")continue;let K=X.keyType._zod.run({value:W,issues:[]},Q);if(K instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(K.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:K.issues.map((U)=>_0(U,Q,h0())),input:W,path:[W],inst:Y}),J.value[K.value]=K.value;continue}let H=X.valueType._zod.run({value:$[W],issues:[]},Q);if(H instanceof Promise)G.push(H.then((U)=>{if(U.issues.length)J.issues.push(...d0(W,U.issues));J.value[K.value]=U.value}));else{if(H.issues.length)J.issues.push(...d0(W,H.issues));J.value[K.value]=H.value}}}if(G.length)return Promise.all(G).then(()=>J);return J}});var X7=q("$ZodEnum",(Y,X)=>{i.init(Y,X);let J=p1(X.entries),Q=new Set(J);Y._zod.values=Q,Y._zod.pattern=new RegExp(`^(${J.filter(($)=>m8.has(typeof $)).map(($)=>typeof $==="string"?l0($):$.toString()).join("|")})$`),Y._zod.parse=($,G)=>{let W=$.value;if(Q.has(W))return $;return $.issues.push({code:"invalid_value",values:J,input:W,inst:Y}),$}}),J7=q("$ZodLiteral",(Y,X)=>{if(i.init(Y,X),X.values.length===0)throw Error("Cannot create literal schema with no valid values");Y._zod.values=new Set(X.values),Y._zod.pattern=new RegExp(`^(${X.values.map((J)=>typeof J==="string"?l0(J):J?l0(J.toString()):String(J)).join("|")})$`),Y._zod.parse=(J,Q)=>{let $=J.value;if(Y._zod.values.has($))return J;return J.issues.push({code:"invalid_value",values:X.values,input:$,inst:Y}),J}});var Q7=q("$ZodTransform",(Y,X)=>{i.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new c1(Y.constructor.name);let $=X.transform(J.value,J);if(Q.async)return($ instanceof Promise?$:Promise.resolve($)).then((W)=>{return J.value=W,J});if($ instanceof Promise)throw new p0;return J.value=$,J}});function BQ(Y,X){if(Y.issues.length&&X===void 0)return{issues:[],value:void 0};return Y}var $7=q("$ZodOptional",(Y,X)=>{i.init(Y,X),Y._zod.optin="optional",Y._zod.optout="optional",p(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,void 0]):void 0}),p(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${d1(J.source)})?$`):void 0}),Y._zod.parse=(J,Q)=>{if(X.innerType._zod.optin==="optional"){let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>BQ(G,J.value));return BQ($,J.value)}if(J.value===void 0)return J;return X.innerType._zod.run(J,Q)}}),G7=q("$ZodNullable",(Y,X)=>{i.init(Y,X),p(Y._zod,"optin",()=>X.innerType._zod.optin),p(Y._zod,"optout",()=>X.innerType._zod.optout),p(Y._zod,"pattern",()=>{let J=X.innerType._zod.pattern;return J?new RegExp(`^(${d1(J.source)}|null)$`):void 0}),p(Y._zod,"values",()=>{return X.innerType._zod.values?new Set([...X.innerType._zod.values,null]):void 0}),Y._zod.parse=(J,Q)=>{if(J.value===null)return J;return X.innerType._zod.run(J,Q)}}),W7=q("$ZodDefault",(Y,X)=>{i.init(Y,X),Y._zod.optin="optional",p(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)return J.value=X.defaultValue,J;let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>ZQ(G,X));return ZQ($,X)}});function ZQ(Y,X){if(Y.value===void 0)Y.value=X.defaultValue;return Y}var z7=q("$ZodPrefault",(Y,X)=>{i.init(Y,X),Y._zod.optin="optional",p(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);if(J.value===void 0)J.value=X.defaultValue;return X.innerType._zod.run(J,Q)}}),K7=q("$ZodNonOptional",(Y,X)=>{i.init(Y,X),p(Y._zod,"values",()=>{let J=X.innerType._zod.values;return J?new Set([...J].filter((Q)=>Q!==void 0)):void 0}),Y._zod.parse=(J,Q)=>{let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>OQ(G,Y));return OQ($,Y)}});function OQ(Y,X){if(!Y.issues.length&&Y.value===void 0)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:Y.value,inst:X});return Y}var U7=q("$ZodCatch",(Y,X)=>{i.init(Y,X),p(Y._zod,"optin",()=>X.innerType._zod.optin),p(Y._zod,"optout",()=>X.innerType._zod.optout),p(Y._zod,"values",()=>X.innerType._zod.values),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>{if(J.value=G.value,G.issues.length)J.value=X.catchValue({...J,error:{issues:G.issues.map((W)=>_0(W,Q,h0()))},input:J.value}),J.issues=[];return J});if(J.value=$.value,$.issues.length)J.value=X.catchValue({...J,error:{issues:$.issues.map((G)=>_0(G,Q,h0()))},input:J.value}),J.issues=[];return J}});var H7=q("$ZodPipe",(Y,X)=>{i.init(Y,X),p(Y._zod,"values",()=>X.in._zod.values),p(Y._zod,"optin",()=>X.in._zod.optin),p(Y._zod,"optout",()=>X.out._zod.optout),p(Y._zod,"propValues",()=>X.in._zod.propValues),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward"){let G=X.out._zod.run(J,Q);if(G instanceof Promise)return G.then((W)=>kY(W,X.in,Q));return kY(G,X.in,Q)}let $=X.in._zod.run(J,Q);if($ instanceof Promise)return $.then((G)=>kY(G,X.out,Q));return kY($,X.out,Q)}});function kY(Y,X,J){if(Y.issues.length)return Y.aborted=!0,Y;return X._zod.run({value:Y.value,issues:Y.issues},J)}var L7=q("$ZodReadonly",(Y,X)=>{i.init(Y,X),p(Y._zod,"propValues",()=>X.innerType._zod.propValues),p(Y._zod,"values",()=>X.innerType._zod.values),p(Y._zod,"optin",()=>X.innerType._zod.optin),p(Y._zod,"optout",()=>X.innerType._zod.optout),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")return X.innerType._zod.run(J,Q);let $=X.innerType._zod.run(J,Q);if($ instanceof Promise)return $.then(FQ);return FQ($)}});function FQ(Y){return Y.value=Object.freeze(Y.value),Y}var N7=q("$ZodLazy",(Y,X)=>{i.init(Y,X),p(Y._zod,"innerType",()=>X.getter()),p(Y._zod,"pattern",()=>Y._zod.innerType._zod.pattern),p(Y._zod,"propValues",()=>Y._zod.innerType._zod.propValues),p(Y._zod,"optin",()=>Y._zod.innerType._zod.optin??void 0),p(Y._zod,"optout",()=>Y._zod.innerType._zod.optout??void 0),Y._zod.parse=(J,Q)=>{return Y._zod.innerType._zod.run(J,Q)}}),V7=q("$ZodCustom",(Y,X)=>{N0.init(Y,X),i.init(Y,X),Y._zod.parse=(J,Q)=>{return J},Y._zod.check=(J)=>{let Q=J.value,$=X.fn(Q);if($ instanceof Promise)return $.then((G)=>qQ(G,J,Q,Y));qQ($,J,Q,Y);return}});function qQ(Y,X,J,Q){if(!Y){let $={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)$.params=Q._zod.def.params;X.issues.push(I1($))}}var kB=Symbol("ZodOutput"),bB=Symbol("ZodInput");class vY{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Y,...X){let J=X[0];if(this._map.set(Y,J),J&&typeof J==="object"&&"id"in J){if(this._idmap.has(J.id))throw Error(`ID ${J.id} already exists in the registry`);this._idmap.set(J.id,Y)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Y){let X=this._map.get(Y);if(X&&typeof X==="object"&&"id"in X)this._idmap.delete(X.id);return this._map.delete(Y),this}get(Y){let X=Y._zod.parent;if(X){let J={...this.get(X)??{}};delete J.id;let Q={...J,...this._map.get(Y)};return Object.keys(Q).length?Q:void 0}return this._map.get(Y)}has(Y){return this._map.has(Y)}}function Yz(){return new vY}var B1=Yz();function B7(Y,X){return new Y({type:"string",...v(X)})}function Z7(Y,X){return new Y({type:"string",format:"email",check:"string_format",abort:!1,...v(X)})}function t8(Y,X){return new Y({type:"string",format:"guid",check:"string_format",abort:!1,...v(X)})}function O7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,...v(X)})}function F7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(X)})}function q7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(X)})}function j7(Y,X){return new Y({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(X)})}function D7(Y,X){return new Y({type:"string",format:"url",check:"string_format",abort:!1,...v(X)})}function P7(Y,X){return new Y({type:"string",format:"emoji",check:"string_format",abort:!1,...v(X)})}function w7(Y,X){return new Y({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(X)})}function E7(Y,X){return new Y({type:"string",format:"cuid",check:"string_format",abort:!1,...v(X)})}function M7(Y,X){return new Y({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(X)})}function A7(Y,X){return new Y({type:"string",format:"ulid",check:"string_format",abort:!1,...v(X)})}function R7(Y,X){return new Y({type:"string",format:"xid",check:"string_format",abort:!1,...v(X)})}function T7(Y,X){return new Y({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(X)})}function C7(Y,X){return new Y({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(X)})}function _7(Y,X){return new Y({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(X)})}function I7(Y,X){return new Y({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(X)})}function S7(Y,X){return new Y({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(X)})}function k7(Y,X){return new Y({type:"string",format:"base64",check:"string_format",abort:!1,...v(X)})}function b7(Y,X){return new Y({type:"string",format:"base64url",check:"string_format",abort:!1,...v(X)})}function x7(Y,X){return new Y({type:"string",format:"e164",check:"string_format",abort:!1,...v(X)})}function v7(Y,X){return new Y({type:"string",format:"jwt",check:"string_format",abort:!1,...v(X)})}function h7(Y,X){return new Y({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(X)})}function g7(Y,X){return new Y({type:"string",format:"date",check:"string_format",...v(X)})}function y7(Y,X){return new Y({type:"string",format:"time",check:"string_format",precision:null,...v(X)})}function f7(Y,X){return new Y({type:"string",format:"duration",check:"string_format",...v(X)})}function m7(Y,X){return new Y({type:"number",checks:[],...v(X)})}function c7(Y,X){return new Y({type:"number",check:"number_format",abort:!1,format:"safeint",...v(X)})}function u7(Y,X){return new Y({type:"boolean",...v(X)})}function p7(Y,X){return new Y({type:"null",...v(X)})}function l7(Y){return new Y({type:"unknown"})}function d7(Y,X){return new Y({type:"never",...v(X)})}function hY(Y,X){return new i8({check:"less_than",...v(X),value:Y,inclusive:!1})}function s1(Y,X){return new i8({check:"less_than",...v(X),value:Y,inclusive:!0})}function gY(Y,X){return new n8({check:"greater_than",...v(X),value:Y,inclusive:!1})}function a1(Y,X){return new n8({check:"greater_than",...v(X),value:Y,inclusive:!0})}function yY(Y,X){return new a6({check:"multiple_of",...v(X),value:Y})}function fY(Y,X){return new e6({check:"max_length",...v(X),maximum:Y})}function S1(Y,X){return new YQ({check:"min_length",...v(X),minimum:Y})}function mY(Y,X){return new XQ({check:"length_equals",...v(X),length:Y})}function e8(Y,X){return new JQ({check:"string_format",format:"regex",...v(X),pattern:Y})}function Y9(Y){return new QQ({check:"string_format",format:"lowercase",...v(Y)})}function X9(Y){return new $Q({check:"string_format",format:"uppercase",...v(Y)})}function J9(Y,X){return new GQ({check:"string_format",format:"includes",...v(X),includes:Y})}function Q9(Y,X){return new WQ({check:"string_format",format:"starts_with",...v(X),prefix:Y})}function $9(Y,X){return new zQ({check:"string_format",format:"ends_with",...v(X),suffix:Y})}function Z1(Y){return new KQ({check:"overwrite",tx:Y})}function G9(Y){return Z1((X)=>X.normalize(Y))}function W9(){return Z1((Y)=>Y.trim())}function z9(){return Z1((Y)=>Y.toLowerCase())}function K9(){return Z1((Y)=>Y.toUpperCase())}function i7(Y,X,J){return new Y({type:"array",element:X,...v(J)})}function n7(Y,X,J){let Q=v(J);return Q.abort??(Q.abort=!0),new Y({type:"custom",check:"custom",fn:X,...Q})}function o7(Y,X,J){return new Y({type:"custom",check:"custom",fn:X,...v(J)})}function r7(Y){let X=Xz((J)=>{return J.addIssue=(Q)=>{if(typeof Q==="string")J.issues.push(I1(Q,J.value,X._zod.def));else{let $=Q;if($.fatal)$.continue=!1;$.code??($.code="custom"),$.input??($.input=J.value),$.inst??($.inst=X),$.continue??($.continue=!X._zod.def.abort),J.issues.push(I1($))}},Y(J.value,J)});return X}function Xz(Y,X){let J=new N0({check:"custom",...v(X)});return J._zod.check=Y,J}class U9{constructor(Y){this.counter=0,this.metadataRegistry=Y?.metadata??B1,this.target=Y?.target??"draft-2020-12",this.unrepresentable=Y?.unrepresentable??"throw",this.override=Y?.override??(()=>{}),this.io=Y?.io??"output",this.seen=new Map}process(Y,X={path:[],schemaPath:[]}){var J;let Q=Y._zod.def,$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G=this.seen.get(Y);if(G){if(G.count++,X.schemaPath.includes(Y))G.cycle=X.path;return G.schema}let W={schema:{},count:1,cycle:void 0,path:X.path};this.seen.set(Y,W);let K=Y._zod.toJSONSchema?.();if(K)W.schema=K;else{let N={...X,schemaPath:[...X.schemaPath,Y],path:X.path},O=Y._zod.parent;if(O)W.ref=O,this.process(O,N),this.seen.get(O).isParent=!0;else{let B=W.schema;switch(Q.type){case"string":{let L=B;L.type="string";let{minimum:Z,maximum:j,format:w,patterns:P,contentEncoding:k}=Y._zod.bag;if(typeof Z==="number")L.minLength=Z;if(typeof j==="number")L.maxLength=j;if(w){if(L.format=$[w]??w,L.format==="")delete L.format}if(k)L.contentEncoding=k;if(P&&P.size>0){let x=[...P];if(x.length===1)L.pattern=x[0].source;else if(x.length>1)W.schema.allOf=[...x.map((S)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:S.source}))]}break}case"number":{let L=B,{minimum:Z,maximum:j,format:w,multipleOf:P,exclusiveMaximum:k,exclusiveMinimum:x}=Y._zod.bag;if(typeof w==="string"&&w.includes("int"))L.type="integer";else L.type="number";if(typeof x==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")L.minimum=x,L.exclusiveMinimum=!0;else L.exclusiveMinimum=x;if(typeof Z==="number"){if(L.minimum=Z,typeof x==="number"&&this.target!=="draft-4")if(x>=Z)delete L.minimum;else delete L.exclusiveMinimum}if(typeof k==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")L.maximum=k,L.exclusiveMaximum=!0;else L.exclusiveMaximum=k;if(typeof j==="number"){if(L.maximum=j,typeof k==="number"&&this.target!=="draft-4")if(k<=j)delete L.maximum;else delete L.exclusiveMaximum}if(typeof P==="number")L.multipleOf=P;break}case"boolean":{let L=B;L.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")B.type="string",B.nullable=!0,B.enum=[null];else B.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{B.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let L=B,{minimum:Z,maximum:j}=Y._zod.bag;if(typeof Z==="number")L.minItems=Z;if(typeof j==="number")L.maxItems=j;L.type="array",L.items=this.process(Q.element,{...N,path:[...N.path,"items"]});break}case"object":{let L=B;L.type="object",L.properties={};let Z=Q.shape;for(let P in Z)L.properties[P]=this.process(Z[P],{...N,path:[...N.path,"properties",P]});let j=new Set(Object.keys(Z)),w=new Set([...j].filter((P)=>{let k=Q.shape[P]._zod;if(this.io==="input")return k.optin===void 0;else return k.optout===void 0}));if(w.size>0)L.required=Array.from(w);if(Q.catchall?._zod.def.type==="never")L.additionalProperties=!1;else if(!Q.catchall){if(this.io==="output")L.additionalProperties=!1}else if(Q.catchall)L.additionalProperties=this.process(Q.catchall,{...N,path:[...N.path,"additionalProperties"]});break}case"union":{let L=B,Z=Q.options.map((j,w)=>this.process(j,{...N,path:[...N.path,"anyOf",w]}));L.anyOf=Z;break}case"intersection":{let L=B,Z=this.process(Q.left,{...N,path:[...N.path,"allOf",0]}),j=this.process(Q.right,{...N,path:[...N.path,"allOf",1]}),w=(k)=>("allOf"in k)&&Object.keys(k).length===1,P=[...w(Z)?Z.allOf:[Z],...w(j)?j.allOf:[j]];L.allOf=P;break}case"tuple":{let L=B;L.type="array";let Z=this.target==="draft-2020-12"?"prefixItems":"items",j=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",w=Q.items.map((S,d)=>this.process(S,{...N,path:[...N.path,Z,d]})),P=Q.rest?this.process(Q.rest,{...N,path:[...N.path,j,...this.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(L.prefixItems=w,P)L.items=P}else if(this.target==="openapi-3.0"){if(L.items={anyOf:w},P)L.items.anyOf.push(P);if(L.minItems=w.length,!P)L.maxItems=w.length}else if(L.items=w,P)L.additionalItems=P;let{minimum:k,maximum:x}=Y._zod.bag;if(typeof k==="number")L.minItems=k;if(typeof x==="number")L.maxItems=x;break}case"record":{let L=B;if(L.type="object",this.target==="draft-7"||this.target==="draft-2020-12")L.propertyNames=this.process(Q.keyType,{...N,path:[...N.path,"propertyNames"]});L.additionalProperties=this.process(Q.valueType,{...N,path:[...N.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let L=B,Z=p1(Q.entries);if(Z.every((j)=>typeof j==="number"))L.type="number";if(Z.every((j)=>typeof j==="string"))L.type="string";L.enum=Z;break}case"literal":{let L=B,Z=[];for(let j of Q.values)if(j===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else Z.push(Number(j));else Z.push(j);if(Z.length===0);else if(Z.length===1){let j=Z[0];if(L.type=j===null?"null":typeof j,this.target==="draft-4"||this.target==="openapi-3.0")L.enum=[j];else L.const=j}else{if(Z.every((j)=>typeof j==="number"))L.type="number";if(Z.every((j)=>typeof j==="string"))L.type="string";if(Z.every((j)=>typeof j==="boolean"))L.type="string";if(Z.every((j)=>j===null))L.type="null";L.enum=Z}break}case"file":{let L=B,Z={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:w,mime:P}=Y._zod.bag;if(j!==void 0)Z.minLength=j;if(w!==void 0)Z.maxLength=w;if(P)if(P.length===1)Z.contentMediaType=P[0],Object.assign(L,Z);else L.anyOf=P.map((k)=>{return{...Z,contentMediaType:k}});else Object.assign(L,Z);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let L=this.process(Q.innerType,N);if(this.target==="openapi-3.0")W.ref=Q.innerType,B.nullable=!0;else B.anyOf=[L,{type:"null"}];break}case"nonoptional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"success":{let L=B;L.type="boolean";break}case"default":{this.process(Q.innerType,N),W.ref=Q.innerType,B.default=JSON.parse(JSON.stringify(Q.defaultValue));break}case"prefault":{if(this.process(Q.innerType,N),W.ref=Q.innerType,this.io==="input")B._prefault=JSON.parse(JSON.stringify(Q.defaultValue));break}case"catch":{this.process(Q.innerType,N),W.ref=Q.innerType;let L;try{L=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}B.default=L;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let L=B,Z=Y._zod.pattern;if(!Z)throw Error("Pattern not found in template literal");L.type="string",L.pattern=Z.source;break}case"pipe":{let L=this.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;this.process(L,N),W.ref=L;break}case"readonly":{this.process(Q.innerType,N),W.ref=Q.innerType,B.readOnly=!0;break}case"promise":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"optional":{this.process(Q.innerType,N),W.ref=Q.innerType;break}case"lazy":{let L=Y._zod.innerType;this.process(L,N),W.ref=L;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let H=this.metadataRegistry.get(Y);if(H)Object.assign(W.schema,H);if(this.io==="input"&&W0(Y))delete W.schema.examples,delete W.schema.default;if(this.io==="input"&&W.schema._prefault)(J=W.schema).default??(J.default=W.schema._prefault);return delete W.schema._prefault,this.seen.get(Y).schema}emit(Y,X){let J={cycles:X?.cycles??"ref",reused:X?.reused??"inline",external:X?.external??void 0},Q=this.seen.get(Y);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let $=(U)=>{let N=this.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let Z=J.external.registry.get(U[0])?.id,j=J.external.uri??((P)=>P);if(Z)return{ref:j(Z)};let w=U[1].defId??U[1].schema.id??`schema${this.counter++}`;return U[1].defId=w,{defId:w,ref:`${j("__shared")}#/${N}/${w}`}}if(U[1]===Q)return{ref:"#"};let B=`${"#"}/${N}/`,L=U[1].schema.id??`__schema${this.counter++}`;return{defId:L,ref:B+L}},G=(U)=>{if(U[1].schema.$ref)return;let N=U[1],{ref:O,defId:B}=$(U);if(N.def={...N.schema},B)N.defId=B;let L=N.schema;for(let Z in L)delete L[Z];L.$ref=O};if(J.cycles==="throw")for(let U of this.seen.entries()){let N=U[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/<root>
123
136
 
124
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let G of this.seen.entries()){let Q=G[1];if($===G[0]){j(G);continue}if(z.external){let H=z.external.registry.get(G[0])?.id;if($!==G[0]&&H){j(G);continue}}if(this.metadataRegistry.get(G[0])?.id){j(G);continue}if(Q.cycle){j(G);continue}if(Q.count>1){if(z.reused==="ref"){j(G);continue}}}let Y=(G,Q)=>{let L=this.seen.get(G),H=L.def??L.schema,w={...H};if(L.ref===null)return;let B=L.ref;if(L.ref=null,B){Y(B,Q);let q=this.seen.get(B).schema;if(q.$ref&&(Q.target==="draft-7"||Q.target==="draft-4"||Q.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(q);else Object.assign(H,q),Object.assign(H,w)}if(!L.isParent)this.override({zodSchema:G,jsonSchema:H,path:L.path??[]})};for(let G of[...this.seen.entries()].reverse())Y(G[0],{target:this.target});let N={};if(this.target==="draft-2020-12")N.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")N.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")N.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(z.external?.uri){let G=z.external.registry.get($)?.id;if(!G)throw Error("Schema is missing an `id` property");N.$id=z.external.uri(G)}Object.assign(N,X.def);let W=z.external?.defs??{};for(let G of this.seen.entries()){let Q=G[1];if(Q.def&&Q.defId)W[Q.defId]=Q.def}if(z.external);else if(Object.keys(W).length>0)if(this.target==="draft-2020-12")N.$defs=W;else N.definitions=W;try{return JSON.parse(JSON.stringify(N))}catch(G){throw Error("Error converting schema to JSON.")}}}function B1($,U){if($ instanceof U1){let X=new dU(U),J={};for(let N of $._idmap.entries()){let[W,G]=N;X.process(G)}let j={},Y={registry:$,uri:U?.uri,defs:J};for(let N of $._idmap.entries()){let[W,G]=N;j[W]=X.emit(G,{...U,external:Y})}if(Object.keys(J).length>0){let N=X.target==="draft-2020-12"?"$defs":"definitions";j.__shared={[N]:J}}return{schemas:j}}let z=new dU(U);return z.process($),z.emit($,U)}function B$($,U){let z=U??{seen:new Set};if(z.seen.has($))return!1;z.seen.add($);let J=$._zod.def;switch(J.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return B$(J.element,z);case"object":{for(let j in J.shape)if(B$(J.shape[j],z))return!0;return!1}case"union":{for(let j of J.options)if(B$(j,z))return!0;return!1}case"intersection":return B$(J.left,z)||B$(J.right,z);case"tuple":{for(let j of J.items)if(B$(j,z))return!0;if(J.rest&&B$(J.rest,z))return!0;return!1}case"record":return B$(J.keyType,z)||B$(J.valueType,z);case"map":return B$(J.keyType,z)||B$(J.valueType,z);case"set":return B$(J.valueType,z);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return B$(J.innerType,z);case"lazy":return B$(J.getter(),z);case"default":return B$(J.innerType,z);case"prefault":return B$(J.innerType,z);case"custom":return!1;case"transform":return!0;case"pipe":return B$(J.in,z)||B$(J.out,z);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${J.type}`)}var o9={};var eU={};w6(eU,{time:()=>JY,duration:()=>zY,datetime:()=>$Y,date:()=>UY,ZodISOTime:()=>aU,ZodISODuration:()=>sU,ZodISODateTime:()=>oU,ZodISODate:()=>tU});var oU=V("ZodISODateTime",($,U)=>{Mz.init($,U),z$.init($,U)});function $Y($){return Bj(oU,$)}var tU=V("ZodISODate",($,U)=>{bz.init($,U),z$.init($,U)});function UY($){return Dj(tU,$)}var aU=V("ZodISOTime",($,U)=>{Rz.init($,U),z$.init($,U)});function JY($){return Kj(aU,$)}var sU=V("ZodISODuration",($,U)=>{Iz.init($,U),z$.init($,U)});function zY($){return qj(sU,$)}var a9=($,U)=>{u4.init($,U),$.name="ZodError",Object.defineProperties($,{format:{value:(z)=>l4($,z)},flatten:{value:(z)=>i4($,z)},addIssue:{value:(z)=>{$.issues.push(z),$.message=JSON.stringify($.issues,W4,2)}},addIssues:{value:(z)=>{$.issues.push(...z),$.message=JSON.stringify($.issues,W4,2)}},isEmpty:{get(){return $.issues.length===0}}})},Z7=V("ZodError",a9),S$=V("ZodError",a9,{Parent:Error});var XY=w4(S$),jY=H4(S$),YY=V4(S$),D1=L4(S$),NY=YU(S$),OY=NU(S$),WY=OU(S$),GY=WU(S$),QY=GU(S$),wY=QU(S$),HY=wU(S$),VY=HU(S$);var i=V("ZodType",($,U)=>{return c.init($,U),$.def=U,$.type=U.type,Object.defineProperty($,"_def",{value:U}),$.check=(...z)=>{return $.clone({...U,checks:[...U.checks??[],...z.map((X)=>typeof X==="function"?{_zod:{check:X,def:{check:"custom"},onattach:[]}}:X)]})},$.clone=(z,X)=>E$($,z,X),$.brand=()=>$,$.register=(z,X)=>{return z.add($,X),$},$.parse=(z,X)=>XY($,z,X,{callee:$.parse}),$.safeParse=(z,X)=>YY($,z,X),$.parseAsync=async(z,X)=>jY($,z,X,{callee:$.parseAsync}),$.safeParseAsync=async(z,X)=>D1($,z,X),$.spa=$.safeParseAsync,$.encode=(z,X)=>NY($,z,X),$.decode=(z,X)=>OY($,z,X),$.encodeAsync=async(z,X)=>WY($,z,X),$.decodeAsync=async(z,X)=>GY($,z,X),$.safeEncode=(z,X)=>QY($,z,X),$.safeDecode=(z,X)=>wY($,z,X),$.safeEncodeAsync=async(z,X)=>HY($,z,X),$.safeDecodeAsync=async(z,X)=>VY($,z,X),$.refine=(z,X)=>$.check(fO(z,X)),$.superRefine=(z)=>$.check(hO(z)),$.overwrite=(z)=>$.check(L6(z)),$.optional=()=>U0($),$.nullable=()=>J0($),$.nullish=()=>U0(J0($)),$.nonoptional=(z)=>EO($,z),$.array=()=>Y0($),$.or=(z)=>fY([$,z]),$.and=(z)=>QO($,z),$.transform=(z)=>z0($,cY(z)),$.default=(z)=>FO($,z),$.prefault=(z)=>AO($,z),$.catch=(z)=>RO($,z),$.pipe=(z)=>z0($,z),$.readonly=()=>kO($),$.describe=(z)=>{let X=$.clone();return U6.add(X,{description:z}),X},Object.defineProperty($,"description",{get(){return U6.get($)?.description},configurable:!0}),$.meta=(...z)=>{if(z.length===0)return U6.get($);let X=$.clone();return U6.add(X,z[0]),X},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$}),DY=V("_ZodString",($,U)=>{p6.init($,U),i.init($,U);let z=$._zod.bag;$.format=z.format??null,$.minLength=z.minimum??null,$.maxLength=z.maximum??null,$.regex=(...X)=>$.check(j1(...X)),$.includes=(...X)=>$.check(O1(...X)),$.startsWith=(...X)=>$.check(W1(...X)),$.endsWith=(...X)=>$.check(G1(...X)),$.min=(...X)=>$.check(Z6(...X)),$.max=(...X)=>$.check(K4(...X)),$.length=(...X)=>$.check(q4(...X)),$.nonempty=(...X)=>$.check(Z6(1,...X)),$.lowercase=(X)=>$.check(Y1(X)),$.uppercase=(X)=>$.check(N1(X)),$.trim=()=>$.check(H1()),$.normalize=(...X)=>$.check(w1(...X)),$.toLowerCase=()=>$.check(V1()),$.toUpperCase=()=>$.check(L1())}),q1=V("ZodString",($,U)=>{p6.init($,U),DY.init($,U),$.email=(z)=>$.check(RU(KY,z)),$.url=(z)=>$.check(z1(X0,z)),$.jwt=(z)=>$.check(pU(ZY,z)),$.emoji=(z)=>$.check(ZU(qY,z)),$.guid=(z)=>$.check(J1($0,z)),$.uuid=(z)=>$.check(IU(D6,z)),$.uuidv4=(z)=>$.check(SU(D6,z)),$.uuidv6=(z)=>$.check(kU(D6,z)),$.uuidv7=(z)=>$.check(CU(D6,z)),$.nanoid=(z)=>$.check(TU(_Y,z)),$.guid=(z)=>$.check(J1($0,z)),$.cuid=(z)=>$.check(gU(vY,z)),$.cuid2=(z)=>$.check(xU(FY,z)),$.ulid=(z)=>$.check(fU(PY,z)),$.base64=(z)=>$.check(lU(SY,z)),$.base64url=(z)=>$.check(nU(kY,z)),$.xid=(z)=>$.check(hU(AY,z)),$.ksuid=(z)=>$.check(yU(EY,z)),$.ipv4=(z)=>$.check(cU(MY,z)),$.ipv6=(z)=>$.check(mU(bY,z)),$.cidrv4=(z)=>$.check(uU(RY,z)),$.cidrv6=(z)=>$.check(iU(IY,z)),$.e164=(z)=>$.check(rU(CY,z)),$.datetime=(z)=>$.check($Y(z)),$.date=(z)=>$.check(UY(z)),$.time=(z)=>$.check(JY(z)),$.duration=(z)=>$.check(zY(z))});function LY($){return Hj(q1,$)}var z$=V("ZodStringFormat",($,U)=>{J$.init($,U),DY.init($,U)}),KY=V("ZodEmail",($,U)=>{Dz.init($,U),z$.init($,U)});function g7($){return RU(KY,$)}var $0=V("ZodGUID",($,U)=>{Lz.init($,U),z$.init($,U)});function x7($){return J1($0,$)}var D6=V("ZodUUID",($,U)=>{Bz.init($,U),z$.init($,U)});function f7($){return IU(D6,$)}function h7($){return SU(D6,$)}function y7($){return kU(D6,$)}function c7($){return CU(D6,$)}var X0=V("ZodURL",($,U)=>{Kz.init($,U),z$.init($,U)});function m7($){return z1(X0,$)}function u7($){return z1(X0,{protocol:/^https?$/,hostname:i$.domain,...v.normalizeParams($)})}var qY=V("ZodEmoji",($,U)=>{qz.init($,U),z$.init($,U)});function i7($){return ZU(qY,$)}var _Y=V("ZodNanoID",($,U)=>{_z.init($,U),z$.init($,U)});function l7($){return TU(_Y,$)}var vY=V("ZodCUID",($,U)=>{vz.init($,U),z$.init($,U)});function n7($){return gU(vY,$)}var FY=V("ZodCUID2",($,U)=>{Fz.init($,U),z$.init($,U)});function r7($){return xU(FY,$)}var PY=V("ZodULID",($,U)=>{Pz.init($,U),z$.init($,U)});function p7($){return fU(PY,$)}var AY=V("ZodXID",($,U)=>{Az.init($,U),z$.init($,U)});function d7($){return hU(AY,$)}var EY=V("ZodKSUID",($,U)=>{Ez.init($,U),z$.init($,U)});function o7($){return yU(EY,$)}var MY=V("ZodIPv4",($,U)=>{Sz.init($,U),z$.init($,U)});function t7($){return cU(MY,$)}var bY=V("ZodIPv6",($,U)=>{kz.init($,U),z$.init($,U)});function a7($){return mU(bY,$)}var RY=V("ZodCIDRv4",($,U)=>{Cz.init($,U),z$.init($,U)});function s7($){return uU(RY,$)}var IY=V("ZodCIDRv6",($,U)=>{Zz.init($,U),z$.init($,U)});function e7($){return iU(IY,$)}var SY=V("ZodBase64",($,U)=>{gz.init($,U),z$.init($,U)});function $5($){return lU(SY,$)}var kY=V("ZodBase64URL",($,U)=>{xz.init($,U),z$.init($,U)});function U5($){return nU(kY,$)}var CY=V("ZodE164",($,U)=>{fz.init($,U),z$.init($,U)});function J5($){return rU(CY,$)}var ZY=V("ZodJWT",($,U)=>{hz.init($,U),z$.init($,U)});function z5($){return pU(ZY,$)}var _1=V("ZodCustomStringFormat",($,U)=>{yz.init($,U),z$.init($,U)});function X5($,U,z={}){return _4(_1,$,U,z)}function j5($){return _4(_1,"hostname",i$.hostname,$)}function Y5($){return _4(_1,"hex",i$.hex,$)}function N5($,U){let z=U?.enc??"hex",X=`${$}_${z}`,J=i$[X];if(!J)throw Error(`Unrecognized hash format: ${X}`);return _4(_1,X,J,U)}var v1=V("ZodNumber",($,U)=>{PU.init($,U),i.init($,U),$.gt=(X,J)=>$.check(V6(X,J)),$.gte=(X,J)=>$.check(I$(X,J)),$.min=(X,J)=>$.check(I$(X,J)),$.lt=(X,J)=>$.check(H6(X,J)),$.lte=(X,J)=>$.check(l$(X,J)),$.max=(X,J)=>$.check(l$(X,J)),$.int=(X)=>$.check(BY(X)),$.safe=(X)=>$.check(BY(X)),$.positive=(X)=>$.check(V6(0,X)),$.nonnegative=(X)=>$.check(I$(0,X)),$.negative=(X)=>$.check(H6(0,X)),$.nonpositive=(X)=>$.check(l$(0,X)),$.multipleOf=(X,J)=>$.check(d6(X,J)),$.step=(X,J)=>$.check(d6(X,J)),$.finite=()=>$;let z=$._zod.bag;$.minValue=Math.max(z.minimum??Number.NEGATIVE_INFINITY,z.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(z.maximum??Number.POSITIVE_INFINITY,z.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(z.format??"").includes("int")||Number.isSafeInteger(z.multipleOf??0.5),$.isFinite=!0,$.format=z.format??null});function s9($){return _j(v1,$)}var F4=V("ZodNumberFormat",($,U)=>{cz.init($,U),v1.init($,U)});function BY($){return Fj(F4,$)}function O5($){return Pj(F4,$)}function W5($){return Aj(F4,$)}function G5($){return Ej(F4,$)}function Q5($){return Mj(F4,$)}var F1=V("ZodBoolean",($,U)=>{p4.init($,U),i.init($,U)});function e9($){return bj(F1,$)}var P1=V("ZodBigInt",($,U)=>{AU.init($,U),i.init($,U),$.gte=(X,J)=>$.check(I$(X,J)),$.min=(X,J)=>$.check(I$(X,J)),$.gt=(X,J)=>$.check(V6(X,J)),$.gte=(X,J)=>$.check(I$(X,J)),$.min=(X,J)=>$.check(I$(X,J)),$.lt=(X,J)=>$.check(H6(X,J)),$.lte=(X,J)=>$.check(l$(X,J)),$.max=(X,J)=>$.check(l$(X,J)),$.positive=(X)=>$.check(V6(BigInt(0),X)),$.negative=(X)=>$.check(H6(BigInt(0),X)),$.nonpositive=(X)=>$.check(l$(BigInt(0),X)),$.nonnegative=(X)=>$.check(I$(BigInt(0),X)),$.multipleOf=(X,J)=>$.check(d6(X,J));let z=$._zod.bag;$.minValue=z.minimum??null,$.maxValue=z.maximum??null,$.format=z.format??null});function w5($){return Ij(P1,$)}var TY=V("ZodBigIntFormat",($,U)=>{mz.init($,U),P1.init($,U)});function H5($){return kj(TY,$)}function V5($){return Cj(TY,$)}var $O=V("ZodSymbol",($,U)=>{uz.init($,U),i.init($,U)});function L5($){return Zj($O,$)}var UO=V("ZodUndefined",($,U)=>{iz.init($,U),i.init($,U)});function B5($){return Tj(UO,$)}var JO=V("ZodNull",($,U)=>{lz.init($,U),i.init($,U)});function zO($){return gj(JO,$)}var XO=V("ZodAny",($,U)=>{nz.init($,U),i.init($,U)});function D5(){return xj(XO)}var jO=V("ZodUnknown",($,U)=>{rz.init($,U),i.init($,U)});function v4(){return fj(jO)}var YO=V("ZodNever",($,U)=>{pz.init($,U),i.init($,U)});function gY($){return hj(YO,$)}var NO=V("ZodVoid",($,U)=>{dz.init($,U),i.init($,U)});function K5($){return yj(NO,$)}var j0=V("ZodDate",($,U)=>{oz.init($,U),i.init($,U),$.min=(X,J)=>$.check(I$(X,J)),$.max=(X,J)=>$.check(l$(X,J));let z=$._zod.bag;$.minDate=z.minimum?new Date(z.minimum):null,$.maxDate=z.maximum?new Date(z.maximum):null});function q5($){return cj(j0,$)}var OO=V("ZodArray",($,U)=>{tz.init($,U),i.init($,U),$.element=U.element,$.min=(z,X)=>$.check(Z6(z,X)),$.nonempty=(z)=>$.check(Z6(1,z)),$.max=(z,X)=>$.check(K4(z,X)),$.length=(z,X)=>$.check(q4(z,X)),$.unwrap=()=>$.element});function Y0($,U){return dj(OO,$,U)}function _5($){let U=$._zod.def.shape;return yY(Object.keys(U))}var N0=V("ZodObject",($,U)=>{az.init($,U),i.init($,U),v.defineLazy($,"shape",()=>U.shape),$.keyof=()=>yY(Object.keys($._zod.def.shape)),$.catchall=(z)=>$.clone({...$._zod.def,catchall:z}),$.passthrough=()=>$.clone({...$._zod.def,catchall:v4()}),$.loose=()=>$.clone({...$._zod.def,catchall:v4()}),$.strict=()=>$.clone({...$._zod.def,catchall:gY()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(z)=>{return v.extend($,z)},$.safeExtend=(z)=>{return v.safeExtend($,z)},$.merge=(z)=>v.merge($,z),$.pick=(z)=>v.pick($,z),$.omit=(z)=>v.omit($,z),$.partial=(...z)=>v.partial(mY,$,z[0]),$.required=(...z)=>v.required(uY,$,z[0])});function v5($,U){let z={type:"object",get shape(){return v.assignProp(this,"shape",$?v.objectClone($):{}),this.shape},...v.normalizeParams(U)};return new N0(z)}function F5($,U){return new N0({type:"object",get shape(){return v.assignProp(this,"shape",v.objectClone($)),this.shape},catchall:gY(),...v.normalizeParams(U)})}function P5($,U){return new N0({type:"object",get shape(){return v.assignProp(this,"shape",v.objectClone($)),this.shape},catchall:v4(),...v.normalizeParams(U)})}var xY=V("ZodUnion",($,U)=>{EU.init($,U),i.init($,U),$.options=U.options});function fY($,U){return new xY({type:"union",options:$,...v.normalizeParams(U)})}var WO=V("ZodDiscriminatedUnion",($,U)=>{xY.init($,U),sz.init($,U)});function A5($,U,z){return new WO({type:"union",options:U,discriminator:$,...v.normalizeParams(z)})}var GO=V("ZodIntersection",($,U)=>{ez.init($,U),i.init($,U)});function QO($,U){return new GO({type:"intersection",left:$,right:U})}var wO=V("ZodTuple",($,U)=>{MU.init($,U),i.init($,U),$.rest=(z)=>$.clone({...$._zod.def,rest:z})});function HO($,U,z){let X=U instanceof c,J=X?z:U;return new wO({type:"tuple",items:$,rest:X?U:null,...v.normalizeParams(J)})}var hY=V("ZodRecord",($,U)=>{$X.init($,U),i.init($,U),$.keyType=U.keyType,$.valueType=U.valueType});function VO($,U,z){return new hY({type:"record",keyType:$,valueType:U,...v.normalizeParams(z)})}function E5($,U,z){let X=E$($);return X._zod.values=void 0,new hY({type:"record",keyType:X,valueType:U,...v.normalizeParams(z)})}var LO=V("ZodMap",($,U)=>{UX.init($,U),i.init($,U),$.keyType=U.keyType,$.valueType=U.valueType});function M5($,U,z){return new LO({type:"map",keyType:$,valueType:U,...v.normalizeParams(z)})}var BO=V("ZodSet",($,U)=>{JX.init($,U),i.init($,U),$.min=(...z)=>$.check(o6(...z)),$.nonempty=(z)=>$.check(o6(1,z)),$.max=(...z)=>$.check(D4(...z)),$.size=(...z)=>$.check(X1(...z))});function b5($,U){return new BO({type:"set",valueType:$,...v.normalizeParams(U)})}var K1=V("ZodEnum",($,U)=>{zX.init($,U),i.init($,U),$.enum=U.entries,$.options=Object.values(U.entries);let z=new Set(Object.keys(U.entries));$.extract=(X,J)=>{let j={};for(let Y of X)if(z.has(Y))j[Y]=U.entries[Y];else throw Error(`Key ${Y} not found in enum`);return new K1({...U,checks:[],...v.normalizeParams(J),entries:j})},$.exclude=(X,J)=>{let j={...U.entries};for(let Y of X)if(z.has(Y))delete j[Y];else throw Error(`Key ${Y} not found in enum`);return new K1({...U,checks:[],...v.normalizeParams(J),entries:j})}});function yY($,U){let z=Array.isArray($)?Object.fromEntries($.map((X)=>[X,X])):$;return new K1({type:"enum",entries:z,...v.normalizeParams(U)})}function R5($,U){return new K1({type:"enum",entries:$,...v.normalizeParams(U)})}var DO=V("ZodLiteral",($,U)=>{XX.init($,U),i.init($,U),$.values=new Set(U.values),Object.defineProperty($,"value",{get(){if(U.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return U.values[0]}})});function I5($,U){return new DO({type:"literal",values:Array.isArray($)?$:[$],...v.normalizeParams(U)})}var KO=V("ZodFile",($,U)=>{jX.init($,U),i.init($,U),$.min=(z,X)=>$.check(o6(z,X)),$.max=(z,X)=>$.check(D4(z,X)),$.mime=(z,X)=>$.check(Q1(Array.isArray(z)?z:[z],X))});function S5($){return oj(KO,$)}var qO=V("ZodTransform",($,U)=>{YX.init($,U),i.init($,U),$._zod.parse=(z,X)=>{if(X.direction==="backward")throw new l6($.constructor.name);z.addIssue=(j)=>{if(typeof j==="string")z.issues.push(v.issue(j,z.value,U));else{let Y=j;if(Y.fatal)Y.continue=!1;Y.code??(Y.code="custom"),Y.input??(Y.input=z.value),Y.inst??(Y.inst=$),z.issues.push(v.issue(Y))}};let J=U.transform(z.value,z);if(J instanceof Promise)return J.then((j)=>{return z.value=j,z});return z.value=J,z}});function cY($){return new qO({type:"transform",transform:$})}var mY=V("ZodOptional",($,U)=>{NX.init($,U),i.init($,U),$.unwrap=()=>$._zod.def.innerType});function U0($){return new mY({type:"optional",innerType:$})}var _O=V("ZodNullable",($,U)=>{OX.init($,U),i.init($,U),$.unwrap=()=>$._zod.def.innerType});function J0($){return new _O({type:"nullable",innerType:$})}function k5($){return U0(J0($))}var vO=V("ZodDefault",($,U)=>{WX.init($,U),i.init($,U),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function FO($,U){return new vO({type:"default",innerType:$,get defaultValue(){return typeof U==="function"?U():v.shallowClone(U)}})}var PO=V("ZodPrefault",($,U)=>{GX.init($,U),i.init($,U),$.unwrap=()=>$._zod.def.innerType});function AO($,U){return new PO({type:"prefault",innerType:$,get defaultValue(){return typeof U==="function"?U():v.shallowClone(U)}})}var uY=V("ZodNonOptional",($,U)=>{QX.init($,U),i.init($,U),$.unwrap=()=>$._zod.def.innerType});function EO($,U){return new uY({type:"nonoptional",innerType:$,...v.normalizeParams(U)})}var MO=V("ZodSuccess",($,U)=>{wX.init($,U),i.init($,U),$.unwrap=()=>$._zod.def.innerType});function C5($){return new MO({type:"success",innerType:$})}var bO=V("ZodCatch",($,U)=>{HX.init($,U),i.init($,U),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function RO($,U){return new bO({type:"catch",innerType:$,catchValue:typeof U==="function"?U:()=>U})}var IO=V("ZodNaN",($,U)=>{VX.init($,U),i.init($,U)});function Z5($){return uj(IO,$)}var iY=V("ZodPipe",($,U)=>{LX.init($,U),i.init($,U),$.in=U.in,$.out=U.out});function z0($,U){return new iY({type:"pipe",in:$,out:U})}var lY=V("ZodCodec",($,U)=>{iY.init($,U),d4.init($,U)});function T5($,U,z){return new lY({type:"pipe",in:$,out:U,transform:z.decode,reverseTransform:z.encode})}var SO=V("ZodReadonly",($,U)=>{BX.init($,U),i.init($,U),$.unwrap=()=>$._zod.def.innerType});function kO($){return new SO({type:"readonly",innerType:$})}var CO=V("ZodTemplateLiteral",($,U)=>{DX.init($,U),i.init($,U)});function g5($,U){return new CO({type:"template_literal",parts:$,...v.normalizeParams(U)})}var ZO=V("ZodLazy",($,U)=>{_X.init($,U),i.init($,U),$.unwrap=()=>$._zod.def.getter()});function TO($){return new ZO({type:"lazy",getter:$})}var gO=V("ZodPromise",($,U)=>{qX.init($,U),i.init($,U),$.unwrap=()=>$._zod.def.innerType});function x5($){return new gO({type:"promise",innerType:$})}var xO=V("ZodFunction",($,U)=>{KX.init($,U),i.init($,U)});function f5($){return new xO({type:"function",input:Array.isArray($?.input)?HO($?.input):$?.input??Y0(v4()),output:$?.output??v4()})}var O0=V("ZodCustom",($,U)=>{vX.init($,U),i.init($,U)});function h5($){let U=new j$({check:"custom"});return U._zod.check=$,U}function y5($,U){return tj(O0,$??(()=>!0),U)}function fO($,U={}){return aj(O0,$,U)}function hO($){return sj($)}function c5($,U={error:`Input not instance of ${$.name}`}){let z=new O0({type:"custom",check:"custom",fn:(X)=>X instanceof $,abort:!0,...v.normalizeParams(U)});return z._zod.bag.Class=$,z}var m5=(...$)=>ej({Codec:lY,Boolean:F1,String:q1},...$);function u5($){let U=TO(()=>{return fY([LY($),s9(),e9(),zO(),Y0(U),VO(LY(),U)])});return U}function i5($,U){return z0(cY($),U)}var l5={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function n5($){H$({customError:$})}function r5(){return H$().customError}var nY;(function($){})(nY||(nY={}));var rY={};w6(rY,{string:()=>p5,number:()=>d5,date:()=>a5,boolean:()=>o5,bigint:()=>t5});function p5($){return Vj(q1,$)}function d5($){return vj(v1,$)}function o5($){return Rj(F1,$)}function t5($){return Sj(P1,$)}function a5($){return mj(j0,$)}H$(o4());var s;(function($){$.assertEqual=(J)=>{};function U(J){}$.assertIs=U;function z(J){throw Error()}$.assertNever=z,$.arrayToEnum=(J)=>{let j={};for(let Y of J)j[Y]=Y;return j},$.getValidEnumValues=(J)=>{let j=$.objectKeys(J).filter((N)=>typeof J[J[N]]!=="number"),Y={};for(let N of j)Y[N]=J[N];return $.objectValues(Y)},$.objectValues=(J)=>{return $.objectKeys(J).map(function(j){return J[j]})},$.objectKeys=typeof Object.keys==="function"?(J)=>Object.keys(J):(J)=>{let j=[];for(let Y in J)if(Object.prototype.hasOwnProperty.call(J,Y))j.push(Y);return j},$.find=(J,j)=>{for(let Y of J)if(j(Y))return Y;return},$.isInteger=typeof Number.isInteger==="function"?(J)=>Number.isInteger(J):(J)=>typeof J==="number"&&Number.isFinite(J)&&Math.floor(J)===J;function X(J,j=" | "){return J.map((Y)=>typeof Y==="string"?`'${Y}'`:Y).join(j)}$.joinValues=X,$.jsonStringifyReplacer=(J,j)=>{if(typeof j==="bigint")return j.toString();return j}})(s||(s={}));var yO;(function($){$.mergeShapes=(U,z)=>{return{...U,...z}}})(yO||(yO={}));var M=s.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),K6=($)=>{switch(typeof $){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN($)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":if(Array.isArray($))return M.array;if($===null)return M.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return M.promise;if(typeof Map<"u"&&$ instanceof Map)return M.map;if(typeof Set<"u"&&$ instanceof Set)return M.set;if(typeof Date<"u"&&$ instanceof Date)return M.date;return M.object;default:return M.unknown}};var _=s.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class h$ extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(z)=>{this.issues=[...this.issues,z]},this.addIssues=(z=[])=>{this.issues=[...this.issues,...z]};let U=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,U);else this.__proto__=U;this.name="ZodError",this.issues=$}format($){let U=$||function(J){return J.message},z={_errors:[]},X=(J)=>{for(let j of J.issues)if(j.code==="invalid_union")j.unionErrors.map(X);else if(j.code==="invalid_return_type")X(j.returnTypeError);else if(j.code==="invalid_arguments")X(j.argumentsError);else if(j.path.length===0)z._errors.push(U(j));else{let Y=z,N=0;while(N<j.path.length){let W=j.path[N];if(N!==j.path.length-1)Y[W]=Y[W]||{_errors:[]};else Y[W]=Y[W]||{_errors:[]},Y[W]._errors.push(U(j));Y=Y[W],N++}}};return X(this),z}static assert($){if(!($ instanceof h$))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,s.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(U)=>U.message){let U={},z=[];for(let X of this.issues)if(X.path.length>0){let J=X.path[0];U[J]=U[J]||[],U[J].push($(X))}else z.push($(X));return{formErrors:z,fieldErrors:U}}get formErrors(){return this.flatten()}}h$.create=($)=>{return new h$($)};var s5=($,U)=>{let z;switch($.code){case _.invalid_type:if($.received===M.undefined)z="Required";else z=`Expected ${$.expected}, received ${$.received}`;break;case _.invalid_literal:z=`Invalid literal value, expected ${JSON.stringify($.expected,s.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:z=`Unrecognized key(s) in object: ${s.joinValues($.keys,", ")}`;break;case _.invalid_union:z="Invalid input";break;case _.invalid_union_discriminator:z=`Invalid discriminator value. Expected ${s.joinValues($.options)}`;break;case _.invalid_enum_value:z=`Invalid enum value. Expected ${s.joinValues($.options)}, received '${$.received}'`;break;case _.invalid_arguments:z="Invalid function arguments";break;case _.invalid_return_type:z="Invalid function return type";break;case _.invalid_date:z="Invalid date";break;case _.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(z=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")z=`${z} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)z=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)z=`Invalid input: must end with "${$.validation.endsWith}"`;else s.assertNever($.validation);else if($.validation!=="regex")z=`Invalid ${$.validation}`;else z="Invalid";break;case _.too_small:if($.type==="array")z=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")z=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")z=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")z=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")z=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else z="Invalid input";break;case _.too_big:if($.type==="array")z=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")z=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")z=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")z=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")z=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else z="Invalid input";break;case _.custom:z="Invalid input";break;case _.invalid_intersection_types:z="Intersection results could not be merged";break;case _.not_multiple_of:z=`Number must be a multiple of ${$.multipleOf}`;break;case _.not_finite:z="Number must be finite";break;default:z=U.defaultError,s.assertNever($)}return{message:z}},T6=s5;var e5=T6;function A1(){return e5}var W0=($)=>{let{data:U,path:z,errorMaps:X,issueData:J}=$,j=[...z,...J.path||[]],Y={...J,path:j};if(J.message!==void 0)return{...J,path:j,message:J.message};let N="",W=X.filter((G)=>!!G).slice().reverse();for(let G of W)N=G(Y,{data:U,defaultError:N}).message;return{...J,path:j,message:N}};function R($,U){let z=A1(),X=W0({issueData:U,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,z,z===T6?void 0:T6].filter((J)=>!!J)});$.common.issues.push(X)}class _${constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,U){let z=[];for(let X of U){if(X.status==="aborted")return x;if(X.status==="dirty")$.dirty();z.push(X.value)}return{status:$.value,value:z}}static async mergeObjectAsync($,U){let z=[];for(let X of U){let J=await X.key,j=await X.value;z.push({key:J,value:j})}return _$.mergeObjectSync($,z)}static mergeObjectSync($,U){let z={};for(let X of U){let{key:J,value:j}=X;if(J.status==="aborted")return x;if(j.status==="aborted")return x;if(J.status==="dirty")$.dirty();if(j.status==="dirty")$.dirty();if(J.value!=="__proto__"&&(typeof j.value<"u"||X.alwaysSet))z[J.value]=j.value}return{status:$.value,value:z}}}var x=Object.freeze({status:"aborted"}),P4=($)=>({status:"dirty",value:$}),M$=($)=>({status:"valid",value:$}),pY=($)=>$.status==="aborted",dY=($)=>$.status==="dirty",t6=($)=>$.status==="valid",E1=($)=>typeof Promise<"u"&&$ instanceof Promise;var C;(function($){$.errToObj=(U)=>typeof U==="string"?{message:U}:U||{},$.toString=(U)=>typeof U==="string"?U:U?.message})(C||(C={}));class d${constructor($,U,z,X){this._cachedPath=[],this.parent=$,this.data=U,this._path=z,this._key=X}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 cO=($,U)=>{if(t6(U))return{success:!0,data:U.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 z=new h$($.common.issues);return this._error=z,this._error}}}};function u($){if(!$)return{};let{errorMap:U,invalid_type_error:z,required_error:X,description:J}=$;if(U&&(z||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(U)return{errorMap:U,description:J};return{errorMap:(Y,N)=>{let{message:W}=$;if(Y.code==="invalid_enum_value")return{message:W??N.defaultError};if(typeof N.data>"u")return{message:W??X??N.defaultError};if(Y.code!=="invalid_type")return{message:N.defaultError};return{message:W??z??N.defaultError}},description:J}}class o{get description(){return this._def.description}_getType($){return K6($.data)}_getOrReturnCtx($,U){return U||{common:$.parent.common,data:$.data,parsedType:K6($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new _$,ctx:{common:$.parent.common,data:$.data,parsedType:K6($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let U=this._parse($);if(E1(U))throw Error("Synchronous parse encountered promise.");return U}_parseAsync($){let U=this._parse($);return Promise.resolve(U)}parse($,U){let z=this.safeParse($,U);if(z.success)return z.data;throw z.error}safeParse($,U){let z={common:{issues:[],async:U?.async??!1,contextualErrorMap:U?.errorMap},path:U?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:K6($)},X=this._parseSync({data:$,path:z.path,parent:z});return cO(z,X)}"~validate"($){let U={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:K6($)};if(!this["~standard"].async)try{let z=this._parseSync({data:$,path:[],parent:U});return t6(z)?{value:z.value}:{issues:U.common.issues}}catch(z){if(z?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;U.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:U}).then((z)=>t6(z)?{value:z.value}:{issues:U.common.issues})}async parseAsync($,U){let z=await this.safeParseAsync($,U);if(z.success)return z.data;throw z.error}async safeParseAsync($,U){let z={common:{issues:[],contextualErrorMap:U?.errorMap,async:!0},path:U?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:K6($)},X=this._parse({data:$,path:z.path,parent:z}),J=await(E1(X)?X:Promise.resolve(X));return cO(z,J)}refine($,U){let z=(X)=>{if(typeof U==="string"||typeof U>"u")return{message:U};else if(typeof U==="function")return U(X);else return U};return this._refinement((X,J)=>{let j=$(X),Y=()=>J.addIssue({code:_.custom,...z(X)});if(typeof Promise<"u"&&j instanceof Promise)return j.then((N)=>{if(!N)return Y(),!1;else return!0});if(!j)return Y(),!1;else return!0})}refinement($,U){return this._refinement((z,X)=>{if(!$(z))return X.addIssue(typeof U==="function"?U(z,X):U),!1;else return!0})}_refinement($){return new X6({schema:this,typeName:F.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:(U)=>this["~validate"](U)}}optional(){return z6.create(this,this._def)}nullable(){return g6.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return J6.create(this)}promise(){return R4.create(this,this._def)}or($){return S1.create([this,$],this._def)}and($){return k1.create(this,$,this._def)}transform($){return new X6({...u(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:$}})}default($){let U=typeof $==="function"?$:()=>$;return new g1({...u(this._def),innerType:this,defaultValue:U,typeName:F.ZodDefault})}brand(){return new sY({typeName:F.ZodBranded,type:this,...u(this._def)})}catch($){let U=typeof $==="function"?$:()=>$;return new x1({...u(this._def),innerType:this,catchValue:U,typeName:F.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return D0.create(this,$)}readonly(){return f1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var $H=/^c[^\s-]{8,}$/i,UH=/^[0-9a-z]+$/,JH=/^[0-9A-HJKMNP-TV-Z]{26}$/i,zH=/^[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,XH=/^[a-z0-9_-]{21}$/i,jH=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,YH=/^[-+]?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)?)??$/,NH=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,OH="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",oY,WH=/^(?:(?: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])$/,GH=/^(?:(?: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])$/,QH=/^(([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]))$/,wH=/^(([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])$/,HH=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,VH=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mO="((\\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])))",LH=new RegExp(`^${mO}$`);function uO($){let U="[0-5]\\d";if($.precision)U=`${U}\\.\\d{${$.precision}}`;else if($.precision==null)U=`${U}(\\.\\d+)?`;let z=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${U})${z}`}function BH($){return new RegExp(`^${uO($)}$`)}function DH($){let U=`${mO}T${uO($)}`,z=[];if(z.push($.local?"Z?":"Z"),$.offset)z.push("([+-]\\d{2}:?\\d{2})");return U=`${U}(${z.join("|")})`,new RegExp(`^${U}$`)}function KH($,U){if((U==="v4"||!U)&&WH.test($))return!0;if((U==="v6"||!U)&&QH.test($))return!0;return!1}function qH($,U){if(!jH.test($))return!1;try{let[z]=$.split(".");if(!z)return!1;let X=z.replace(/-/g,"+").replace(/_/g,"/").padEnd(z.length+(4-z.length%4)%4,"="),J=JSON.parse(atob(X));if(typeof J!=="object"||J===null)return!1;if("typ"in J&&J?.typ!=="JWT")return!1;if(!J.alg)return!1;if(U&&J.alg!==U)return!1;return!0}catch{return!1}}function _H($,U){if((U==="v4"||!U)&&GH.test($))return!0;if((U==="v6"||!U)&&wH.test($))return!0;return!1}class _6 extends o{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==M.string){let J=this._getOrReturnCtx($);return R(J,{code:_.invalid_type,expected:M.string,received:J.parsedType}),x}let z=new _$,X=void 0;for(let J of this._def.checks)if(J.kind==="min"){if($.data.length<J.value)X=this._getOrReturnCtx($,X),R(X,{code:_.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),z.dirty()}else if(J.kind==="max"){if($.data.length>J.value)X=this._getOrReturnCtx($,X),R(X,{code:_.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),z.dirty()}else if(J.kind==="length"){let j=$.data.length>J.value,Y=$.data.length<J.value;if(j||Y){if(X=this._getOrReturnCtx($,X),j)R(X,{code:_.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});else if(Y)R(X,{code:_.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});z.dirty()}}else if(J.kind==="email"){if(!NH.test($.data))X=this._getOrReturnCtx($,X),R(X,{validation:"email",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="emoji"){if(!oY)oY=new RegExp(OH,"u");if(!oY.test($.data))X=this._getOrReturnCtx($,X),R(X,{validation:"emoji",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="uuid"){if(!zH.test($.data))X=this._getOrReturnCtx($,X),R(X,{validation:"uuid",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="nanoid"){if(!XH.test($.data))X=this._getOrReturnCtx($,X),R(X,{validation:"nanoid",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="cuid"){if(!$H.test($.data))X=this._getOrReturnCtx($,X),R(X,{validation:"cuid",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="cuid2"){if(!UH.test($.data))X=this._getOrReturnCtx($,X),R(X,{validation:"cuid2",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="ulid"){if(!JH.test($.data))X=this._getOrReturnCtx($,X),R(X,{validation:"ulid",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="url")try{new URL($.data)}catch{X=this._getOrReturnCtx($,X),R(X,{validation:"url",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="regex"){if(J.regex.lastIndex=0,!J.regex.test($.data))X=this._getOrReturnCtx($,X),R(X,{validation:"regex",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="trim")$.data=$.data.trim();else if(J.kind==="includes"){if(!$.data.includes(J.value,J.position))X=this._getOrReturnCtx($,X),R(X,{code:_.invalid_string,validation:{includes:J.value,position:J.position},message:J.message}),z.dirty()}else if(J.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(J.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(J.kind==="startsWith"){if(!$.data.startsWith(J.value))X=this._getOrReturnCtx($,X),R(X,{code:_.invalid_string,validation:{startsWith:J.value},message:J.message}),z.dirty()}else if(J.kind==="endsWith"){if(!$.data.endsWith(J.value))X=this._getOrReturnCtx($,X),R(X,{code:_.invalid_string,validation:{endsWith:J.value},message:J.message}),z.dirty()}else if(J.kind==="datetime"){if(!DH(J).test($.data))X=this._getOrReturnCtx($,X),R(X,{code:_.invalid_string,validation:"datetime",message:J.message}),z.dirty()}else if(J.kind==="date"){if(!LH.test($.data))X=this._getOrReturnCtx($,X),R(X,{code:_.invalid_string,validation:"date",message:J.message}),z.dirty()}else if(J.kind==="time"){if(!BH(J).test($.data))X=this._getOrReturnCtx($,X),R(X,{code:_.invalid_string,validation:"time",message:J.message}),z.dirty()}else if(J.kind==="duration"){if(!YH.test($.data))X=this._getOrReturnCtx($,X),R(X,{validation:"duration",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="ip"){if(!KH($.data,J.version))X=this._getOrReturnCtx($,X),R(X,{validation:"ip",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="jwt"){if(!qH($.data,J.alg))X=this._getOrReturnCtx($,X),R(X,{validation:"jwt",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="cidr"){if(!_H($.data,J.version))X=this._getOrReturnCtx($,X),R(X,{validation:"cidr",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="base64"){if(!HH.test($.data))X=this._getOrReturnCtx($,X),R(X,{validation:"base64",code:_.invalid_string,message:J.message}),z.dirty()}else if(J.kind==="base64url"){if(!VH.test($.data))X=this._getOrReturnCtx($,X),R(X,{validation:"base64url",code:_.invalid_string,message:J.message}),z.dirty()}else s.assertNever(J);return{status:z.value,value:$.data}}_regex($,U,z){return this.refinement((X)=>$.test(X),{validation:U,code:_.invalid_string,...C.errToObj(z)})}_addCheck($){return new _6({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...C.errToObj($)})}url($){return this._addCheck({kind:"url",...C.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...C.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...C.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...C.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...C.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...C.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...C.errToObj($)})}base64($){return this._addCheck({kind:"base64",...C.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...C.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...C.errToObj($)})}ip($){return this._addCheck({kind:"ip",...C.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...C.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,...C.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,...C.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...C.errToObj($)})}regex($,U){return this._addCheck({kind:"regex",regex:$,...C.errToObj(U)})}includes($,U){return this._addCheck({kind:"includes",value:$,position:U?.position,...C.errToObj(U?.message)})}startsWith($,U){return this._addCheck({kind:"startsWith",value:$,...C.errToObj(U)})}endsWith($,U){return this._addCheck({kind:"endsWith",value:$,...C.errToObj(U)})}min($,U){return this._addCheck({kind:"min",value:$,...C.errToObj(U)})}max($,U){return this._addCheck({kind:"max",value:$,...C.errToObj(U)})}length($,U){return this._addCheck({kind:"length",value:$,...C.errToObj(U)})}nonempty($){return this.min(1,C.errToObj($))}trim(){return new _6({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new _6({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new _6({...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 U of this._def.checks)if(U.kind==="min"){if($===null||U.value>$)$=U.value}return $}get maxLength(){let $=null;for(let U of this._def.checks)if(U.kind==="max"){if($===null||U.value<$)$=U.value}return $}}_6.create=($)=>{return new _6({checks:[],typeName:F.ZodString,coerce:$?.coerce??!1,...u($)})};function vH($,U){let z=($.toString().split(".")[1]||"").length,X=(U.toString().split(".")[1]||"").length,J=z>X?z:X,j=Number.parseInt($.toFixed(J).replace(".","")),Y=Number.parseInt(U.toFixed(J).replace(".",""));return j%Y/10**J}class E4 extends o{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($)!==M.number){let J=this._getOrReturnCtx($);return R(J,{code:_.invalid_type,expected:M.number,received:J.parsedType}),x}let z=void 0,X=new _$;for(let J of this._def.checks)if(J.kind==="int"){if(!s.isInteger($.data))z=this._getOrReturnCtx($,z),R(z,{code:_.invalid_type,expected:"integer",received:"float",message:J.message}),X.dirty()}else if(J.kind==="min"){if(J.inclusive?$.data<J.value:$.data<=J.value)z=this._getOrReturnCtx($,z),R(z,{code:_.too_small,minimum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),X.dirty()}else if(J.kind==="max"){if(J.inclusive?$.data>J.value:$.data>=J.value)z=this._getOrReturnCtx($,z),R(z,{code:_.too_big,maximum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),X.dirty()}else if(J.kind==="multipleOf"){if(vH($.data,J.value)!==0)z=this._getOrReturnCtx($,z),R(z,{code:_.not_multiple_of,multipleOf:J.value,message:J.message}),X.dirty()}else if(J.kind==="finite"){if(!Number.isFinite($.data))z=this._getOrReturnCtx($,z),R(z,{code:_.not_finite,message:J.message}),X.dirty()}else s.assertNever(J);return{status:X.value,value:$.data}}gte($,U){return this.setLimit("min",$,!0,C.toString(U))}gt($,U){return this.setLimit("min",$,!1,C.toString(U))}lte($,U){return this.setLimit("max",$,!0,C.toString(U))}lt($,U){return this.setLimit("max",$,!1,C.toString(U))}setLimit($,U,z,X){return new E4({...this._def,checks:[...this._def.checks,{kind:$,value:U,inclusive:z,message:C.toString(X)}]})}_addCheck($){return new E4({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:C.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString($)})}multipleOf($,U){return this._addCheck({kind:"multipleOf",value:$,message:C.toString(U)})}finite($){return this._addCheck({kind:"finite",message:C.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString($)})}get minValue(){let $=null;for(let U of this._def.checks)if(U.kind==="min"){if($===null||U.value>$)$=U.value}return $}get maxValue(){let $=null;for(let U of this._def.checks)if(U.kind==="max"){if($===null||U.value<$)$=U.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&s.isInteger($.value))}get isFinite(){let $=null,U=null;for(let z of this._def.checks)if(z.kind==="finite"||z.kind==="int"||z.kind==="multipleOf")return!0;else if(z.kind==="min"){if(U===null||z.value>U)U=z.value}else if(z.kind==="max"){if($===null||z.value<$)$=z.value}return Number.isFinite(U)&&Number.isFinite($)}}E4.create=($)=>{return new E4({checks:[],typeName:F.ZodNumber,coerce:$?.coerce||!1,...u($)})};class M4 extends o{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($)!==M.bigint)return this._getInvalidInput($);let z=void 0,X=new _$;for(let J of this._def.checks)if(J.kind==="min"){if(J.inclusive?$.data<J.value:$.data<=J.value)z=this._getOrReturnCtx($,z),R(z,{code:_.too_small,type:"bigint",minimum:J.value,inclusive:J.inclusive,message:J.message}),X.dirty()}else if(J.kind==="max"){if(J.inclusive?$.data>J.value:$.data>=J.value)z=this._getOrReturnCtx($,z),R(z,{code:_.too_big,type:"bigint",maximum:J.value,inclusive:J.inclusive,message:J.message}),X.dirty()}else if(J.kind==="multipleOf"){if($.data%J.value!==BigInt(0))z=this._getOrReturnCtx($,z),R(z,{code:_.not_multiple_of,multipleOf:J.value,message:J.message}),X.dirty()}else s.assertNever(J);return{status:X.value,value:$.data}}_getInvalidInput($){let U=this._getOrReturnCtx($);return R(U,{code:_.invalid_type,expected:M.bigint,received:U.parsedType}),x}gte($,U){return this.setLimit("min",$,!0,C.toString(U))}gt($,U){return this.setLimit("min",$,!1,C.toString(U))}lte($,U){return this.setLimit("max",$,!0,C.toString(U))}lt($,U){return this.setLimit("max",$,!1,C.toString(U))}setLimit($,U,z,X){return new M4({...this._def,checks:[...this._def.checks,{kind:$,value:U,inclusive:z,message:C.toString(X)}]})}_addCheck($){return new M4({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString($)})}multipleOf($,U){return this._addCheck({kind:"multipleOf",value:$,message:C.toString(U)})}get minValue(){let $=null;for(let U of this._def.checks)if(U.kind==="min"){if($===null||U.value>$)$=U.value}return $}get maxValue(){let $=null;for(let U of this._def.checks)if(U.kind==="max"){if($===null||U.value<$)$=U.value}return $}}M4.create=($)=>{return new M4({checks:[],typeName:F.ZodBigInt,coerce:$?.coerce??!1,...u($)})};class G0 extends o{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==M.boolean){let z=this._getOrReturnCtx($);return R(z,{code:_.invalid_type,expected:M.boolean,received:z.parsedType}),x}return M$($.data)}}G0.create=($)=>{return new G0({typeName:F.ZodBoolean,coerce:$?.coerce||!1,...u($)})};class b1 extends o{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==M.date){let J=this._getOrReturnCtx($);return R(J,{code:_.invalid_type,expected:M.date,received:J.parsedType}),x}if(Number.isNaN($.data.getTime())){let J=this._getOrReturnCtx($);return R(J,{code:_.invalid_date}),x}let z=new _$,X=void 0;for(let J of this._def.checks)if(J.kind==="min"){if($.data.getTime()<J.value)X=this._getOrReturnCtx($,X),R(X,{code:_.too_small,message:J.message,inclusive:!0,exact:!1,minimum:J.value,type:"date"}),z.dirty()}else if(J.kind==="max"){if($.data.getTime()>J.value)X=this._getOrReturnCtx($,X),R(X,{code:_.too_big,message:J.message,inclusive:!0,exact:!1,maximum:J.value,type:"date"}),z.dirty()}else s.assertNever(J);return{status:z.value,value:new Date($.data.getTime())}}_addCheck($){return new b1({...this._def,checks:[...this._def.checks,$]})}min($,U){return this._addCheck({kind:"min",value:$.getTime(),message:C.toString(U)})}max($,U){return this._addCheck({kind:"max",value:$.getTime(),message:C.toString(U)})}get minDate(){let $=null;for(let U of this._def.checks)if(U.kind==="min"){if($===null||U.value>$)$=U.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let U of this._def.checks)if(U.kind==="max"){if($===null||U.value<$)$=U.value}return $!=null?new Date($):null}}b1.create=($)=>{return new b1({checks:[],coerce:$?.coerce||!1,typeName:F.ZodDate,...u($)})};class Q0 extends o{_parse($){if(this._getType($)!==M.symbol){let z=this._getOrReturnCtx($);return R(z,{code:_.invalid_type,expected:M.symbol,received:z.parsedType}),x}return M$($.data)}}Q0.create=($)=>{return new Q0({typeName:F.ZodSymbol,...u($)})};class R1 extends o{_parse($){if(this._getType($)!==M.undefined){let z=this._getOrReturnCtx($);return R(z,{code:_.invalid_type,expected:M.undefined,received:z.parsedType}),x}return M$($.data)}}R1.create=($)=>{return new R1({typeName:F.ZodUndefined,...u($)})};class I1 extends o{_parse($){if(this._getType($)!==M.null){let z=this._getOrReturnCtx($);return R(z,{code:_.invalid_type,expected:M.null,received:z.parsedType}),x}return M$($.data)}}I1.create=($)=>{return new I1({typeName:F.ZodNull,...u($)})};class w0 extends o{constructor(){super(...arguments);this._any=!0}_parse($){return M$($.data)}}w0.create=($)=>{return new w0({typeName:F.ZodAny,...u($)})};class a6 extends o{constructor(){super(...arguments);this._unknown=!0}_parse($){return M$($.data)}}a6.create=($)=>{return new a6({typeName:F.ZodUnknown,...u($)})};class v6 extends o{_parse($){let U=this._getOrReturnCtx($);return R(U,{code:_.invalid_type,expected:M.never,received:U.parsedType}),x}}v6.create=($)=>{return new v6({typeName:F.ZodNever,...u($)})};class H0 extends o{_parse($){if(this._getType($)!==M.undefined){let z=this._getOrReturnCtx($);return R(z,{code:_.invalid_type,expected:M.void,received:z.parsedType}),x}return M$($.data)}}H0.create=($)=>{return new H0({typeName:F.ZodVoid,...u($)})};class J6 extends o{_parse($){let{ctx:U,status:z}=this._processInputParams($),X=this._def;if(U.parsedType!==M.array)return R(U,{code:_.invalid_type,expected:M.array,received:U.parsedType}),x;if(X.exactLength!==null){let j=U.data.length>X.exactLength.value,Y=U.data.length<X.exactLength.value;if(j||Y)R(U,{code:j?_.too_big:_.too_small,minimum:Y?X.exactLength.value:void 0,maximum:j?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),z.dirty()}if(X.minLength!==null){if(U.data.length<X.minLength.value)R(U,{code:_.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),z.dirty()}if(X.maxLength!==null){if(U.data.length>X.maxLength.value)R(U,{code:_.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),z.dirty()}if(U.common.async)return Promise.all([...U.data].map((j,Y)=>{return X.type._parseAsync(new d$(U,j,U.path,Y))})).then((j)=>{return _$.mergeArray(z,j)});let J=[...U.data].map((j,Y)=>{return X.type._parseSync(new d$(U,j,U.path,Y))});return _$.mergeArray(z,J)}get element(){return this._def.type}min($,U){return new J6({...this._def,minLength:{value:$,message:C.toString(U)}})}max($,U){return new J6({...this._def,maxLength:{value:$,message:C.toString(U)}})}length($,U){return new J6({...this._def,exactLength:{value:$,message:C.toString(U)}})}nonempty($){return this.min(1,$)}}J6.create=($,U)=>{return new J6({type:$,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...u(U)})};function A4($){if($ instanceof G$){let U={};for(let z in $.shape){let X=$.shape[z];U[z]=z6.create(A4(X))}return new G$({...$._def,shape:()=>U})}else if($ instanceof J6)return new J6({...$._def,type:A4($.element)});else if($ instanceof z6)return z6.create(A4($.unwrap()));else if($ instanceof g6)return g6.create(A4($.unwrap()));else if($ instanceof F6)return F6.create($.items.map((U)=>A4(U)));else return $}class G$ extends o{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(),U=s.objectKeys($);return this._cached={shape:$,keys:U},this._cached}_parse($){if(this._getType($)!==M.object){let W=this._getOrReturnCtx($);return R(W,{code:_.invalid_type,expected:M.object,received:W.parsedType}),x}let{status:z,ctx:X}=this._processInputParams($),{shape:J,keys:j}=this._getCached(),Y=[];if(!(this._def.catchall instanceof v6&&this._def.unknownKeys==="strip")){for(let W in X.data)if(!j.includes(W))Y.push(W)}let N=[];for(let W of j){let G=J[W],Q=X.data[W];N.push({key:{status:"valid",value:W},value:G._parse(new d$(X,Q,X.path,W)),alwaysSet:W in X.data})}if(this._def.catchall instanceof v6){let W=this._def.unknownKeys;if(W==="passthrough")for(let G of Y)N.push({key:{status:"valid",value:G},value:{status:"valid",value:X.data[G]}});else if(W==="strict"){if(Y.length>0)R(X,{code:_.unrecognized_keys,keys:Y}),z.dirty()}else if(W==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let W=this._def.catchall;for(let G of Y){let Q=X.data[G];N.push({key:{status:"valid",value:G},value:W._parse(new d$(X,Q,X.path,G)),alwaysSet:G in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let W=[];for(let G of N){let Q=await G.key,L=await G.value;W.push({key:Q,value:L,alwaysSet:G.alwaysSet})}return W}).then((W)=>{return _$.mergeObjectSync(z,W)});else return _$.mergeObjectSync(z,N)}get shape(){return this._def.shape()}strict($){return C.errToObj,new G$({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(U,z)=>{let X=this._def.errorMap?.(U,z).message??z.defaultError;if(U.code==="unrecognized_keys")return{message:C.errToObj($).message??X};return{message:X}}}:{}})}strip(){return new G$({...this._def,unknownKeys:"strip"})}passthrough(){return new G$({...this._def,unknownKeys:"passthrough"})}extend($){return new G$({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new G$({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:F.ZodObject})}setKey($,U){return this.augment({[$]:U})}catchall($){return new G$({...this._def,catchall:$})}pick($){let U={};for(let z of s.objectKeys($))if($[z]&&this.shape[z])U[z]=this.shape[z];return new G$({...this._def,shape:()=>U})}omit($){let U={};for(let z of s.objectKeys(this.shape))if(!$[z])U[z]=this.shape[z];return new G$({...this._def,shape:()=>U})}deepPartial(){return A4(this)}partial($){let U={};for(let z of s.objectKeys(this.shape)){let X=this.shape[z];if($&&!$[z])U[z]=X;else U[z]=X.optional()}return new G$({...this._def,shape:()=>U})}required($){let U={};for(let z of s.objectKeys(this.shape))if($&&!$[z])U[z]=this.shape[z];else{let J=this.shape[z];while(J instanceof z6)J=J._def.innerType;U[z]=J}return new G$({...this._def,shape:()=>U})}keyof(){return iO(s.objectKeys(this.shape))}}G$.create=($,U)=>{return new G$({shape:()=>$,unknownKeys:"strip",catchall:v6.create(),typeName:F.ZodObject,...u(U)})};G$.strictCreate=($,U)=>{return new G$({shape:()=>$,unknownKeys:"strict",catchall:v6.create(),typeName:F.ZodObject,...u(U)})};G$.lazycreate=($,U)=>{return new G$({shape:$,unknownKeys:"strip",catchall:v6.create(),typeName:F.ZodObject,...u(U)})};class S1 extends o{_parse($){let{ctx:U}=this._processInputParams($),z=this._def.options;function X(J){for(let Y of J)if(Y.result.status==="valid")return Y.result;for(let Y of J)if(Y.result.status==="dirty")return U.common.issues.push(...Y.ctx.common.issues),Y.result;let j=J.map((Y)=>new h$(Y.ctx.common.issues));return R(U,{code:_.invalid_union,unionErrors:j}),x}if(U.common.async)return Promise.all(z.map(async(J)=>{let j={...U,common:{...U.common,issues:[]},parent:null};return{result:await J._parseAsync({data:U.data,path:U.path,parent:j}),ctx:j}})).then(X);else{let J=void 0,j=[];for(let N of z){let W={...U,common:{...U.common,issues:[]},parent:null},G=N._parseSync({data:U.data,path:U.path,parent:W});if(G.status==="valid")return G;else if(G.status==="dirty"&&!J)J={result:G,ctx:W};if(W.common.issues.length)j.push(W.common.issues)}if(J)return U.common.issues.push(...J.ctx.common.issues),J.result;let Y=j.map((N)=>new h$(N));return R(U,{code:_.invalid_union,unionErrors:Y}),x}}get options(){return this._def.options}}S1.create=($,U)=>{return new S1({options:$,typeName:F.ZodUnion,...u(U)})};var q6=($)=>{if($ instanceof C1)return q6($.schema);else if($ instanceof X6)return q6($.innerType());else if($ instanceof Z1)return[$.value];else if($ instanceof s6)return $.options;else if($ instanceof T1)return s.objectValues($.enum);else if($ instanceof g1)return q6($._def.innerType);else if($ instanceof R1)return[void 0];else if($ instanceof I1)return[null];else if($ instanceof z6)return[void 0,...q6($.unwrap())];else if($ instanceof g6)return[null,...q6($.unwrap())];else if($ instanceof sY)return q6($.unwrap());else if($ instanceof f1)return q6($.unwrap());else if($ instanceof x1)return q6($._def.innerType);else return[]};class aY extends o{_parse($){let{ctx:U}=this._processInputParams($);if(U.parsedType!==M.object)return R(U,{code:_.invalid_type,expected:M.object,received:U.parsedType}),x;let z=this.discriminator,X=U.data[z],J=this.optionsMap.get(X);if(!J)return R(U,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[z]}),x;if(U.common.async)return J._parseAsync({data:U.data,path:U.path,parent:U});else return J._parseSync({data:U.data,path:U.path,parent:U})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,U,z){let X=new Map;for(let J of U){let j=q6(J.shape[$]);if(!j.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let Y of j){if(X.has(Y))throw Error(`Discriminator property ${String($)} has duplicate value ${String(Y)}`);X.set(Y,J)}}return new aY({typeName:F.ZodDiscriminatedUnion,discriminator:$,options:U,optionsMap:X,...u(z)})}}function tY($,U){let z=K6($),X=K6(U);if($===U)return{valid:!0,data:$};else if(z===M.object&&X===M.object){let J=s.objectKeys(U),j=s.objectKeys($).filter((N)=>J.indexOf(N)!==-1),Y={...$,...U};for(let N of j){let W=tY($[N],U[N]);if(!W.valid)return{valid:!1};Y[N]=W.data}return{valid:!0,data:Y}}else if(z===M.array&&X===M.array){if($.length!==U.length)return{valid:!1};let J=[];for(let j=0;j<$.length;j++){let Y=$[j],N=U[j],W=tY(Y,N);if(!W.valid)return{valid:!1};J.push(W.data)}return{valid:!0,data:J}}else if(z===M.date&&X===M.date&&+$===+U)return{valid:!0,data:$};else return{valid:!1}}class k1 extends o{_parse($){let{status:U,ctx:z}=this._processInputParams($),X=(J,j)=>{if(pY(J)||pY(j))return x;let Y=tY(J.value,j.value);if(!Y.valid)return R(z,{code:_.invalid_intersection_types}),x;if(dY(J)||dY(j))U.dirty();return{status:U.value,value:Y.data}};if(z.common.async)return Promise.all([this._def.left._parseAsync({data:z.data,path:z.path,parent:z}),this._def.right._parseAsync({data:z.data,path:z.path,parent:z})]).then(([J,j])=>X(J,j));else return X(this._def.left._parseSync({data:z.data,path:z.path,parent:z}),this._def.right._parseSync({data:z.data,path:z.path,parent:z}))}}k1.create=($,U,z)=>{return new k1({left:$,right:U,typeName:F.ZodIntersection,...u(z)})};class F6 extends o{_parse($){let{status:U,ctx:z}=this._processInputParams($);if(z.parsedType!==M.array)return R(z,{code:_.invalid_type,expected:M.array,received:z.parsedType}),x;if(z.data.length<this._def.items.length)return R(z,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),x;if(!this._def.rest&&z.data.length>this._def.items.length)R(z,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U.dirty();let J=[...z.data].map((j,Y)=>{let N=this._def.items[Y]||this._def.rest;if(!N)return null;return N._parse(new d$(z,j,z.path,Y))}).filter((j)=>!!j);if(z.common.async)return Promise.all(J).then((j)=>{return _$.mergeArray(U,j)});else return _$.mergeArray(U,J)}get items(){return this._def.items}rest($){return new F6({...this._def,rest:$})}}F6.create=($,U)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new F6({items:$,typeName:F.ZodTuple,rest:null,...u(U)})};class V0 extends o{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:U,ctx:z}=this._processInputParams($);if(z.parsedType!==M.object)return R(z,{code:_.invalid_type,expected:M.object,received:z.parsedType}),x;let X=[],J=this._def.keyType,j=this._def.valueType;for(let Y in z.data)X.push({key:J._parse(new d$(z,Y,z.path,Y)),value:j._parse(new d$(z,z.data[Y],z.path,Y)),alwaysSet:Y in z.data});if(z.common.async)return _$.mergeObjectAsync(U,X);else return _$.mergeObjectSync(U,X)}get element(){return this._def.valueType}static create($,U,z){if(U instanceof o)return new V0({keyType:$,valueType:U,typeName:F.ZodRecord,...u(z)});return new V0({keyType:_6.create(),valueType:$,typeName:F.ZodRecord,...u(U)})}}class L0 extends o{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:U,ctx:z}=this._processInputParams($);if(z.parsedType!==M.map)return R(z,{code:_.invalid_type,expected:M.map,received:z.parsedType}),x;let X=this._def.keyType,J=this._def.valueType,j=[...z.data.entries()].map(([Y,N],W)=>{return{key:X._parse(new d$(z,Y,z.path,[W,"key"])),value:J._parse(new d$(z,N,z.path,[W,"value"]))}});if(z.common.async){let Y=new Map;return Promise.resolve().then(async()=>{for(let N of j){let W=await N.key,G=await N.value;if(W.status==="aborted"||G.status==="aborted")return x;if(W.status==="dirty"||G.status==="dirty")U.dirty();Y.set(W.value,G.value)}return{status:U.value,value:Y}})}else{let Y=new Map;for(let N of j){let{key:W,value:G}=N;if(W.status==="aborted"||G.status==="aborted")return x;if(W.status==="dirty"||G.status==="dirty")U.dirty();Y.set(W.value,G.value)}return{status:U.value,value:Y}}}}L0.create=($,U,z)=>{return new L0({valueType:U,keyType:$,typeName:F.ZodMap,...u(z)})};class b4 extends o{_parse($){let{status:U,ctx:z}=this._processInputParams($);if(z.parsedType!==M.set)return R(z,{code:_.invalid_type,expected:M.set,received:z.parsedType}),x;let X=this._def;if(X.minSize!==null){if(z.data.size<X.minSize.value)R(z,{code:_.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),U.dirty()}if(X.maxSize!==null){if(z.data.size>X.maxSize.value)R(z,{code:_.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),U.dirty()}let J=this._def.valueType;function j(N){let W=new Set;for(let G of N){if(G.status==="aborted")return x;if(G.status==="dirty")U.dirty();W.add(G.value)}return{status:U.value,value:W}}let Y=[...z.data.values()].map((N,W)=>J._parse(new d$(z,N,z.path,W)));if(z.common.async)return Promise.all(Y).then((N)=>j(N));else return j(Y)}min($,U){return new b4({...this._def,minSize:{value:$,message:C.toString(U)}})}max($,U){return new b4({...this._def,maxSize:{value:$,message:C.toString(U)}})}size($,U){return this.min($,U).max($,U)}nonempty($){return this.min(1,$)}}b4.create=($,U)=>{return new b4({valueType:$,minSize:null,maxSize:null,typeName:F.ZodSet,...u(U)})};class M1 extends o{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:U}=this._processInputParams($);if(U.parsedType!==M.function)return R(U,{code:_.invalid_type,expected:M.function,received:U.parsedType}),x;function z(Y,N){return W0({data:Y,path:U.path,errorMaps:[U.common.contextualErrorMap,U.schemaErrorMap,A1(),T6].filter((W)=>!!W),issueData:{code:_.invalid_arguments,argumentsError:N}})}function X(Y,N){return W0({data:Y,path:U.path,errorMaps:[U.common.contextualErrorMap,U.schemaErrorMap,A1(),T6].filter((W)=>!!W),issueData:{code:_.invalid_return_type,returnTypeError:N}})}let J={errorMap:U.common.contextualErrorMap},j=U.data;if(this._def.returns instanceof R4){let Y=this;return M$(async function(...N){let W=new h$([]),G=await Y._def.args.parseAsync(N,J).catch((H)=>{throw W.addIssue(z(N,H)),W}),Q=await Reflect.apply(j,this,G);return await Y._def.returns._def.type.parseAsync(Q,J).catch((H)=>{throw W.addIssue(X(Q,H)),W})})}else{let Y=this;return M$(function(...N){let W=Y._def.args.safeParse(N,J);if(!W.success)throw new h$([z(N,W.error)]);let G=Reflect.apply(j,this,W.data),Q=Y._def.returns.safeParse(G,J);if(!Q.success)throw new h$([X(G,Q.error)]);return Q.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new M1({...this._def,args:F6.create($).rest(a6.create())})}returns($){return new M1({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,U,z){return new M1({args:$?$:F6.create([]).rest(a6.create()),returns:U||a6.create(),typeName:F.ZodFunction,...u(z)})}}class C1 extends o{get schema(){return this._def.getter()}_parse($){let{ctx:U}=this._processInputParams($);return this._def.getter()._parse({data:U.data,path:U.path,parent:U})}}C1.create=($,U)=>{return new C1({getter:$,typeName:F.ZodLazy,...u(U)})};class Z1 extends o{_parse($){if($.data!==this._def.value){let U=this._getOrReturnCtx($);return R(U,{received:U.data,code:_.invalid_literal,expected:this._def.value}),x}return{status:"valid",value:$.data}}get value(){return this._def.value}}Z1.create=($,U)=>{return new Z1({value:$,typeName:F.ZodLiteral,...u(U)})};function iO($,U){return new s6({values:$,typeName:F.ZodEnum,...u(U)})}class s6 extends o{_parse($){if(typeof $.data!=="string"){let U=this._getOrReturnCtx($),z=this._def.values;return R(U,{expected:s.joinValues(z),received:U.parsedType,code:_.invalid_type}),x}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let U=this._getOrReturnCtx($),z=this._def.values;return R(U,{received:U.data,code:_.invalid_enum_value,options:z}),x}return M$($.data)}get options(){return this._def.values}get enum(){let $={};for(let U of this._def.values)$[U]=U;return $}get Values(){let $={};for(let U of this._def.values)$[U]=U;return $}get Enum(){let $={};for(let U of this._def.values)$[U]=U;return $}extract($,U=this._def){return s6.create($,{...this._def,...U})}exclude($,U=this._def){return s6.create(this.options.filter((z)=>!$.includes(z)),{...this._def,...U})}}s6.create=iO;class T1 extends o{_parse($){let U=s.getValidEnumValues(this._def.values),z=this._getOrReturnCtx($);if(z.parsedType!==M.string&&z.parsedType!==M.number){let X=s.objectValues(U);return R(z,{expected:s.joinValues(X),received:z.parsedType,code:_.invalid_type}),x}if(!this._cache)this._cache=new Set(s.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let X=s.objectValues(U);return R(z,{received:z.data,code:_.invalid_enum_value,options:X}),x}return M$($.data)}get enum(){return this._def.values}}T1.create=($,U)=>{return new T1({values:$,typeName:F.ZodNativeEnum,...u(U)})};class R4 extends o{unwrap(){return this._def.type}_parse($){let{ctx:U}=this._processInputParams($);if(U.parsedType!==M.promise&&U.common.async===!1)return R(U,{code:_.invalid_type,expected:M.promise,received:U.parsedType}),x;let z=U.parsedType===M.promise?U.data:Promise.resolve(U.data);return M$(z.then((X)=>{return this._def.type.parseAsync(X,{path:U.path,errorMap:U.common.contextualErrorMap})}))}}R4.create=($,U)=>{return new R4({type:$,typeName:F.ZodPromise,...u(U)})};class X6 extends o{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:U,ctx:z}=this._processInputParams($),X=this._def.effect||null,J={addIssue:(j)=>{if(R(z,j),j.fatal)U.abort();else U.dirty()},get path(){return z.path}};if(J.addIssue=J.addIssue.bind(J),X.type==="preprocess"){let j=X.transform(z.data,J);if(z.common.async)return Promise.resolve(j).then(async(Y)=>{if(U.value==="aborted")return x;let N=await this._def.schema._parseAsync({data:Y,path:z.path,parent:z});if(N.status==="aborted")return x;if(N.status==="dirty")return P4(N.value);if(U.value==="dirty")return P4(N.value);return N});else{if(U.value==="aborted")return x;let Y=this._def.schema._parseSync({data:j,path:z.path,parent:z});if(Y.status==="aborted")return x;if(Y.status==="dirty")return P4(Y.value);if(U.value==="dirty")return P4(Y.value);return Y}}if(X.type==="refinement"){let j=(Y)=>{let N=X.refinement(Y,J);if(z.common.async)return Promise.resolve(N);if(N instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Y};if(z.common.async===!1){let Y=this._def.schema._parseSync({data:z.data,path:z.path,parent:z});if(Y.status==="aborted")return x;if(Y.status==="dirty")U.dirty();return j(Y.value),{status:U.value,value:Y.value}}else return this._def.schema._parseAsync({data:z.data,path:z.path,parent:z}).then((Y)=>{if(Y.status==="aborted")return x;if(Y.status==="dirty")U.dirty();return j(Y.value).then(()=>{return{status:U.value,value:Y.value}})})}if(X.type==="transform")if(z.common.async===!1){let j=this._def.schema._parseSync({data:z.data,path:z.path,parent:z});if(!t6(j))return x;let Y=X.transform(j.value,J);if(Y instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:U.value,value:Y}}else return this._def.schema._parseAsync({data:z.data,path:z.path,parent:z}).then((j)=>{if(!t6(j))return x;return Promise.resolve(X.transform(j.value,J)).then((Y)=>({status:U.value,value:Y}))});s.assertNever(X)}}X6.create=($,U,z)=>{return new X6({schema:$,typeName:F.ZodEffects,effect:U,...u(z)})};X6.createWithPreprocess=($,U,z)=>{return new X6({schema:U,effect:{type:"preprocess",transform:$},typeName:F.ZodEffects,...u(z)})};class z6 extends o{_parse($){if(this._getType($)===M.undefined)return M$(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}z6.create=($,U)=>{return new z6({innerType:$,typeName:F.ZodOptional,...u(U)})};class g6 extends o{_parse($){if(this._getType($)===M.null)return M$(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}g6.create=($,U)=>{return new g6({innerType:$,typeName:F.ZodNullable,...u(U)})};class g1 extends o{_parse($){let{ctx:U}=this._processInputParams($),z=U.data;if(U.parsedType===M.undefined)z=this._def.defaultValue();return this._def.innerType._parse({data:z,path:U.path,parent:U})}removeDefault(){return this._def.innerType}}g1.create=($,U)=>{return new g1({innerType:$,typeName:F.ZodDefault,defaultValue:typeof U.default==="function"?U.default:()=>U.default,...u(U)})};class x1 extends o{_parse($){let{ctx:U}=this._processInputParams($),z={...U,common:{...U.common,issues:[]}},X=this._def.innerType._parse({data:z.data,path:z.path,parent:{...z}});if(E1(X))return X.then((J)=>{return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new h$(z.common.issues)},input:z.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new h$(z.common.issues)},input:z.data})}}removeCatch(){return this._def.innerType}}x1.create=($,U)=>{return new x1({innerType:$,typeName:F.ZodCatch,catchValue:typeof U.catch==="function"?U.catch:()=>U.catch,...u(U)})};class B0 extends o{_parse($){if(this._getType($)!==M.nan){let z=this._getOrReturnCtx($);return R(z,{code:_.invalid_type,expected:M.nan,received:z.parsedType}),x}return{status:"valid",value:$.data}}}B0.create=($)=>{return new B0({typeName:F.ZodNaN,...u($)})};var XF=Symbol("zod_brand");class sY extends o{_parse($){let{ctx:U}=this._processInputParams($),z=U.data;return this._def.type._parse({data:z,path:U.path,parent:U})}unwrap(){return this._def.type}}class D0 extends o{_parse($){let{status:U,ctx:z}=this._processInputParams($);if(z.common.async)return(async()=>{let J=await this._def.in._parseAsync({data:z.data,path:z.path,parent:z});if(J.status==="aborted")return x;if(J.status==="dirty")return U.dirty(),P4(J.value);else return this._def.out._parseAsync({data:J.value,path:z.path,parent:z})})();else{let X=this._def.in._parseSync({data:z.data,path:z.path,parent:z});if(X.status==="aborted")return x;if(X.status==="dirty")return U.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:z.path,parent:z})}}static create($,U){return new D0({in:$,out:U,typeName:F.ZodPipeline})}}class f1 extends o{_parse($){let U=this._def.innerType._parse($),z=(X)=>{if(t6(X))X.value=Object.freeze(X.value);return X};return E1(U)?U.then((X)=>z(X)):z(U)}unwrap(){return this._def.innerType}}f1.create=($,U)=>{return new f1({innerType:$,typeName:F.ZodReadonly,...u(U)})};var jF={object:G$.lazycreate},F;(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"})(F||(F={}));var YF=_6.create,NF=E4.create,OF=B0.create,WF=M4.create,GF=G0.create,QF=b1.create,wF=Q0.create,HF=R1.create,VF=I1.create,LF=w0.create,BF=a6.create,DF=v6.create,KF=H0.create,qF=J6.create,_F=G$.create,vF=G$.strictCreate,FF=S1.create,PF=aY.create,AF=k1.create,EF=F6.create,MF=V0.create,bF=L0.create,RF=b4.create,IF=M1.create,SF=C1.create,kF=Z1.create,CF=s6.create,ZF=T1.create,TF=R4.create,gF=X6.create,xF=z6.create,fF=g6.create,hF=X6.createWithPreprocess,yF=D0.create;var FH=[{mediaType:"audio/mpeg",bytesPrefix:[255,251]},{mediaType:"audio/mpeg",bytesPrefix:[255,250]},{mediaType:"audio/mpeg",bytesPrefix:[255,243]},{mediaType:"audio/mpeg",bytesPrefix:[255,242]},{mediaType:"audio/mpeg",bytesPrefix:[255,227]},{mediaType:"audio/mpeg",bytesPrefix:[255,226]},{mediaType:"audio/wav",bytesPrefix:[82,73,70,70,null,null,null,null,87,65,86,69]},{mediaType:"audio/ogg",bytesPrefix:[79,103,103,83]},{mediaType:"audio/flac",bytesPrefix:[102,76,97,67]},{mediaType:"audio/aac",bytesPrefix:[64,21,0,0]},{mediaType:"audio/webm",bytesPrefix:[26,69,223,163]}],nF=[...FH,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var PH=12,AH=131072,rF=AH+PH;async function K0($){var U;try{await((U=$.body)==null?void 0:U.cancel())}catch(z){}}var tO="AI_DownloadError",aO=`vercel.ai.error.${tO}`,EH=Symbol.for(aO),lO,nO,k$=class extends(nO=$$,lO=EH,nO){constructor({url:$,statusCode:U,statusText:z,cause:X,message:J=X==null?`Failed to download ${$}: ${U} ${z}`:`Failed to download ${$}: ${X}`}){super({name:tO,message:J,cause:X});this[lO]=!0,this.url=$,this.statusCode=U,this.statusText=z}static isInstance($){return $$.hasMarker($,aO)}};function MH($=globalThis){return $.window!=null}function rO($,U){try{return new URL($).origin===new URL(U).origin}catch(z){return!1}}var bH=["connection","keep-alive","te","trailer","transfer-encoding","upgrade","host","forwarded","proxy-authorization","via","x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","metadata","metadata-flavor","x-aws-ec2-metadata-token","x-metadata-token","cookie","set-cookie"];function RH($){let U=new Headers($);for(let z of bH)U.delete(z);return U}function IH($){let U;try{U=new URL($)}catch(X){throw new k$({url:$,message:`Invalid URL: ${$}`})}if(U.protocol==="data:")return;if(U.protocol!=="http:"&&U.protocol!=="https:")throw new k$({url:$,message:`URL scheme must be http, https, or data, got ${U.protocol}`});let z=U.hostname.toLowerCase().replace(/\.+$/,"");if(!z)throw new k$({url:$,message:"URL must have a hostname"});if(z==="localhost"||z.endsWith(".local")||z.endsWith(".localhost"))throw new k$({url:$,message:`URL with hostname ${z} is not allowed`});if(z.startsWith("[")&&z.endsWith("]")){let X=z.slice(1,-1);if(kH(X))throw new k$({url:$,message:`URL with IPv6 address ${z} is not allowed`});return}if(sO(z)){if(eO(z))throw new k$({url:$,message:`URL with IP address ${z} is not allowed`});return}}function sO($){let U=$.split(".");if(U.length!==4)return!1;return U.every((z)=>{let X=Number(z);return Number.isInteger(X)&&X>=0&&X<=255&&String(X)===z})}function eO($){let U=$.split(".").map(Number),[z,X,J]=U;if(z===0)return!0;if(z===10)return!0;if(z===100&&X>=64&&X<=127)return!0;if(z===127)return!0;if(z===169&&X===254)return!0;if(z===172&&X>=16&&X<=31)return!0;if(z===192&&X===0&&J===0)return!0;if(z===192&&X===0&&J===2)return!0;if(z===192&&X===168)return!0;if(z===198&&(X===18||X===19))return!0;if(z===198&&X===51&&J===100)return!0;if(z===203&&X===0&&J===113)return!0;if(z>=224)return!0;return!1}function SH($){let U=$.toLowerCase(),z=U.indexOf("%");if(z!==-1)U=U.slice(0,z);let X=U.split("::");if(X.length>2)return null;let J=(Y)=>{if(Y==="")return[];let N=[],W=Y.split(":");for(let G=0;G<W.length;G++){let Q=W[G];if(Q.includes(".")){if(G!==W.length-1||!sO(Q))return null;let[L,H,w,B]=Q.split(".").map(Number);N.push(L<<8|H,w<<8|B);continue}if(!/^[0-9a-f]{1,4}$/.test(Q))return null;N.push(parseInt(Q,16))}return N},j=J(X[0]);if(j===null)return null;if(X.length===2){let Y=J(X[1]);if(Y===null)return null;let N=8-j.length-Y.length;if(N<0)return null;return[...j,...Array(N).fill(0),...Y]}return j.length===8?j:null}function kH($){let U=SH($);if(U===null)return!0;let z=(J)=>U.slice(0,J).every((j)=>j===0);if(z(7)&&(U[7]===0||U[7]===1))return!0;if((U[0]&65024)===64512)return!0;if((U[0]&65472)===65152)return!0;if((U[0]&65472)===65216)return!0;if((U[0]&65280)===65280)return!0;if(U[0]===8193&&U[1]===3512)return!0;if(U[0]===16383&&(U[1]&61440)===0)return!0;if(z(6)||z(5)&&U[5]===65535||z(4)&&U[4]===65535&&U[5]===0||U[0]===100&&U[1]===65435&&U[2]===0&&U[3]===0&&U[4]===0&&U[5]===0||U[0]===100&&U[1]===65435&&U[2]===1){let J=U[6]>>8&255,j=U[6]&255,Y=U[7]>>8&255,N=U[7]&255;return eO(`${J}.${j}.${Y}.${N}`)}return!1}var CH=10,ZH=new Set([301,302,303,307,308]);async function $W({url:$,headers:U,abortSignal:z,maxRedirects:X=CH,fetch:J=globalThis.fetch,trustedOrigin:j}){let Y=U===void 0?void 0:RH(U),N=(G)=>{let Q={signal:z,redirect:G};if(Y!==void 0)Q.headers=new Headers(Y);return Q},W=$;for(let G=0;G<=X;G++){if(j===void 0||!rO(W,j))IH(W);let Q=await J(W,N("manual"));if(Q.type==="opaqueredirect"){if(!MH())throw new k$({url:$,message:`Redirect from ${W} could not be validated and was blocked`});return await J(W,N("follow"))}let L=Q.headers.get("location");if(ZH.has(Q.status)&&L){await K0(Q);let H=new URL(L,W).toString();if(Y!==void 0&&!rO(H,W)){let w=Y.get("user-agent");Y=new Headers(w==null?void 0:{"user-agent":w})}W=H;continue}return Q}throw new k$({url:$,message:`Too many redirects (max ${X})`})}var zN=2147483648;async function UW({response:$,url:U,maxBytes:z=zN}){let X=$.headers.get("content-length");if(X!=null){let Q=parseInt(X,10);if(!isNaN(Q)&&Q>z)throw await K0($),new k$({url:U,message:`Download of ${U} exceeded maximum size of ${z} bytes (Content-Length: ${Q}).`})}let J=$.body;if(J==null)return new Uint8Array(0);let j=J.getReader(),Y=[],N=0;try{while(!0){let{done:Q,value:L}=await j.read();if(Q)break;if(N+=L.length,N>z)throw new k$({url:U,message:`Download of ${U} exceeded maximum size of ${z} bytes.`});Y.push(L)}}finally{try{await j.cancel()}finally{j.releaseLock()}}let W=new Uint8Array(N),G=0;for(let Q of Y)W.set(Q,G),G+=Q.length;return W}var V$=({prefix:$,size:U=16,alphabet:z="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:X="-"}={})=>{let J=()=>{let j=z.length,Y=Array(U);for(let N=0;N<U;N++)Y[N]=z[Math.random()*j|0];return Y.join("")};if($==null)return J;if(z.includes(X))throw new o8({argument:"separator",message:`The separator "${X}" must not be part of the alphabet "${z}".`});return()=>`${$}${X}${J()}`},oF=V$();function JW($=globalThis){var U,z,X;if($.window)return"runtime/browser";if((U=$.navigator)==null?void 0:U.userAgent)return`runtime/${$.navigator.userAgent.toLowerCase()}`;if((X=(z=$.process)==null?void 0:z.versions)==null?void 0:X.node)return`runtime/node.js/${$.process.version.substring(0)}`;if($.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function TH($){if($==null)return{};let U={};if($ instanceof Headers)$.forEach((z,X)=>{U[X.toLowerCase()]=z});else{if(!Array.isArray($))$=Object.entries($);for(let[z,X]of $)if(X!=null)U[z.toLowerCase()]=X}return U}function I4($,...U){let z=new Headers(TH($)),X=z.get("user-agent")||"";return z.set("user-agent",[X,...U].filter(Boolean).join(" ")),Object.fromEntries(z.entries())}function zW($){var U,z;return(z=(U=globalThis.Buffer)==null?void 0:U.isBuffer($))!=null?z:!1}var gH=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,xH=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function pO($){let U=JSON.parse($);if(U===null||typeof U!=="object")return U;if(gH.test($)===!1&&xH.test($)===!1)return U;return fH(U)}function fH($){let U=[$];while(U.length){let z=U;U=[];for(let X of z){if(Object.prototype.hasOwnProperty.call(X,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(X,"constructor")&&X.constructor!==null&&typeof X.constructor==="object"&&Object.prototype.hasOwnProperty.call(X.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let J in X){let j=X[J];if(j&&typeof j==="object")U.push(j)}}}return $}function hH($){let{stackTraceLimit:U}=Error;try{Error.stackTraceLimit=0}catch(z){return pO($)}try{return pO($)}finally{Error.stackTraceLimit=U}}function XN($){if($.type==="object"||Array.isArray($.type)&&$.type.includes("object")){$.additionalProperties=!1;let{properties:z}=$;if(z!=null)for(let X of Object.keys(z))z[X]=e6(z[X])}if($.items!=null)$.items=Array.isArray($.items)?$.items.map(e6):e6($.items);if($.anyOf!=null)$.anyOf=$.anyOf.map(e6);if($.allOf!=null)$.allOf=$.allOf.map(e6);if($.oneOf!=null)$.oneOf=$.oneOf.map(e6);let{definitions:U}=$;if(U!=null)for(let z of Object.keys(U))U[z]=e6(U[z]);return $}function e6($){if(typeof $==="boolean")return $;return XN($)}var yH=Symbol("Let zodToJsonSchema decide on which parser to use"),dO={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},cH=($)=>typeof $==="string"?{...dO,name:$}:{...dO,...$};function y$(){return{}}function mH($,U){var z,X,J;let j={type:"array"};if(((z=$.type)==null?void 0:z._def)&&((J=(X=$.type)==null?void 0:X._def)==null?void 0:J.typeName)!==F.ZodAny)j.items=U$($.type._def,{...U,currentPath:[...U.currentPath,"items"]});if($.minLength)j.minItems=$.minLength.value;if($.maxLength)j.maxItems=$.maxLength.value;if($.exactLength)j.minItems=$.exactLength.value,j.maxItems=$.exactLength.value;return j}function uH($){let U={type:"integer",format:"int64"};if(!$.checks)return U;for(let z of $.checks)switch(z.kind){case"min":if(z.inclusive)U.minimum=z.value;else U.exclusiveMinimum=z.value;break;case"max":if(z.inclusive)U.maximum=z.value;else U.exclusiveMaximum=z.value;break;case"multipleOf":U.multipleOf=z.value;break}return U}function iH(){return{type:"boolean"}}function XW($,U){return U$($.type._def,U)}var lH=($,U)=>{return U$($.innerType._def,U)};function jW($,U,z){let X=z!=null?z:U.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((J)=>jW($,U,J))};switch(X){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return nH($)}}var nH=($)=>{let U={type:"integer",format:"unix-time"};for(let z of $.checks)switch(z.kind){case"min":U.minimum=z.value;break;case"max":U.maximum=z.value;break}return U};function rH($,U){return{...U$($.innerType._def,U),default:$.defaultValue()}}function pH($,U){return U.effectStrategy==="input"?U$($.schema._def,U):y$()}function dH($){return{type:"string",enum:Array.from($.values)}}var oH=($)=>{if("type"in $&&$.type==="string")return!1;return"allOf"in $};function tH($,U){let z=[U$($.left._def,{...U,currentPath:[...U.currentPath,"allOf","0"]}),U$($.right._def,{...U,currentPath:[...U.currentPath,"allOf","1"]})].filter((J)=>!!J),X=[];return z.forEach((J)=>{if(oH(J))X.push(...J.allOf);else{let j=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:Y,...N}=J;j=N}X.push(j)}}),X.length?{allOf:X}:void 0}function aH($){let U=typeof $.value;if(U!=="bigint"&&U!=="number"&&U!=="boolean"&&U!=="string")return{type:Array.isArray($.value)?"array":"object"};return{type:U==="bigint"?"integer":U,const:$.value}}var eY=void 0,o$={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(eY===void 0)eY=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return eY},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function YW($,U){let z={type:"string"};if($.checks)for(let X of $.checks)switch(X.kind){case"min":z.minLength=typeof z.minLength==="number"?Math.max(z.minLength,X.value):X.value;break;case"max":z.maxLength=typeof z.maxLength==="number"?Math.min(z.maxLength,X.value):X.value;break;case"email":switch(U.emailStrategy){case"format:email":t$(z,"email",X.message,U);break;case"format:idn-email":t$(z,"idn-email",X.message,U);break;case"pattern:zod":b$(z,o$.email,X.message,U);break}break;case"url":t$(z,"uri",X.message,U);break;case"uuid":t$(z,"uuid",X.message,U);break;case"regex":b$(z,X.regex,X.message,U);break;case"cuid":b$(z,o$.cuid,X.message,U);break;case"cuid2":b$(z,o$.cuid2,X.message,U);break;case"startsWith":b$(z,RegExp(`^${$N(X.value,U)}`),X.message,U);break;case"endsWith":b$(z,RegExp(`${$N(X.value,U)}$`),X.message,U);break;case"datetime":t$(z,"date-time",X.message,U);break;case"date":t$(z,"date",X.message,U);break;case"time":t$(z,"time",X.message,U);break;case"duration":t$(z,"duration",X.message,U);break;case"length":z.minLength=typeof z.minLength==="number"?Math.max(z.minLength,X.value):X.value,z.maxLength=typeof z.maxLength==="number"?Math.min(z.maxLength,X.value):X.value;break;case"includes":{b$(z,RegExp($N(X.value,U)),X.message,U);break}case"ip":{if(X.version!=="v6")t$(z,"ipv4",X.message,U);if(X.version!=="v4")t$(z,"ipv6",X.message,U);break}case"base64url":b$(z,o$.base64url,X.message,U);break;case"jwt":b$(z,o$.jwt,X.message,U);break;case"cidr":{if(X.version!=="v6")b$(z,o$.ipv4Cidr,X.message,U);if(X.version!=="v4")b$(z,o$.ipv6Cidr,X.message,U);break}case"emoji":b$(z,o$.emoji(),X.message,U);break;case"ulid":{b$(z,o$.ulid,X.message,U);break}case"base64":{switch(U.base64Strategy){case"format:binary":{t$(z,"binary",X.message,U);break}case"contentEncoding:base64":{z.contentEncoding="base64";break}case"pattern:zod":{b$(z,o$.base64,X.message,U);break}}break}case"nanoid":b$(z,o$.nanoid,X.message,U);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return z}function $N($,U){return U.patternStrategy==="escape"?eH($):$}var sH=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function eH($){let U="";for(let z=0;z<$.length;z++){if(!sH.has($[z]))U+="\\";U+=$[z]}return U}function t$($,U,z,X){var J;if($.format||((J=$.anyOf)==null?void 0:J.some((j)=>j.format))){if(!$.anyOf)$.anyOf=[];if($.format)$.anyOf.push({format:$.format}),delete $.format;$.anyOf.push({format:U,...z&&X.errorMessages&&{errorMessage:{format:z}}})}else $.format=U}function b$($,U,z,X){var J;if($.pattern||((J=$.allOf)==null?void 0:J.some((j)=>j.pattern))){if(!$.allOf)$.allOf=[];if($.pattern)$.allOf.push({pattern:$.pattern}),delete $.pattern;$.allOf.push({pattern:oO(U,X),...z&&X.errorMessages&&{errorMessage:{pattern:z}}})}else $.pattern=oO(U,X)}function oO($,U){var z;if(!U.applyRegexFlags||!$.flags)return $.source;let X={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},J=X.i?$.source.toLowerCase():$.source,j="",Y=!1,N=!1,W=!1;for(let G=0;G<J.length;G++){if(Y){j+=J[G],Y=!1;continue}if(X.i){if(N){if(J[G].match(/[a-z]/)){if(W)j+=J[G],j+=`${J[G-2]}-${J[G]}`.toUpperCase(),W=!1;else if(J[G+1]==="-"&&((z=J[G+2])==null?void 0:z.match(/[a-z]/)))j+=J[G],W=!0;else j+=`${J[G]}${J[G].toUpperCase()}`;continue}}else if(J[G].match(/[a-z]/)){j+=`[${J[G]}${J[G].toUpperCase()}]`;continue}}if(X.m){if(J[G]==="^"){j+=`(^|(?<=[\r
125
- ]))`;continue}else if(J[G]==="$"){j+=`($|(?=[\r
126
- ]))`;continue}}if(X.s&&J[G]==="."){j+=N?`${J[G]}\r
127
- `:`[${J[G]}\r
128
- ]`;continue}if(j+=J[G],J[G]==="\\")Y=!0;else if(N&&J[G]==="]")N=!1;else if(!N&&J[G]==="[")N=!0}try{new RegExp(j)}catch(G){return console.warn(`Could not convert regex pattern at ${U.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return j}function NW($,U){var z,X,J,j,Y,N;let W={type:"object",additionalProperties:(z=U$($.valueType._def,{...U,currentPath:[...U.currentPath,"additionalProperties"]}))!=null?z:U.allowedAdditionalProperties};if(((X=$.keyType)==null?void 0:X._def.typeName)===F.ZodString&&((J=$.keyType._def.checks)==null?void 0:J.length)){let{type:G,...Q}=YW($.keyType._def,U);return{...W,propertyNames:Q}}else if(((j=$.keyType)==null?void 0:j._def.typeName)===F.ZodEnum)return{...W,propertyNames:{enum:$.keyType._def.values}};else if(((Y=$.keyType)==null?void 0:Y._def.typeName)===F.ZodBranded&&$.keyType._def.type._def.typeName===F.ZodString&&((N=$.keyType._def.type._def.checks)==null?void 0:N.length)){let{type:G,...Q}=XW($.keyType._def,U);return{...W,propertyNames:Q}}return W}function $V($,U){if(U.mapStrategy==="record")return NW($,U);let z=U$($.keyType._def,{...U,currentPath:[...U.currentPath,"items","items","0"]})||y$(),X=U$($.valueType._def,{...U,currentPath:[...U.currentPath,"items","items","1"]})||y$();return{type:"array",maxItems:125,items:{type:"array",items:[z,X],minItems:2,maxItems:2}}}function UV($){let U=$.values,X=Object.keys($.values).filter((j)=>{return typeof U[U[j]]!=="number"}).map((j)=>U[j]),J=Array.from(new Set(X.map((j)=>typeof j)));return{type:J.length===1?J[0]==="string"?"string":"number":["string","number"],enum:X}}function JV(){return{not:y$()}}function zV(){return{type:"null"}}var UN={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function XV($,U){let z=$.options instanceof Map?Array.from($.options.values()):$.options;if(z.every((X)=>(X._def.typeName in UN)&&(!X._def.checks||!X._def.checks.length))){let X=z.reduce((J,j)=>{let Y=UN[j._def.typeName];return Y&&!J.includes(Y)?[...J,Y]:J},[]);return{type:X.length>1?X:X[0]}}else if(z.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=z.reduce((J,j)=>{let Y=typeof j._def.value;switch(Y){case"string":case"number":case"boolean":return[...J,Y];case"bigint":return[...J,"integer"];case"object":if(j._def.value===null)return[...J,"null"];case"symbol":case"undefined":case"function":default:return J}},[]);if(X.length===z.length){let J=X.filter((j,Y,N)=>N.indexOf(j)===Y);return{type:J.length>1?J:J[0],enum:z.reduce((j,Y)=>{return j.includes(Y._def.value)?j:[...j,Y._def.value]},[])}}}else if(z.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:z.reduce((X,J)=>[...X,...J._def.values.filter((j)=>!X.includes(j))],[])};return jV($,U)}var jV=($,U)=>{let z=($.options instanceof Map?Array.from($.options.values()):$.options).map((X,J)=>U$(X._def,{...U,currentPath:[...U.currentPath,"anyOf",`${J}`]})).filter((X)=>!!X&&(!U.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return z.length?{anyOf:z}:void 0};function YV($,U){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length))return{type:[UN[$.innerType._def.typeName],"null"]};let z=U$($.innerType._def,{...U,currentPath:[...U.currentPath,"anyOf","0"]});return z&&{anyOf:[z,{type:"null"}]}}function NV($){let U={type:"number"};if(!$.checks)return U;for(let z of $.checks)switch(z.kind){case"int":U.type="integer";break;case"min":if(z.inclusive)U.minimum=z.value;else U.exclusiveMinimum=z.value;break;case"max":if(z.inclusive)U.maximum=z.value;else U.exclusiveMaximum=z.value;break;case"multipleOf":U.multipleOf=z.value;break}return U}function OV($,U){let z={type:"object",properties:{}},X=[],J=$.shape();for(let Y in J){let N=J[Y];if(N===void 0||N._def===void 0)continue;let W=GV(N),G=U$(N._def,{...U,currentPath:[...U.currentPath,"properties",Y],propertyPath:[...U.currentPath,"properties",Y]});if(G===void 0)continue;if(z.properties[Y]=G,!W)X.push(Y)}if(X.length)z.required=X;let j=WV($,U);if(j!==void 0)z.additionalProperties=j;return z}function WV($,U){if($.catchall._def.typeName!=="ZodNever")return U$($.catchall._def,{...U,currentPath:[...U.currentPath,"additionalProperties"]});switch($.unknownKeys){case"passthrough":return U.allowedAdditionalProperties;case"strict":return U.rejectedAdditionalProperties;case"strip":return U.removeAdditionalStrategy==="strict"?U.allowedAdditionalProperties:U.rejectedAdditionalProperties}}function GV($){try{return $.isOptional()}catch(U){return!0}}var QV=($,U)=>{var z;if(U.currentPath.toString()===((z=U.propertyPath)==null?void 0:z.toString()))return U$($.innerType._def,U);let X=U$($.innerType._def,{...U,currentPath:[...U.currentPath,"anyOf","1"]});return X?{anyOf:[{not:y$()},X]}:y$()},wV=($,U)=>{if(U.pipeStrategy==="input")return U$($.in._def,U);else if(U.pipeStrategy==="output")return U$($.out._def,U);let z=U$($.in._def,{...U,currentPath:[...U.currentPath,"allOf","0"]}),X=U$($.out._def,{...U,currentPath:[...U.currentPath,"allOf",z?"1":"0"]});return{allOf:[z,X].filter((J)=>J!==void 0)}};function HV($,U){return U$($.type._def,U)}function VV($,U){let X={type:"array",uniqueItems:!0,items:U$($.valueType._def,{...U,currentPath:[...U.currentPath,"items"]})};if($.minSize)X.minItems=$.minSize.value;if($.maxSize)X.maxItems=$.maxSize.value;return X}function LV($,U){if($.rest)return{type:"array",minItems:$.items.length,items:$.items.map((z,X)=>U$(z._def,{...U,currentPath:[...U.currentPath,"items",`${X}`]})).reduce((z,X)=>X===void 0?z:[...z,X],[]),additionalItems:U$($.rest._def,{...U,currentPath:[...U.currentPath,"additionalItems"]})};else return{type:"array",minItems:$.items.length,maxItems:$.items.length,items:$.items.map((z,X)=>U$(z._def,{...U,currentPath:[...U.currentPath,"items",`${X}`]})).reduce((z,X)=>X===void 0?z:[...z,X],[])}}function BV(){return{not:y$()}}function DV(){return y$()}var KV=($,U)=>{return U$($.innerType._def,U)},qV=($,U,z)=>{switch(U){case F.ZodString:return YW($,z);case F.ZodNumber:return NV($);case F.ZodObject:return OV($,z);case F.ZodBigInt:return uH($);case F.ZodBoolean:return iH();case F.ZodDate:return jW($,z);case F.ZodUndefined:return BV();case F.ZodNull:return zV();case F.ZodArray:return mH($,z);case F.ZodUnion:case F.ZodDiscriminatedUnion:return XV($,z);case F.ZodIntersection:return tH($,z);case F.ZodTuple:return LV($,z);case F.ZodRecord:return NW($,z);case F.ZodLiteral:return aH($);case F.ZodEnum:return dH($);case F.ZodNativeEnum:return UV($);case F.ZodNullable:return YV($,z);case F.ZodOptional:return QV($,z);case F.ZodMap:return $V($,z);case F.ZodSet:return VV($,z);case F.ZodLazy:return()=>$.getter()._def;case F.ZodPromise:return HV($,z);case F.ZodNaN:case F.ZodNever:return JV();case F.ZodEffects:return pH($,z);case F.ZodAny:return y$();case F.ZodUnknown:return DV();case F.ZodDefault:return rH($,z);case F.ZodBranded:return XW($,z);case F.ZodReadonly:return KV($,z);case F.ZodCatch:return lH($,z);case F.ZodPipeline:return wV($,z);case F.ZodFunction:case F.ZodVoid:case F.ZodSymbol:return;default:return((X)=>{return})(U)}},_V=($,U)=>{let z=0;for(;z<$.length&&z<U.length;z++)if($[z]!==U[z])break;return[($.length-z).toString(),...U.slice(z)].join("/")};function U$($,U,z=!1){var X;let J=U.seen.get($);if(U.override){let W=(X=U.override)==null?void 0:X.call(U,$,U,J,z);if(W!==yH)return W}if(J&&!z){let W=vV(J,U);if(W!==void 0)return W}let j={def:$,path:U.currentPath,jsonSchema:void 0};U.seen.set($,j);let Y=qV($,$.typeName,U),N=typeof Y==="function"?U$(Y(),U):Y;if(N)FV($,U,N);if(U.postProcess){let W=U.postProcess(N,$,U);return j.jsonSchema=N,W}return j.jsonSchema=N,N}var vV=($,U)=>{switch(U.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:_V(U.currentPath,$.path)};case"none":case"seen":{if($.path.length<U.currentPath.length&&$.path.every((z,X)=>U.currentPath[X]===z))return console.warn(`Recursive reference detected at ${U.currentPath.join("/")}! Defaulting to any`),y$();return U.$refStrategy==="seen"?y$():void 0}}},FV=($,U,z)=>{if($.description)z.description=$.description;return z},PV=($)=>{let U=cH($),z=U.name!==void 0?[...U.basePath,U.definitionPath,U.name]:U.basePath;return{...U,currentPath:z,propertyPath:void 0,seen:new Map(Object.entries(U.definitions).map(([X,J])=>[J._def,{def:J._def,path:[...U.basePath,U.definitionPath,X],jsonSchema:void 0}]))}},AV=($,U)=>{var z;let X=PV(U),J=typeof U==="object"&&U.definitions?Object.entries(U.definitions).reduce((G,[Q,L])=>{var H;return{...G,[Q]:(H=U$(L._def,{...X,currentPath:[...X.basePath,X.definitionPath,Q]},!0))!=null?H:y$()}},{}):void 0,j=typeof U==="string"?U:(U==null?void 0:U.nameStrategy)==="title"?void 0:U==null?void 0:U.name,Y=(z=U$($._def,j===void 0?X:{...X,currentPath:[...X.basePath,X.definitionPath,j]},!1))!=null?z:y$(),N=typeof U==="object"&&U.name!==void 0&&U.nameStrategy==="title"?U.name:void 0;if(N!==void 0)Y.title=N;let W=j===void 0?J?{...Y,[X.definitionPath]:J}:Y:{$ref:[...X.$refStrategy==="relative"?[]:X.basePath,X.definitionPath,j].join("/"),[X.definitionPath]:{...J,[j]:Y}};return W.$schema="http://json-schema.org/draft-07/schema#",W},JN=Symbol.for("vercel.ai.schema");function q0($){let U;return()=>{if(U==null)U=$();return U}}function _0($,{validate:U}={}){return{[JN]:!0,_type:void 0,get jsonSchema(){if(typeof $==="function")$=$();return $},validate:U}}function EV($){return typeof $==="object"&&$!==null&&JN in $&&$[JN]===!0&&"jsonSchema"in $&&"validate"in $}function v0($){return $==null?_0({type:"object",properties:{},additionalProperties:!1}):EV($)?$:("~standard"in $)?$["~standard"].vendor==="zod"?h1($):MV($):$()}function MV($){return _0(()=>{if(!bV($))throw Error(`Standard schema vendor '${$["~standard"].vendor}' does not support JSON Schema conversion.`);return XN($["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async(U)=>{let z=await $["~standard"].validate(U);return"value"in z?{success:!0,value:z.value}:{success:!1,error:new s$({value:U,cause:z.issues})}}})}function bV($){return $["~standard"].jsonSchema!=null}function RV($,U){var z;let X=(z=U==null?void 0:U.useReferences)!=null?z:!1;return _0(()=>AV($,{$refStrategy:X?"root":"none"}),{validate:async(J)=>{let j=await $.safeParseAsync(J);return j.success?{success:!0,value:j.data}:{success:!1,error:j.error}}})}function IV($,U){var z;let X=(z=U==null?void 0:U.useReferences)!=null?z:!1;return _0(()=>XN(B1($,{target:"draft-7",io:"input",reused:X?"ref":"inline"})),{validate:async(J)=>{let j=await D1($,J);return j.success?{success:!0,value:j.data}:{success:!1,error:j.error}}})}function SV($){return"_zod"in $}function h1($,U){if(SV($))return IV($,U);else return RV($,U)}async function y1({value:$,schema:U,context:z}){let X=v0(U);try{if(X.validate==null)return{success:!0,value:$,rawValue:$};let J=await X.validate($);if(J.success)return{success:!0,value:J.value,rawValue:$};return{success:!1,error:s$.wrap({value:$,cause:J.error,context:z}),rawValue:$}}catch(J){return{success:!1,error:s$.wrap({value:$,cause:J,context:z}),rawValue:$}}}async function x6({text:$,schema:U}){try{let z=hH($);if(U==null)return{success:!0,value:z,rawValue:z};return await y1({value:z,schema:U})}catch(z){return{success:!1,error:UU.isInstance(z)?z:new UU({text:$,cause:z}),rawValue:void 0}}}async function jN($){if(typeof $==="function")$=$();return Promise.resolve($)}var ZV=Object.defineProperty,TV=($,U)=>{for(var z in U)ZV($,z,{get:U[z],enumerable:!0})},gV="AI_InvalidArgumentError",xV=`vercel.ai.error.${gV}`,fV=Symbol.for(xV),hV;hV=fV;var yV="AI_InvalidStreamPartError",cV=`vercel.ai.error.${yV}`,mV=Symbol.for(cV),uV;uV=mV;var iV="AI_InvalidToolApprovalError",lV=`vercel.ai.error.${iV}`,nV=Symbol.for(lV),rV;rV=nV;var pV="AI_InvalidToolApprovalSignatureError",dV=`vercel.ai.error.${pV}`,oV=Symbol.for(dV),tV;tV=oV;var aV="AI_InvalidToolInputError",sV=`vercel.ai.error.${aV}`,eV=Symbol.for(sV),$L;$L=eV;var UL="AI_ToolCallNotFoundForApprovalError",JL=`vercel.ai.error.${UL}`,zL=Symbol.for(JL),XL;XL=zL;var jL="AI_MissingToolResultsError",YL=`vercel.ai.error.${jL}`,NL=Symbol.for(YL),OL;OL=NL;var WL="AI_NoImageGeneratedError",GL=`vercel.ai.error.${WL}`,QL=Symbol.for(GL),wL;wL=QL;var OW="AI_NoObjectGeneratedError",WW=`vercel.ai.error.${OW}`,HL=Symbol.for(WW),GW,f6=class extends $${constructor({message:$="No object generated.",cause:U,text:z,response:X,usage:J,finishReason:j}){super({name:OW,message:$,cause:U});this[GW]=!0,this.text=z,this.response=X,this.usage=J,this.finishReason=j}static isInstance($){return $$.hasMarker($,WW)}};GW=HL;var VL="AI_NoOutputGeneratedError",LL=`vercel.ai.error.${VL}`,BL=Symbol.for(LL),DL;DL=BL;var KL="AI_NoSpeechGeneratedError",qL=`vercel.ai.error.${KL}`,_L=Symbol.for(qL),vL;vL=_L;var FL="AI_NoTranscriptGeneratedError",PL=`vercel.ai.error.${FL}`,AL=Symbol.for(PL),EL;EL=AL;var ML="AI_NoVideoGeneratedError",bL=`vercel.ai.error.${ML}`,RL=Symbol.for(bL),IL;IL=RL;var SL="AI_NoSuchToolError",kL=`vercel.ai.error.${SL}`,CL=Symbol.for(kL),ZL;ZL=CL;var TL="AI_ToolCallRepairError",gL=`vercel.ai.error.${TL}`,xL=Symbol.for(gL),fL;fL=xL;var hL="AI_UIMessageStreamError",yL=`vercel.ai.error.${hL}`,cL=Symbol.for(yL),mL;mL=cL;var uL="AI_InvalidDataContentError",iL=`vercel.ai.error.${uL}`,lL=Symbol.for(iL),nL;nL=lL;var rL="AI_InvalidMessageRoleError",pL=`vercel.ai.error.${rL}`,dL=Symbol.for(pL),oL;oL=dL;var tL="AI_MessageConversionError",aL=`vercel.ai.error.${tL}`,sL=Symbol.for(aL),eL;eL=sL;var $B="AI_RetryError",UB=`vercel.ai.error.${$B}`,JB=Symbol.for(UB),zB;zB=JB;var XB="7.0.34",jB=async({url:$,maxBytes:U,abortSignal:z})=>{var X;let J=$.toString();try{let j=I4({},`ai-sdk/${XB}`,JW()),Y=await $W({url:J,headers:j,abortSignal:z});if(!Y.ok)throw await K0(Y),new k$({url:J,statusCode:Y.status,statusText:Y.statusText});return{data:await UW({response:Y,url:J,maxBytes:U!=null?U:zN}),mediaType:(X=Y.headers.get("content-type"))!=null?X:void 0}}catch(j){if(k$.isInstance(j))throw j;throw new k$({url:J,cause:j})}};var $4=O.lazy(()=>O.union([O.null(),O.string(),O.number(),O.boolean(),O.record(O.string(),$4.optional()),O.array($4)])),I=O.record(O.string(),O.record(O.string(),$4.optional())),m1=O.union([O.string(),O.instanceof(Uint8Array),O.instanceof(ArrayBuffer),O.custom(zW,{message:"Must be a Buffer"})]),YN=O.record(O.string(),O.string()),QW=O.object({type:O.literal("text"),text:O.string(),providerOptions:I.optional()}),YB=O.object({type:O.literal("image"),image:O.union([m1,O.instanceof(URL),YN]),mediaType:O.string().optional(),providerOptions:I.optional()}),wW=O.discriminatedUnion("type",[O.object({type:O.literal("data"),data:m1}),O.object({type:O.literal("url"),url:O.instanceof(URL)}),O.object({type:O.literal("reference"),reference:YN}),O.object({type:O.literal("text"),text:O.string()})]),NB=O.discriminatedUnion("type",[O.object({type:O.literal("data"),data:m1}),O.object({type:O.literal("url"),url:O.instanceof(URL)})]),HW=O.object({type:O.literal("file"),data:O.union([wW,m1,O.instanceof(URL),YN]),filename:O.string().optional(),mediaType:O.string(),providerOptions:I.optional()}),OB=O.object({type:O.literal("reasoning"),text:O.string(),providerOptions:I.optional()}),WB=O.object({type:O.literal("custom"),kind:O.string().transform(($)=>$),providerOptions:I.optional()}),GB=O.object({type:O.literal("reasoning-file"),data:O.union([NB,m1,O.instanceof(URL)]),mediaType:O.string(),providerOptions:I.optional()}),QB=O.object({type:O.literal("tool-call"),toolCallId:O.string(),toolName:O.string(),input:O.unknown(),providerOptions:I.optional(),providerExecuted:O.boolean().optional()}),wB=O.discriminatedUnion("type",[O.object({type:O.literal("text"),value:O.string(),providerOptions:I.optional()}),O.object({type:O.literal("json"),value:$4,providerOptions:I.optional()}),O.object({type:O.literal("execution-denied"),reason:O.string().optional(),providerOptions:I.optional()}),O.object({type:O.literal("error-text"),value:O.string(),providerOptions:I.optional()}),O.object({type:O.literal("error-json"),value:$4,providerOptions:I.optional()}),O.object({type:O.literal("content"),value:O.array(O.union([O.object({type:O.literal("text"),text:O.string(),providerOptions:I.optional()}),O.object({type:O.literal("file"),data:wW,mediaType:O.string(),filename:O.string().optional(),providerOptions:I.optional()}),O.object({type:O.literal("file-data"),data:O.string(),mediaType:O.string(),filename:O.string().optional(),providerOptions:I.optional()}),O.object({type:O.literal("file-url"),url:O.string(),mediaType:O.string().optional(),providerOptions:I.optional()}),O.object({type:O.literal("file-id"),fileId:O.union([O.string(),O.record(O.string(),O.string())]),providerOptions:I.optional()}),O.object({type:O.literal("file-reference"),providerReference:O.record(O.string(),O.string()),providerOptions:I.optional()}),O.object({type:O.literal("image-data"),data:O.string(),mediaType:O.string(),providerOptions:I.optional()}),O.object({type:O.literal("image-url"),url:O.string(),providerOptions:I.optional()}),O.object({type:O.literal("image-file-id"),fileId:O.union([O.string(),O.record(O.string(),O.string())]),providerOptions:I.optional()}),O.object({type:O.literal("image-file-reference"),providerReference:O.record(O.string(),O.string()),providerOptions:I.optional()}),O.object({type:O.literal("custom"),providerOptions:I.optional()})]))})]),VW=O.object({type:O.literal("tool-result"),toolCallId:O.string(),toolName:O.string(),output:wB,providerOptions:I.optional()}),HB=O.object({type:O.literal("tool-approval-request"),approvalId:O.string(),toolCallId:O.string()}),VB=O.object({type:O.literal("tool-approval-response"),approvalId:O.string(),approved:O.boolean(),reason:O.string().optional()}),LB=O.object({role:O.literal("system"),content:O.string(),providerOptions:I.optional()}),BB=O.object({role:O.literal("user"),content:O.union([O.string(),O.array(O.union([QW,YB,HW]))]),providerOptions:I.optional()}),DB=O.object({role:O.literal("assistant"),content:O.union([O.string(),O.array(O.union([QW,WB,HW,OB,GB,QB,VW,HB]))]),providerOptions:I.optional()}),KB=O.object({role:O.literal("tool"),content:O.array(O.union([VW,VB])),providerOptions:I.optional()}),DP=O.union([LB,BB,DB,KB]);var qB={};TV(qB,{array:()=>PB,choice:()=>AB,json:()=>EB,object:()=>FB,text:()=>vB});function _B($){let U=["ROOT"],z=-1,X=null,J=0;function j(Q){return Q>="0"&&Q<="9"||Q>="A"&&Q<="F"||Q>="a"&&Q<="f"}function Y(Q,L,H){switch(Q){case'"':{z=L,U.pop(),U.push(H),U.push("INSIDE_STRING");break}case"f":case"t":case"n":{z=L,X=L,U.pop(),U.push(H),U.push("INSIDE_LITERAL");break}case"-":{U.pop(),U.push(H),U.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{z=L,U.pop(),U.push(H),U.push("INSIDE_NUMBER");break}case"{":{z=L,U.pop(),U.push(H),U.push("INSIDE_OBJECT_START");break}case"[":{z=L,U.pop(),U.push(H),U.push("INSIDE_ARRAY_START");break}}}function N(Q,L){switch(Q){case",":{U.pop(),U.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{z=L,U.pop();break}}}function W(Q,L){switch(Q){case",":{U.pop(),U.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{z=L,U.pop();break}}}for(let Q=0;Q<$.length;Q++){let L=$[Q];switch(U[U.length-1]){case"ROOT":Y(L,Q,"FINISH");break;case"INSIDE_OBJECT_START":{switch(L){case'"':{U.pop(),U.push("INSIDE_OBJECT_KEY");break}case"}":{z=Q,U.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(L){case'"':{U.pop(),U.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(L){case'"':{U.pop(),U.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(L){case":":{U.pop(),U.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{Y(L,Q,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{N(L,Q);break}case"INSIDE_STRING":{switch(L){case'"':{U.pop(),z=Q;break}case"\\":{U.push("INSIDE_STRING_ESCAPE");break}default:z=Q}break}case"INSIDE_ARRAY_START":{switch(L){case"]":{z=Q,U.pop();break}default:{z=Q,Y(L,Q,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(L){case",":{U.pop(),U.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{z=Q,U.pop();break}default:{z=Q;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{Y(L,Q,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(U.pop(),L==="u")J=0,U.push("INSIDE_STRING_UNICODE_ESCAPE");else z=Q;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(j(L)){if(J++,J===4)U.pop(),z=Q}break}case"INSIDE_NUMBER":{switch(L){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{z=Q;break}case"e":case"E":case"-":case".":break;case",":{if(U.pop(),U[U.length-1]==="INSIDE_ARRAY_AFTER_VALUE")W(L,Q);if(U[U.length-1]==="INSIDE_OBJECT_AFTER_VALUE")N(L,Q);break}case"}":{if(U.pop(),U[U.length-1]==="INSIDE_OBJECT_AFTER_VALUE")N(L,Q);break}case"]":{if(U.pop(),U[U.length-1]==="INSIDE_ARRAY_AFTER_VALUE")W(L,Q);break}default:{U.pop();break}}break}case"INSIDE_LITERAL":{let w=$.substring(X,Q+1);if(!"false".startsWith(w)&&!"true".startsWith(w)&&!"null".startsWith(w)){if(U.pop(),U[U.length-1]==="INSIDE_OBJECT_AFTER_VALUE")N(L,Q);else if(U[U.length-1]==="INSIDE_ARRAY_AFTER_VALUE")W(L,Q)}else z=Q;break}}}let G=$.slice(0,z+1);for(let Q=U.length-1;Q>=0;Q--)switch(U[Q]){case"INSIDE_STRING":{G+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{G+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{G+="]";break}case"INSIDE_LITERAL":{let H=$.substring(X,$.length);if("true".startsWith(H))G+="true".slice(H.length);else if("false".startsWith(H))G+="false".slice(H.length);else if("null".startsWith(H))G+="null".slice(H.length)}}return G}async function F0($){if($===void 0)return{value:void 0,state:"undefined-input"};let U=await x6({text:$});if(U.success)return{value:U.value,state:"successful-parse"};if(U=await x6({text:_B($)}),U.success)return{value:U.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var vB=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:$}){return $},async parsePartialOutput({text:$}){return{partial:$}},createElementStreamTransform(){return}}),FB=({schema:$,name:U,description:z})=>{let X=v0($);return{name:"object",responseFormat:jN(X.jsonSchema).then((J)=>({type:"json",schema:J,...U!=null&&{name:U},...z!=null&&{description:z}})),async parseCompleteOutput({text:J},j){let Y=await x6({text:J});if(!Y.success)throw new f6({message:"No object generated: could not parse the response.",cause:Y.error,text:J,response:j.response,usage:j.usage,finishReason:j.finishReason});let N=await y1({value:Y.value,schema:X});if(!N.success)throw new f6({message:"No object generated: response did not match schema.",cause:N.error,text:J,response:j.response,usage:j.usage,finishReason:j.finishReason});return N.value},async parsePartialOutput({text:J}){let j=await F0(J);switch(j.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:j.value}}},createElementStreamTransform(){return}}},PB=({element:$,name:U,description:z})=>{let X=v0($);return{name:"array",responseFormat:jN(X.jsonSchema).then((J)=>{let{$schema:j,...Y}=J;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:Y}},required:["elements"],additionalProperties:!1},...U!=null&&{name:U},...z!=null&&{description:z}}}),async parseCompleteOutput({text:J},j){let Y=await x6({text:J});if(!Y.success)throw new f6({message:"No object generated: could not parse the response.",cause:Y.error,text:J,response:j.response,usage:j.usage,finishReason:j.finishReason});let N=Y.value;if(N==null||typeof N!=="object"||!("elements"in N)||!Array.isArray(N.elements))throw new f6({message:"No object generated: response did not match schema.",cause:new s$({value:N,cause:"response must be an object with an elements array"}),text:J,response:j.response,usage:j.usage,finishReason:j.finishReason});let W=[];for(let G of N.elements){let Q=await y1({value:G,schema:X});if(!Q.success)throw new f6({message:"No object generated: response did not match schema.",cause:Q.error,text:J,response:j.response,usage:j.usage,finishReason:j.finishReason});W.push(Q.value)}return W},async parsePartialOutput({text:J}){let j=await F0(J);switch(j.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let Y=j.value;if(Y==null||typeof Y!=="object"||!("elements"in Y)||!Array.isArray(Y.elements))return;let N=j.state==="repaired-parse"&&Y.elements.length>0?Y.elements.slice(0,-1):Y.elements,W=[];for(let G of N){let Q=await y1({value:G,schema:X});if(Q.success)W.push(Q.value)}return{partial:W}}}},createElementStreamTransform(){let J=0;return new TransformStream({transform({partialOutput:j},Y){if(j!=null)for(;J<j.length;J++)Y.enqueue(j[J])}})}}},AB=({options:$,name:U,description:z})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:$}},required:["result"],additionalProperties:!1},...U!=null&&{name:U},...z!=null&&{description:z}}),async parseCompleteOutput({text:X},J){let j=await x6({text:X});if(!j.success)throw new f6({message:"No object generated: could not parse the response.",cause:j.error,text:X,response:J.response,usage:J.usage,finishReason:J.finishReason});let Y=j.value;if(Y==null||typeof Y!=="object"||!("result"in Y)||typeof Y.result!=="string"||!$.includes(Y.result))throw new f6({message:"No object generated: response did not match schema.",cause:new s$({value:Y,cause:"response must be an object that contains a choice value."}),text:X,response:J.response,usage:J.usage,finishReason:J.finishReason});return Y.result},async parsePartialOutput({text:X}){let J=await F0(X);switch(J.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let j=J.value;if(j==null||typeof j!=="object"||!("result"in j)||typeof j.result!=="string")return;let Y=$.filter((N)=>N.startsWith(j.result));if(J.state==="successful-parse")return Y.includes(j.result)?{partial:j.result}:void 0;else return Y.length===1?{partial:Y[0]}:void 0}}},createElementStreamTransform(){return}}},EB=({name:$,description:U}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...$!=null&&{name:$},...U!=null&&{description:U}}),async parseCompleteOutput({text:z},X){let J=await x6({text:z});if(!J.success)throw new f6({message:"No object generated: could not parse the response.",cause:J.error,text:z,response:X.response,usage:X.usage,finishReason:X.finishReason});return J.value},async parsePartialOutput({text:z}){let X=await F0(z);switch(X.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return X.value===void 0?void 0:{partial:X.value}}},createElementStreamTransform(){return}}};var vP=V$({prefix:"aitxt",size:24}),FP=V$({prefix:"call",size:24});var AP=class extends TransformStream{constructor(){super({transform($,U){U.enqueue(`data: ${JSON.stringify($)}
137
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let U of this.seen.entries()){let N=U[1];if(Y===U[0]){G(U);continue}if(J.external){let B=J.external.registry.get(U[0])?.id;if(Y!==U[0]&&B){G(U);continue}}if(this.metadataRegistry.get(U[0])?.id){G(U);continue}if(N.cycle){G(U);continue}if(N.count>1){if(J.reused==="ref"){G(U);continue}}}let W=(U,N)=>{let O=this.seen.get(U),B=O.def??O.schema,L={...B};if(O.ref===null)return;let Z=O.ref;if(O.ref=null,Z){W(Z,N);let j=this.seen.get(Z).schema;if(j.$ref&&(N.target==="draft-7"||N.target==="draft-4"||N.target==="openapi-3.0"))B.allOf=B.allOf??[],B.allOf.push(j);else Object.assign(B,j),Object.assign(B,L)}if(!O.isParent)this.override({zodSchema:U,jsonSchema:B,path:O.path??[]})};for(let U of[...this.seen.entries()].reverse())W(U[0],{target:this.target});let K={};if(this.target==="draft-2020-12")K.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")K.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")K.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(J.external?.uri){let U=J.external.registry.get(Y)?.id;if(!U)throw Error("Schema is missing an `id` property");K.$id=J.external.uri(U)}Object.assign(K,Q.def);let H=J.external?.defs??{};for(let U of this.seen.entries()){let N=U[1];if(N.def&&N.defId)H[N.defId]=N.def}if(J.external);else if(Object.keys(H).length>0)if(this.target==="draft-2020-12")K.$defs=H;else K.definitions=H;try{return JSON.parse(JSON.stringify(K))}catch(U){throw Error("Error converting schema to JSON.")}}}function s7(Y,X){if(Y instanceof vY){let Q=new U9(X),$={};for(let K of Y._idmap.entries()){let[H,U]=K;Q.process(U)}let G={},W={registry:Y,uri:X?.uri,defs:$};for(let K of Y._idmap.entries()){let[H,U]=K;G[H]=Q.emit(U,{...X,external:W})}if(Object.keys($).length>0){let K=Q.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[K]:$}}return{schemas:G}}let J=new U9(X);return J.process(Y),J.emit(Y,X)}function W0(Y,X){let J=X??{seen:new Set};if(J.seen.has(Y))return!1;J.seen.add(Y);let $=Y._zod.def;switch($.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return W0($.element,J);case"object":{for(let G in $.shape)if(W0($.shape[G],J))return!0;return!1}case"union":{for(let G of $.options)if(W0(G,J))return!0;return!1}case"intersection":return W0($.left,J)||W0($.right,J);case"tuple":{for(let G of $.items)if(W0(G,J))return!0;if($.rest&&W0($.rest,J))return!0;return!1}case"record":return W0($.keyType,J)||W0($.valueType,J);case"map":return W0($.keyType,J)||W0($.valueType,J);case"set":return W0($.valueType,J);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return W0($.innerType,J);case"lazy":return W0($.getter(),J);case"default":return W0($.innerType,J);case"prefault":return W0($.innerType,J);case"custom":return!1;case"transform":return!0;case"pipe":return W0($.in,J)||W0($.out,J);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${$.type}`)}var zz=q("ZodISODateTime",(Y,X)=>{IQ.init(Y,X),o.init(Y,X)});function a7(Y){return h7(zz,Y)}var Kz=q("ZodISODate",(Y,X)=>{SQ.init(Y,X),o.init(Y,X)});function t7(Y){return g7(Kz,Y)}var Uz=q("ZodISOTime",(Y,X)=>{kQ.init(Y,X),o.init(Y,X)});function e7(Y){return y7(Uz,Y)}var Hz=q("ZodISODuration",(Y,X)=>{bQ.init(Y,X),o.init(Y,X)});function Y$(Y){return f7(Hz,Y)}var X$=(Y,X)=>{CY.init(Y,X),Y.name="ZodError",Object.defineProperties(Y,{format:{value:(J)=>H6(Y,J)},flatten:{value:(J)=>U6(Y,J)},addIssue:{value:(J)=>{Y.issues.push(J),Y.message=JSON.stringify(Y.issues,C1,2)}},addIssues:{value:(J)=>{Y.issues.push(...J),Y.message=JSON.stringify(Y.issues,C1,2)}},isEmpty:{get(){return Y.issues.length===0}}})},UZ=q("ZodError",X$),E0=q("ZodError",X$,{Parent:Error});var J$=_Y(E0),Q$=IY(E0),$$=n1(E0),uY=o1(E0),G$=V6(E0),W$=B6(E0),z$=Z6(E0),K$=O6(E0),U$=F6(E0),H$=q6(E0),L$=j6(E0),N$=D6(E0);var r=q("ZodType",(Y,X)=>{return i.init(Y,X),Y.def=X,Y.type=X.type,Object.defineProperty(Y,"_def",{value:X}),Y.check=(...J)=>{return Y.clone({...X,checks:[...X.checks??[],...J.map((Q)=>typeof Q==="function"?{_zod:{check:Q,def:{check:"custom"},onattach:[]}}:Q)]})},Y.clone=(J,Q)=>C0(Y,J,Q),Y.brand=()=>Y,Y.register=(J,Q)=>{return J.add(Y,Q),Y},Y.parse=(J,Q)=>J$(Y,J,Q,{callee:Y.parse}),Y.safeParse=(J,Q)=>$$(Y,J,Q),Y.parseAsync=async(J,Q)=>Q$(Y,J,Q,{callee:Y.parseAsync}),Y.safeParseAsync=async(J,Q)=>uY(Y,J,Q),Y.spa=Y.safeParseAsync,Y.encode=(J,Q)=>G$(Y,J,Q),Y.decode=(J,Q)=>W$(Y,J,Q),Y.encodeAsync=async(J,Q)=>z$(Y,J,Q),Y.decodeAsync=async(J,Q)=>K$(Y,J,Q),Y.safeEncode=(J,Q)=>U$(Y,J,Q),Y.safeDecode=(J,Q)=>H$(Y,J,Q),Y.safeEncodeAsync=async(J,Q)=>L$(Y,J,Q),Y.safeDecodeAsync=async(J,Q)=>N$(Y,J,Q),Y.refine=(J,Q)=>Y.check(QK(J,Q)),Y.superRefine=(J)=>Y.check($K(J)),Y.overwrite=(J)=>Y.check(Z1(J)),Y.optional=()=>Z$(Y),Y.nullable=()=>O$(Y),Y.nullish=()=>Z$(O$(Y)),Y.nonoptional=(J)=>sz(Y,J),Y.array=()=>N9(Y),Y.or=(J)=>V9([Y,J]),Y.and=(J)=>mz(Y,J),Y.transform=(J)=>F$(Y,lz(J)),Y.default=(J)=>nz(Y,J),Y.prefault=(J)=>rz(Y,J),Y.catch=(J)=>tz(Y,J),Y.pipe=(J)=>F$(Y,J),Y.readonly=()=>XK(Y),Y.describe=(J)=>{let Q=Y.clone();return B1.add(Q,{description:J}),Q},Object.defineProperty(Y,"description",{get(){return B1.get(Y)?.description},configurable:!0}),Y.meta=(...J)=>{if(J.length===0)return B1.get(Y);let Q=Y.clone();return B1.add(Q,J[0]),Q},Y.isOptional=()=>Y.safeParse(void 0).success,Y.isNullable=()=>Y.safeParse(null).success,Y}),q$=q("_ZodString",(Y,X)=>{xY.init(Y,X),r.init(Y,X);let J=Y._zod.bag;Y.format=J.format??null,Y.minLength=J.minimum??null,Y.maxLength=J.maximum??null,Y.regex=(...Q)=>Y.check(e8(...Q)),Y.includes=(...Q)=>Y.check(J9(...Q)),Y.startsWith=(...Q)=>Y.check(Q9(...Q)),Y.endsWith=(...Q)=>Y.check($9(...Q)),Y.min=(...Q)=>Y.check(S1(...Q)),Y.max=(...Q)=>Y.check(fY(...Q)),Y.length=(...Q)=>Y.check(mY(...Q)),Y.nonempty=(...Q)=>Y.check(S1(1,...Q)),Y.lowercase=(Q)=>Y.check(Y9(Q)),Y.uppercase=(Q)=>Y.check(X9(Q)),Y.trim=()=>Y.check(W9()),Y.normalize=(...Q)=>Y.check(G9(...Q)),Y.toLowerCase=()=>Y.check(z9()),Y.toUpperCase=()=>Y.check(K9())}),Bz=q("ZodString",(Y,X)=>{xY.init(Y,X),q$.init(Y,X),Y.email=(J)=>Y.check(Z7(Zz,J)),Y.url=(J)=>Y.check(D7(Oz,J)),Y.jwt=(J)=>Y.check(v7(Sz,J)),Y.emoji=(J)=>Y.check(P7(Fz,J)),Y.guid=(J)=>Y.check(t8(V$,J)),Y.uuid=(J)=>Y.check(O7(pY,J)),Y.uuidv4=(J)=>Y.check(F7(pY,J)),Y.uuidv6=(J)=>Y.check(q7(pY,J)),Y.uuidv7=(J)=>Y.check(j7(pY,J)),Y.nanoid=(J)=>Y.check(w7(qz,J)),Y.guid=(J)=>Y.check(t8(V$,J)),Y.cuid=(J)=>Y.check(E7(jz,J)),Y.cuid2=(J)=>Y.check(M7(Dz,J)),Y.ulid=(J)=>Y.check(A7(Pz,J)),Y.base64=(J)=>Y.check(k7(Cz,J)),Y.base64url=(J)=>Y.check(b7(_z,J)),Y.xid=(J)=>Y.check(R7(wz,J)),Y.ksuid=(J)=>Y.check(T7(Ez,J)),Y.ipv4=(J)=>Y.check(C7(Mz,J)),Y.ipv6=(J)=>Y.check(_7(Az,J)),Y.cidrv4=(J)=>Y.check(I7(Rz,J)),Y.cidrv6=(J)=>Y.check(S7(Tz,J)),Y.e164=(J)=>Y.check(x7(Iz,J)),Y.datetime=(J)=>Y.check(a7(J)),Y.date=(J)=>Y.check(t7(J)),Y.time=(J)=>Y.check(e7(J)),Y.duration=(J)=>Y.check(Y$(J))});function j$(Y){return B7(Bz,Y)}var o=q("ZodStringFormat",(Y,X)=>{n.init(Y,X),q$.init(Y,X)}),Zz=q("ZodEmail",(Y,X)=>{PQ.init(Y,X),o.init(Y,X)});var V$=q("ZodGUID",(Y,X)=>{jQ.init(Y,X),o.init(Y,X)});var pY=q("ZodUUID",(Y,X)=>{DQ.init(Y,X),o.init(Y,X)});var Oz=q("ZodURL",(Y,X)=>{wQ.init(Y,X),o.init(Y,X)});var Fz=q("ZodEmoji",(Y,X)=>{EQ.init(Y,X),o.init(Y,X)});var qz=q("ZodNanoID",(Y,X)=>{MQ.init(Y,X),o.init(Y,X)});var jz=q("ZodCUID",(Y,X)=>{AQ.init(Y,X),o.init(Y,X)});var Dz=q("ZodCUID2",(Y,X)=>{RQ.init(Y,X),o.init(Y,X)});var Pz=q("ZodULID",(Y,X)=>{TQ.init(Y,X),o.init(Y,X)});var wz=q("ZodXID",(Y,X)=>{CQ.init(Y,X),o.init(Y,X)});var Ez=q("ZodKSUID",(Y,X)=>{_Q.init(Y,X),o.init(Y,X)});var Mz=q("ZodIPv4",(Y,X)=>{xQ.init(Y,X),o.init(Y,X)});var Az=q("ZodIPv6",(Y,X)=>{vQ.init(Y,X),o.init(Y,X)});var Rz=q("ZodCIDRv4",(Y,X)=>{hQ.init(Y,X),o.init(Y,X)});var Tz=q("ZodCIDRv6",(Y,X)=>{gQ.init(Y,X),o.init(Y,X)});var Cz=q("ZodBase64",(Y,X)=>{fQ.init(Y,X),o.init(Y,X)});var _z=q("ZodBase64URL",(Y,X)=>{mQ.init(Y,X),o.init(Y,X)});var Iz=q("ZodE164",(Y,X)=>{cQ.init(Y,X),o.init(Y,X)});var Sz=q("ZodJWT",(Y,X)=>{uQ.init(Y,X),o.init(Y,X)});var D$=q("ZodNumber",(Y,X)=>{s8.init(Y,X),r.init(Y,X),Y.gt=(Q,$)=>Y.check(gY(Q,$)),Y.gte=(Q,$)=>Y.check(a1(Q,$)),Y.min=(Q,$)=>Y.check(a1(Q,$)),Y.lt=(Q,$)=>Y.check(hY(Q,$)),Y.lte=(Q,$)=>Y.check(s1(Q,$)),Y.max=(Q,$)=>Y.check(s1(Q,$)),Y.int=(Q)=>Y.check(B$(Q)),Y.safe=(Q)=>Y.check(B$(Q)),Y.positive=(Q)=>Y.check(gY(0,Q)),Y.nonnegative=(Q)=>Y.check(a1(0,Q)),Y.negative=(Q)=>Y.check(hY(0,Q)),Y.nonpositive=(Q)=>Y.check(s1(0,Q)),Y.multipleOf=(Q,$)=>Y.check(yY(Q,$)),Y.step=(Q,$)=>Y.check(yY(Q,$)),Y.finite=()=>Y;let J=Y._zod.bag;Y.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Y.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Y.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),Y.isFinite=!0,Y.format=J.format??null});function P$(Y){return m7(D$,Y)}var kz=q("ZodNumberFormat",(Y,X)=>{pQ.init(Y,X),D$.init(Y,X)});function B$(Y){return c7(kz,Y)}var bz=q("ZodBoolean",(Y,X)=>{lQ.init(Y,X),r.init(Y,X)});function w$(Y){return u7(bz,Y)}var xz=q("ZodNull",(Y,X)=>{dQ.init(Y,X),r.init(Y,X)});function E$(Y){return p7(xz,Y)}var vz=q("ZodUnknown",(Y,X)=>{iQ.init(Y,X),r.init(Y,X)});function t1(){return l7(vz)}var hz=q("ZodNever",(Y,X)=>{nQ.init(Y,X),r.init(Y,X)});function L9(Y){return d7(hz,Y)}var gz=q("ZodArray",(Y,X)=>{oQ.init(Y,X),r.init(Y,X),Y.element=X.element,Y.min=(J,Q)=>Y.check(S1(J,Q)),Y.nonempty=(J)=>Y.check(S1(1,J)),Y.max=(J,Q)=>Y.check(fY(J,Q)),Y.length=(J,Q)=>Y.check(mY(J,Q)),Y.unwrap=()=>Y.element});function N9(Y,X){return i7(gz,Y,X)}var M$=q("ZodObject",(Y,X)=>{aQ.init(Y,X),r.init(Y,X),c.defineLazy(Y,"shape",()=>X.shape),Y.keyof=()=>B9(Object.keys(Y._zod.def.shape)),Y.catchall=(J)=>Y.clone({...Y._zod.def,catchall:J}),Y.passthrough=()=>Y.clone({...Y._zod.def,catchall:t1()}),Y.loose=()=>Y.clone({...Y._zod.def,catchall:t1()}),Y.strict=()=>Y.clone({...Y._zod.def,catchall:L9()}),Y.strip=()=>Y.clone({...Y._zod.def,catchall:void 0}),Y.extend=(J)=>{return c.extend(Y,J)},Y.safeExtend=(J)=>{return c.safeExtend(Y,J)},Y.merge=(J)=>c.merge(Y,J),Y.pick=(J)=>c.pick(Y,J),Y.omit=(J)=>c.omit(Y,J),Y.partial=(...J)=>c.partial(S$,Y,J[0]),Y.required=(...J)=>c.required(k$,Y,J[0])});function A$(Y,X){let J={type:"object",get shape(){return c.assignProp(this,"shape",Y?c.objectClone(Y):{}),this.shape},...c.normalizeParams(X)};return new M$(J)}function R$(Y,X){return new M$({type:"object",get shape(){return c.assignProp(this,"shape",c.objectClone(Y)),this.shape},catchall:t1(),...c.normalizeParams(X)})}var T$=q("ZodUnion",(Y,X)=>{a8.init(Y,X),r.init(Y,X),Y.options=X.options});function V9(Y,X){return new T$({type:"union",options:Y,...c.normalizeParams(X)})}var yz=q("ZodDiscriminatedUnion",(Y,X)=>{T$.init(Y,X),tQ.init(Y,X)});function C$(Y,X,J){return new yz({type:"union",options:X,discriminator:Y,...c.normalizeParams(J)})}var fz=q("ZodIntersection",(Y,X)=>{eQ.init(Y,X),r.init(Y,X)});function mz(Y,X){return new fz({type:"intersection",left:Y,right:X})}var cz=q("ZodRecord",(Y,X)=>{Y7.init(Y,X),r.init(Y,X),Y.keyType=X.keyType,Y.valueType=X.valueType});function _$(Y,X,J){return new cz({type:"record",keyType:Y,valueType:X,...c.normalizeParams(J)})}var H9=q("ZodEnum",(Y,X)=>{X7.init(Y,X),r.init(Y,X),Y.enum=X.entries,Y.options=Object.values(X.entries);let J=new Set(Object.keys(X.entries));Y.extract=(Q,$)=>{let G={};for(let W of Q)if(J.has(W))G[W]=X.entries[W];else throw Error(`Key ${W} not found in enum`);return new H9({...X,checks:[],...c.normalizeParams($),entries:G})},Y.exclude=(Q,$)=>{let G={...X.entries};for(let W of Q)if(J.has(W))delete G[W];else throw Error(`Key ${W} not found in enum`);return new H9({...X,checks:[],...c.normalizeParams($),entries:G})}});function B9(Y,X){let J=Array.isArray(Y)?Object.fromEntries(Y.map((Q)=>[Q,Q])):Y;return new H9({type:"enum",entries:J,...c.normalizeParams(X)})}var uz=q("ZodLiteral",(Y,X)=>{J7.init(Y,X),r.init(Y,X),Y.values=new Set(X.values),Object.defineProperty(Y,"value",{get(){if(X.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return X.values[0]}})});function I$(Y,X){return new uz({type:"literal",values:Array.isArray(Y)?Y:[Y],...c.normalizeParams(X)})}var pz=q("ZodTransform",(Y,X)=>{Q7.init(Y,X),r.init(Y,X),Y._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new c1(Y.constructor.name);J.addIssue=(G)=>{if(typeof G==="string")J.issues.push(c.issue(G,J.value,X));else{let W=G;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=J.value),W.inst??(W.inst=Y),J.issues.push(c.issue(W))}};let $=X.transform(J.value,J);if($ instanceof Promise)return $.then((G)=>{return J.value=G,J});return J.value=$,J}});function lz(Y){return new pz({type:"transform",transform:Y})}var S$=q("ZodOptional",(Y,X)=>{$7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function Z$(Y){return new S$({type:"optional",innerType:Y})}var dz=q("ZodNullable",(Y,X)=>{G7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function O$(Y){return new dz({type:"nullable",innerType:Y})}var iz=q("ZodDefault",(Y,X)=>{W7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeDefault=Y.unwrap});function nz(Y,X){return new iz({type:"default",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var oz=q("ZodPrefault",(Y,X)=>{z7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function rz(Y,X){return new oz({type:"prefault",innerType:Y,get defaultValue(){return typeof X==="function"?X():c.shallowClone(X)}})}var k$=q("ZodNonOptional",(Y,X)=>{K7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function sz(Y,X){return new k$({type:"nonoptional",innerType:Y,...c.normalizeParams(X)})}var az=q("ZodCatch",(Y,X)=>{U7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType,Y.removeCatch=Y.unwrap});function tz(Y,X){return new az({type:"catch",innerType:Y,catchValue:typeof X==="function"?X:()=>X})}var ez=q("ZodPipe",(Y,X)=>{H7.init(Y,X),r.init(Y,X),Y.in=X.in,Y.out=X.out});function F$(Y,X){return new ez({type:"pipe",in:Y,out:X})}var YK=q("ZodReadonly",(Y,X)=>{L7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.innerType});function XK(Y){return new YK({type:"readonly",innerType:Y})}var JK=q("ZodLazy",(Y,X)=>{N7.init(Y,X),r.init(Y,X),Y.unwrap=()=>Y._zod.def.getter()});function b$(Y){return new JK({type:"lazy",getter:Y})}var Z9=q("ZodCustom",(Y,X)=>{V7.init(Y,X),r.init(Y,X)});function x$(Y,X){return n7(Z9,Y??(()=>!0),X)}function QK(Y,X={}){return o7(Z9,Y,X)}function $K(Y){return r7(Y)}function v$(Y,X={error:`Input not instance of ${Y.name}`}){let J=new Z9({type:"custom",check:"custom",fn:(Q)=>Q instanceof Y,abort:!0,...c.normalizeParams(X)});return J._zod.bag.Class=Y,J}var GK=[{mediaType:"audio/mpeg",bytesPrefix:[255,251]},{mediaType:"audio/mpeg",bytesPrefix:[255,250]},{mediaType:"audio/mpeg",bytesPrefix:[255,243]},{mediaType:"audio/mpeg",bytesPrefix:[255,242]},{mediaType:"audio/mpeg",bytesPrefix:[255,227]},{mediaType:"audio/mpeg",bytesPrefix:[255,226]},{mediaType:"audio/wav",bytesPrefix:[82,73,70,70,null,null,null,null,87,65,86,69]},{mediaType:"audio/ogg",bytesPrefix:[79,103,103,83]},{mediaType:"audio/flac",bytesPrefix:[102,76,97,67]},{mediaType:"audio/aac",bytesPrefix:[64,21,0,0]},{mediaType:"audio/webm",bytesPrefix:[26,69,223,163]}],sZ=[...GK,{mediaType:"audio/mp4",bytesPrefix:[0,0,0,null,102,116,121,112]}];var WK=12,zK=131072,aZ=zK+WK;async function lY(Y){var X;try{await((X=Y.body)==null?void 0:X.cancel())}catch(J){}}var d$="AI_DownloadError",i$=`vercel.ai.error.${d$}`,KK=Symbol.for(i$),h$,g$,F0=class extends(g$=f,h$=KK,g$){constructor({url:Y,statusCode:X,statusText:J,cause:Q,message:$=Q==null?`Failed to download ${Y}: ${X} ${J}`:`Failed to download ${Y}: ${Q}`}){super({name:d$,message:$,cause:Q});this[h$]=!0,this.url=Y,this.statusCode=X,this.statusText=J}static isInstance(Y){return f.hasMarker(Y,i$)}};function UK(Y=globalThis){return Y.window!=null}function y$(Y,X){try{return new URL(Y).origin===new URL(X).origin}catch(J){return!1}}function HK(Y){let X;try{X=new URL(Y)}catch(Q){throw new F0({url:Y,message:`Invalid URL: ${Y}`})}if(X.protocol==="data:")return;if(X.protocol!=="http:"&&X.protocol!=="https:")throw new F0({url:Y,message:`URL scheme must be http, https, or data, got ${X.protocol}`});let J=X.hostname.toLowerCase().replace(/\.+$/,"");if(!J)throw new F0({url:Y,message:"URL must have a hostname"});if(J==="localhost"||J.endsWith(".local")||J.endsWith(".localhost"))throw new F0({url:Y,message:`URL with hostname ${J} is not allowed`});if(J.startsWith("[")&&J.endsWith("]")){let Q=J.slice(1,-1);if(n$(Q))throw new F0({url:Y,message:`URL with IPv6 address ${J} is not allowed`});return}if(P9(J)){if(w9(J))throw new F0({url:Y,message:`URL with IP address ${J} is not allowed`});return}}function LK({address:Y,family:X,hostname:J}){if(X===4?!P9(Y)||w9(Y):X===6?n$(Y):!0)throw new F0({url:J,message:`Hostname ${J} resolved to disallowed IP address ${Y}`})}function P9(Y){let X=Y.split(".");if(X.length!==4)return!1;return X.every((J)=>{let Q=Number(J);return Number.isInteger(Q)&&Q>=0&&Q<=255&&String(Q)===J})}function w9(Y){let X=Y.split(".").map(Number),[J,Q,$]=X;if(J===0)return!0;if(J===10)return!0;if(J===100&&Q>=64&&Q<=127)return!0;if(J===127)return!0;if(J===169&&Q===254)return!0;if(J===172&&Q>=16&&Q<=31)return!0;if(J===192&&Q===0&&$===0)return!0;if(J===192&&Q===0&&$===2)return!0;if(J===192&&Q===168)return!0;if(J===198&&(Q===18||Q===19))return!0;if(J===198&&Q===51&&$===100)return!0;if(J===203&&Q===0&&$===113)return!0;if(J>=224)return!0;return!1}function NK(Y){let X=Y.toLowerCase(),J=X.indexOf("%");if(J!==-1)X=X.slice(0,J);let Q=X.split("::");if(Q.length>2)return null;let $=(W)=>{if(W==="")return[];let K=[],H=W.split(":");for(let U=0;U<H.length;U++){let N=H[U];if(N.includes(".")){if(U!==H.length-1||!P9(N))return null;let[O,B,L,Z]=N.split(".").map(Number);K.push(O<<8|B,L<<8|Z);continue}if(!/^[0-9a-f]{1,4}$/.test(N))return null;K.push(parseInt(N,16))}return K},G=$(Q[0]);if(G===null)return null;if(Q.length===2){let W=$(Q[1]);if(W===null)return null;let K=8-G.length-W.length;if(K<0)return null;return[...G,...Array(K).fill(0),...W]}return G.length===8?G:null}function n$(Y){let X=NK(Y);if(X===null)return!0;let J=($)=>X.slice(0,$).every((G)=>G===0);if(J(7)&&(X[7]===0||X[7]===1))return!0;if((X[0]&65024)===64512)return!0;if((X[0]&65472)===65152)return!0;if((X[0]&65472)===65216)return!0;if((X[0]&65280)===65280)return!0;if(X[0]===8193&&X[1]===3512)return!0;if(X[0]===16383&&(X[1]&61440)===0)return!0;if(J(6)||J(5)&&X[5]===65535||J(4)&&X[4]===65535&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===0&&X[3]===0&&X[4]===0&&X[5]===0||X[0]===100&&X[1]===65435&&X[2]===1){let $=X[6]>>8&255,G=X[6]&255,W=X[7]>>8&255,K=X[7]&255;return w9(`${$}.${G}.${W}.${K}`)}return!1}function VK(Y){return(X,J,Q)=>{Y(X,{...J,all:!0},($,G)=>{if($){Q($);return}try{let[W]=G;if(W==null)throw Error(`Hostname ${X} did not resolve to an address`);for(let{address:K,family:H}of G)LK({address:K,family:H,hostname:X});if(J.all===!0)Q(null,G);else Q(null,W.address,W.family)}catch(W){Q(W instanceof Error?W:Error(String(W)))}})}}var O9,o$=globalThis.fetch,BK=FK(o$);function ZK(){var Y,X;let J=globalThis.process;return((Y=J==null?void 0:J.release)==null?void 0:Y.name)==="node"&&((X=J.versions)==null?void 0:X.bun)==null}async function OK(){if(!ZK()||!BK||globalThis.fetch!==o$)return globalThis.fetch;return O9!=null?O9:O9=Promise.resolve().then(qK)}function FK(Y){if(typeof Y!=="function")return!1;let X=Function.prototype.toString.call(Y);return X.includes("internal/deps/undici")||X.includes("lazy loading of undici")}function qK(){let{createRequire:Y}=f$("node:module"),{lookup:X}=f$("node:dns"),{Agent:J,fetch:Q}=Y(r$())("undici"),$=new J({connect:{lookup:VK(X)}});return(G,W)=>Q(G,{...W,dispatcher:$})}function f$(Y){var X;let J=globalThis.process,Q=(X=J==null?void 0:J.getBuiltinModule)==null?void 0:X.call(J,Y);if(Q==null)throw Error(`Node.js built-in module ${Y} is unavailable`);return Q}function r$(){let Y=Error.prepareStackTrace;try{Error.prepareStackTrace=($,G)=>G;let X=Error("Capture current module path");Error.captureStackTrace(X,r$);let[J]=X.stack,Q=J==null?void 0:J.getFileName();if(Q==null)throw Error("Unable to determine the current module path");return Q}finally{Error.prepareStackTrace=Y}}var jK=["connection","keep-alive","te","trailer","transfer-encoding","upgrade","host","forwarded","proxy-authorization","via","x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","metadata","metadata-flavor","x-aws-ec2-metadata-token","x-metadata-token","cookie","set-cookie"];function DK(Y){let X=new Headers(Y);for(let J of jK)X.delete(J);return X}var PK=10,wK=new Set([301,302,303,307,308]);async function s$({url:Y,headers:X,abortSignal:J,maxRedirects:Q=PK,fetch:$,trustedOrigin:G}){let W=X===void 0?void 0:DK(X),K=(U)=>{let N={signal:J,redirect:U};if(W!==void 0)N.headers=new Headers(W);return N},H=Y;for(let U=0;U<=Q;U++){let N=G!==void 0&&y$(H,G);if(!N)HK(H);let O=$!=null?$:N?globalThis.fetch:await OK(),B=await O(H,K("manual"));if(B.type==="opaqueredirect"){if(!UK())throw new F0({url:Y,message:`Redirect from ${H} could not be validated and was blocked`});return await O(H,K("follow"))}let L=B.headers.get("location");if(wK.has(B.status)&&L){await lY(B);let Z=new URL(L,H).toString();if(W!==void 0&&!y$(Z,H)){let j=W.get("user-agent");W=new Headers(j==null?void 0:{"user-agent":j})}H=Z;continue}return B}throw new F0({url:Y,message:`Too many redirects (max ${Q})`})}var E9=2147483648;async function a$({response:Y,url:X,maxBytes:J=E9}){let Q=Y.headers.get("content-length");if(Q!=null){let N=parseInt(Q,10);if(!isNaN(N)&&N>J)throw await lY(Y),new F0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes (Content-Length: ${N}).`})}let $=Y.body;if($==null)return new Uint8Array(0);let G=$.getReader(),W=[],K=0;try{while(!0){let{done:N,value:O}=await G.read();if(N)break;if(K+=O.length,K>J)throw new F0({url:X,message:`Download of ${X} exceeded maximum size of ${J} bytes.`});W.push(O)}}finally{try{await G.cancel()}finally{G.releaseLock()}}let H=new Uint8Array(K),U=0;for(let N of W)H.set(N,U),U+=N.length;return H}var J0=({prefix:Y,size:X=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:Q="-"}={})=>{let $=()=>{let G=J.length,W=Array(X);for(let K=0;K<X;K++)W[K]=J[Math.random()*G|0];return W.join("")};if(Y==null)return $;if(J.includes(Q))throw new IJ({argument:"separator",message:`The separator "${Q}" must not be part of the alphabet "${J}".`});return()=>`${Y}${Q}${$()}`},YO=J0();function t$(Y=globalThis){var X,J,Q;if(Y.window)return"runtime/browser";if((X=Y.navigator)==null?void 0:X.userAgent)return`runtime/${Y.navigator.userAgent.toLowerCase()}`;if((Q=(J=Y.process)==null?void 0:J.versions)==null?void 0:Q.node)return`runtime/node.js/${Y.process.version.substring(0)}`;if(Y.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function EK(Y){if(Y==null)return{};let X={};if(Y instanceof Headers)Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J});else{if(!Array.isArray(Y))Y=Object.entries(Y);for(let[J,Q]of Y)if(Q!=null)X[J.toLowerCase()]=Q}return X}function k1(Y,...X){let J=new Headers(EK(Y)),Q=J.get("user-agent")||"";return J.set("user-agent",[Q,...X].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}function e$(Y){var X,J;return(J=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Y))!=null?J:!1}var MK=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,AK=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function m$(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(MK.test(Y)===!1&&AK.test(Y)===!1)return X;return RK(X)}function RK(Y){let X=[Y];while(X.length){let J=X;X=[];for(let Q of J){if(Object.prototype.hasOwnProperty.call(Q,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(Q,"constructor")&&Q.constructor!==null&&typeof Q.constructor==="object"&&Object.prototype.hasOwnProperty.call(Q.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let $ in Q){let G=Q[$];if(G&&typeof G==="object")X.push(G)}}}return Y}function TK(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(J){return m$(Y)}try{return m$(Y)}finally{Error.stackTraceLimit=X}}function M9(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){Y.additionalProperties=!1;let{properties:J}=Y;if(J!=null)for(let Q of Object.keys(J))J[Q]=O1(J[Q])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(O1):O1(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(O1);if(Y.allOf!=null)Y.allOf=Y.allOf.map(O1);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(O1);let{definitions:X}=Y;if(X!=null)for(let J of Object.keys(X))X[J]=O1(X[J]);return Y}function O1(Y){if(typeof Y==="boolean")return Y;return M9(Y)}var CK=Symbol("Let zodToJsonSchema decide on which parser to use"),c$={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},_K=(Y)=>typeof Y==="string"?{...c$,name:Y}:{...c$,...Y};function M0(){return{}}function IK(Y,X){var J,Q,$;let G={type:"array"};if(((J=Y.type)==null?void 0:J._def)&&(($=(Q=Y.type)==null?void 0:Q._def)==null?void 0:$.typeName)!=="ZodAny")G.items=l(Y.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Y.minLength)G.minItems=Y.minLength.value;if(Y.maxLength)G.maxItems=Y.maxLength.value;if(Y.exactLength)G.minItems=Y.exactLength.value,G.maxItems=Y.exactLength.value;return G}function SK(Y){let X={type:"integer",format:"int64"};if(!Y.checks)return X;for(let J of Y.checks)switch(J.kind){case"min":if(J.inclusive)X.minimum=J.value;else X.exclusiveMinimum=J.value;break;case"max":if(J.inclusive)X.maximum=J.value;else X.exclusiveMaximum=J.value;break;case"multipleOf":X.multipleOf=J.value;break}return X}function kK(){return{type:"boolean"}}function YG(Y,X){return l(Y.type._def,X)}var bK=(Y,X)=>{return l(Y.innerType._def,X)};function XG(Y,X,J){let Q=J!=null?J:X.dateStrategy;if(Array.isArray(Q))return{anyOf:Q.map(($)=>XG(Y,X,$))};switch(Q){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return xK(Y)}}var xK=(Y)=>{let X={type:"integer",format:"unix-time"};for(let J of Y.checks)switch(J.kind){case"min":X.minimum=J.value;break;case"max":X.maximum=J.value;break}return X};function vK(Y,X){return{...l(Y.innerType._def,X),default:Y.defaultValue()}}function hK(Y,X){return X.effectStrategy==="input"?l(Y.schema._def,X):M0()}function gK(Y){return{type:"string",enum:Array.from(Y.values)}}var yK=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function fK(Y,X){let J=[l(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),l(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter(($)=>!!$),Q=[];return J.forEach(($)=>{if(yK($))Q.push(...$.allOf);else{let G=$;if("additionalProperties"in $&&$.additionalProperties===!1){let{additionalProperties:W,...K}=$;G=K}Q.push(G)}}),Q.length?{allOf:Q}:void 0}function mK(Y){let X=typeof Y.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(Y.value)?"array":"object"};return{type:X==="bigint"?"integer":X,const:Y.value}}var F9=void 0,I0={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(F9===void 0)F9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return F9},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function JG(Y,X){let J={type:"string"};if(Y.checks)for(let Q of Y.checks)switch(Q.kind){case"min":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value;break;case"max":J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"email":switch(X.emailStrategy){case"format:email":S0(J,"email",Q.message,X);break;case"format:idn-email":S0(J,"idn-email",Q.message,X);break;case"pattern:zod":O0(J,I0.email,Q.message,X);break}break;case"url":S0(J,"uri",Q.message,X);break;case"uuid":S0(J,"uuid",Q.message,X);break;case"regex":O0(J,Q.regex,Q.message,X);break;case"cuid":O0(J,I0.cuid,Q.message,X);break;case"cuid2":O0(J,I0.cuid2,Q.message,X);break;case"startsWith":O0(J,RegExp(`^${q9(Q.value,X)}`),Q.message,X);break;case"endsWith":O0(J,RegExp(`${q9(Q.value,X)}$`),Q.message,X);break;case"datetime":S0(J,"date-time",Q.message,X);break;case"date":S0(J,"date",Q.message,X);break;case"time":S0(J,"time",Q.message,X);break;case"duration":S0(J,"duration",Q.message,X);break;case"length":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,Q.value):Q.value,J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,Q.value):Q.value;break;case"includes":{O0(J,RegExp(q9(Q.value,X)),Q.message,X);break}case"ip":{if(Q.version!=="v6")S0(J,"ipv4",Q.message,X);if(Q.version!=="v4")S0(J,"ipv6",Q.message,X);break}case"base64url":O0(J,I0.base64url,Q.message,X);break;case"jwt":O0(J,I0.jwt,Q.message,X);break;case"cidr":{if(Q.version!=="v6")O0(J,I0.ipv4Cidr,Q.message,X);if(Q.version!=="v4")O0(J,I0.ipv6Cidr,Q.message,X);break}case"emoji":O0(J,I0.emoji(),Q.message,X);break;case"ulid":{O0(J,I0.ulid,Q.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{S0(J,"binary",Q.message,X);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{O0(J,I0.base64,Q.message,X);break}}break}case"nanoid":O0(J,I0.nanoid,Q.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function q9(Y,X){return X.patternStrategy==="escape"?uK(Y):Y}var cK=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function uK(Y){let X="";for(let J=0;J<Y.length;J++){if(!cK.has(Y[J]))X+="\\";X+=Y[J]}return X}function S0(Y,X,J,Q){var $;if(Y.format||(($=Y.anyOf)==null?void 0:$.some((G)=>G.format))){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:X,...J&&Q.errorMessages&&{errorMessage:{format:J}}})}else Y.format=X}function O0(Y,X,J,Q){var $;if(Y.pattern||(($=Y.allOf)==null?void 0:$.some((G)=>G.pattern))){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:u$(X,Q),...J&&Q.errorMessages&&{errorMessage:{pattern:J}}})}else Y.pattern=u$(X,Q)}function u$(Y,X){var J;if(!X.applyRegexFlags||!Y.flags)return Y.source;let Q={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},$=Q.i?Y.source.toLowerCase():Y.source,G="",W=!1,K=!1,H=!1;for(let U=0;U<$.length;U++){if(W){G+=$[U],W=!1;continue}if(Q.i){if(K){if($[U].match(/[a-z]/)){if(H)G+=$[U],G+=`${$[U-2]}-${$[U]}`.toUpperCase(),H=!1;else if($[U+1]==="-"&&((J=$[U+2])==null?void 0:J.match(/[a-z]/)))G+=$[U],H=!0;else G+=`${$[U]}${$[U].toUpperCase()}`;continue}}else if($[U].match(/[a-z]/)){G+=`[${$[U]}${$[U].toUpperCase()}]`;continue}}if(Q.m){if($[U]==="^"){G+=`(^|(?<=[\r
138
+ ]))`;continue}else if($[U]==="$"){G+=`($|(?=[\r
139
+ ]))`;continue}}if(Q.s&&$[U]==="."){G+=K?`${$[U]}\r
140
+ `:`[${$[U]}\r
141
+ ]`;continue}if(G+=$[U],$[U]==="\\")W=!0;else if(K&&$[U]==="]")K=!1;else if(!K&&$[U]==="[")K=!0}try{new RegExp(G)}catch(U){return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Y.source}return G}function QG(Y,X){var J,Q,$,G,W,K;let H={type:"object",additionalProperties:(J=l(Y.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]}))!=null?J:X.allowedAdditionalProperties};if(((Q=Y.keyType)==null?void 0:Q._def.typeName)==="ZodString"&&(($=Y.keyType._def.checks)==null?void 0:$.length)){let{type:U,...N}=JG(Y.keyType._def,X);return{...H,propertyNames:N}}else if(((G=Y.keyType)==null?void 0:G._def.typeName)==="ZodEnum")return{...H,propertyNames:{enum:Y.keyType._def.values}};else if(((W=Y.keyType)==null?void 0:W._def.typeName)==="ZodBranded"&&Y.keyType._def.type._def.typeName==="ZodString"&&((K=Y.keyType._def.type._def.checks)==null?void 0:K.length)){let{type:U,...N}=YG(Y.keyType._def,X);return{...H,propertyNames:N}}return H}function pK(Y,X){if(X.mapStrategy==="record")return QG(Y,X);let J=l(Y.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||M0(),Q=l(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||M0();return{type:"array",maxItems:125,items:{type:"array",items:[J,Q],minItems:2,maxItems:2}}}function lK(Y){let X=Y.values,Q=Object.keys(Y.values).filter((G)=>{return typeof X[X[G]]!=="number"}).map((G)=>X[G]),$=Array.from(new Set(Q.map((G)=>typeof G)));return{type:$.length===1?$[0]==="string"?"string":"number":["string","number"],enum:Q}}function dK(){return{not:M0()}}function iK(){return{type:"null"}}var j9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function nK(Y,X){let J=Y.options instanceof Map?Array.from(Y.options.values()):Y.options;if(J.every((Q)=>(Q._def.typeName in j9)&&(!Q._def.checks||!Q._def.checks.length))){let Q=J.reduce(($,G)=>{let W=j9[G._def.typeName];return W&&!$.includes(W)?[...$,W]:$},[]);return{type:Q.length>1?Q:Q[0]}}else if(J.every((Q)=>Q._def.typeName==="ZodLiteral"&&!Q.description)){let Q=J.reduce(($,G)=>{let W=typeof G._def.value;switch(W){case"string":case"number":case"boolean":return[...$,W];case"bigint":return[...$,"integer"];case"object":if(G._def.value===null)return[...$,"null"];case"symbol":case"undefined":case"function":default:return $}},[]);if(Q.length===J.length){let $=Q.filter((G,W,K)=>K.indexOf(G)===W);return{type:$.length>1?$:$[0],enum:J.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if(J.every((Q)=>Q._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((Q,$)=>[...Q,...$._def.values.filter((G)=>!Q.includes(G))],[])};return oK(Y,X)}var oK=(Y,X)=>{let J=(Y.options instanceof Map?Array.from(Y.options.values()):Y.options).map((Q,$)=>l(Q._def,{...X,currentPath:[...X.currentPath,"anyOf",`${$}`]})).filter((Q)=>!!Q&&(!X.strictUnions||typeof Q==="object"&&Object.keys(Q).length>0));return J.length?{anyOf:J}:void 0};function rK(Y,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Y.innerType._def.typeName)&&(!Y.innerType._def.checks||!Y.innerType._def.checks.length))return{type:[j9[Y.innerType._def.typeName],"null"]};let J=l(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function sK(Y){let X={type:"number"};if(!Y.checks)return X;for(let J of Y.checks)switch(J.kind){case"int":X.type="integer";break;case"min":if(J.inclusive)X.minimum=J.value;else X.exclusiveMinimum=J.value;break;case"max":if(J.inclusive)X.maximum=J.value;else X.exclusiveMaximum=J.value;break;case"multipleOf":X.multipleOf=J.value;break}return X}function aK(Y,X){let J={type:"object",properties:{}},Q=[],$=Y.shape();for(let W in $){let K=$[W];if(K===void 0||K._def===void 0)continue;let H=eK(K),U=l(K._def,{...X,currentPath:[...X.currentPath,"properties",W],propertyPath:[...X.currentPath,"properties",W]});if(U===void 0)continue;if(J.properties[W]=U,!H)Q.push(W)}if(Q.length)J.required=Q;let G=tK(Y,X);if(G!==void 0)J.additionalProperties=G;return J}function tK(Y,X){if(Y.catchall._def.typeName!=="ZodNever")return l(Y.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Y.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function eK(Y){try{return Y.isOptional()}catch(X){return!0}}var YU=(Y,X)=>{var J;if(X.currentPath.toString()===((J=X.propertyPath)==null?void 0:J.toString()))return l(Y.innerType._def,X);let Q=l(Y.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:M0()},Q]}:M0()},XU=(Y,X)=>{if(X.pipeStrategy==="input")return l(Y.in._def,X);else if(X.pipeStrategy==="output")return l(Y.out._def,X);let J=l(Y.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),Q=l(Y.out._def,{...X,currentPath:[...X.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,Q].filter(($)=>$!==void 0)}};function JU(Y,X){return l(Y.type._def,X)}function QU(Y,X){let Q={type:"array",uniqueItems:!0,items:l(Y.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Y.minSize)Q.minItems=Y.minSize.value;if(Y.maxSize)Q.maxItems=Y.maxSize.value;return Q}function $U(Y,X){if(Y.rest)return{type:"array",minItems:Y.items.length,items:Y.items.map((J,Q)=>l(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[]),additionalItems:l(Y.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Y.items.length,maxItems:Y.items.length,items:Y.items.map((J,Q)=>l(J._def,{...X,currentPath:[...X.currentPath,"items",`${Q}`]})).reduce((J,Q)=>Q===void 0?J:[...J,Q],[])}}function GU(){return{not:M0()}}function WU(){return M0()}var zU=(Y,X)=>{return l(Y.innerType._def,X)},KU=(Y,X,J)=>{switch(X){case"ZodString":return JG(Y,J);case"ZodNumber":return sK(Y);case"ZodObject":return aK(Y,J);case"ZodBigInt":return SK(Y);case"ZodBoolean":return kK();case"ZodDate":return XG(Y,J);case"ZodUndefined":return GU();case"ZodNull":return iK();case"ZodArray":return IK(Y,J);case"ZodUnion":case"ZodDiscriminatedUnion":return nK(Y,J);case"ZodIntersection":return fK(Y,J);case"ZodTuple":return $U(Y,J);case"ZodRecord":return QG(Y,J);case"ZodLiteral":return mK(Y);case"ZodEnum":return gK(Y);case"ZodNativeEnum":return lK(Y);case"ZodNullable":return rK(Y,J);case"ZodOptional":return YU(Y,J);case"ZodMap":return pK(Y,J);case"ZodSet":return QU(Y,J);case"ZodLazy":return()=>Y.getter()._def;case"ZodPromise":return JU(Y,J);case"ZodNaN":case"ZodNever":return dK();case"ZodEffects":return hK(Y,J);case"ZodAny":return M0();case"ZodUnknown":return WU();case"ZodDefault":return vK(Y,J);case"ZodBranded":return YG(Y,J);case"ZodReadonly":return zU(Y,J);case"ZodCatch":return bK(Y,J);case"ZodPipeline":return XU(Y,J);case"ZodFunction":case"ZodVoid":case"ZodSymbol":return;default:return((Q)=>{return})(X)}},UU=(Y,X)=>{let J=0;for(;J<Y.length&&J<X.length;J++)if(Y[J]!==X[J])break;return[(Y.length-J).toString(),...X.slice(J)].join("/")};function l(Y,X,J=!1){var Q;let $=X.seen.get(Y);if(X.override){let H=(Q=X.override)==null?void 0:Q.call(X,Y,X,$,J);if(H!==CK)return H}if($&&!J){let H=HU($,X);if(H!==void 0)return H}let G={def:Y,path:X.currentPath,jsonSchema:void 0};X.seen.set(Y,G);let W=KU(Y,Y.typeName,X),K=typeof W==="function"?l(W(),X):W;if(K)LU(Y,X,K);if(X.postProcess){let H=X.postProcess(K,Y,X);return G.jsonSchema=K,H}return G.jsonSchema=K,K}var HU=(Y,X)=>{switch(X.$refStrategy){case"root":return{$ref:Y.path.join("/")};case"relative":return{$ref:UU(X.currentPath,Y.path)};case"none":case"seen":{if(Y.path.length<X.currentPath.length&&Y.path.every((J,Q)=>X.currentPath[Q]===J))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),M0();return X.$refStrategy==="seen"?M0():void 0}}},LU=(Y,X,J)=>{if(Y.description)J.description=Y.description;return J},NU=(Y)=>{let X=_K(Y),J=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:J,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([Q,$])=>[$._def,{def:$._def,path:[...X.basePath,X.definitionPath,Q],jsonSchema:void 0}]))}},VU=(Y,X)=>{var J;let Q=NU(X),$=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((U,[N,O])=>{var B;return{...U,[N]:(B=l(O._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,N]},!0))!=null?B:M0()}},{}):void 0,G=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,W=(J=l(Y._def,G===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,G]},!1))!=null?J:M0(),K=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(K!==void 0)W.title=K;let H=G===void 0?$?{...W,[Q.definitionPath]:$}:W:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,G].join("/"),[Q.definitionPath]:{...$,[G]:W}};return H.$schema="http://json-schema.org/draft-07/schema#",H},D9=Symbol.for("vercel.ai.schema");function dY(Y){let X;return()=>{if(X==null)X=Y();return X}}function iY(Y,{validate:X}={}){return{[D9]:!0,_type:void 0,get jsonSchema(){if(typeof Y==="function")Y=Y();return Y},validate:X}}function BU(Y){return typeof Y==="object"&&Y!==null&&D9 in Y&&Y[D9]===!0&&"jsonSchema"in Y&&"validate"in Y}function nY(Y){return Y==null?iY({type:"object",properties:{},additionalProperties:!1}):BU(Y)?Y:("~standard"in Y)?Y["~standard"].vendor==="zod"?e1(Y):ZU(Y):Y()}function ZU(Y){return iY(()=>{if(!OU(Y))throw Error(`Standard schema vendor '${Y["~standard"].vendor}' does not support JSON Schema conversion.`);return M9(Y["~standard"].jsonSchema.input({target:"draft-07"}))},{validate:async(X)=>{let J=await Y["~standard"].validate(X);return"value"in J?{success:!0,value:J.value}:{success:!1,error:new v0({value:X,cause:J.issues})}}})}function OU(Y){return Y["~standard"].jsonSchema!=null}function FU(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return iY(()=>VU(Y,{$refStrategy:Q?"root":"none"}),{validate:async($)=>{let G=await Y.safeParseAsync($);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function qU(Y,X){var J;let Q=(J=X==null?void 0:X.useReferences)!=null?J:!1;return iY(()=>M9(s7(Y,{target:"draft-7",io:"input",reused:Q?"ref":"inline"})),{validate:async($)=>{let G=await uY(Y,$);return G.success?{success:!0,value:G.data}:{success:!1,error:G.error}}})}function jU(Y){return"_zod"in Y}function e1(Y,X){if(jU(Y))return qU(Y,X);else return FU(Y,X)}async function YY({value:Y,schema:X,context:J}){let Q=nY(X);try{if(Q.validate==null)return{success:!0,value:Y,rawValue:Y};let $=await Q.validate(Y);if($.success)return{success:!0,value:$.value,rawValue:Y};return{success:!1,error:v0.wrap({value:Y,cause:$.error,context:J}),rawValue:Y}}catch($){return{success:!1,error:v0.wrap({value:Y,cause:$,context:J}),rawValue:Y}}}async function J1({text:Y,schema:X}){try{let J=TK(Y);if(X==null)return{success:!0,value:J,rawValue:J};return await YY({value:J,schema:X})}catch(J){return{success:!1,error:MY.isInstance(J)?J:new MY({text:Y,cause:J}),rawValue:void 0}}}async function A9(Y){if(typeof Y==="function")Y=Y();return Promise.resolve(Y)}var $G="AI_SerializationError",GG=`vercel.ai.error.${$G}`,DU=Symbol.for(GG),p$,l$,zO=class extends(l$=f,p$=DU,l$){constructor({message:Y="Failed to serialize value.",cause:X}={}){super({name:$G,message:Y,cause:X});this[p$]=!0}static isInstance(Y){return f.hasMarker(Y,GG)}};var EU=Object.defineProperty,MU=(Y,X)=>{for(var J in X)EU(Y,J,{get:X[J],enumerable:!0})},AU="AI_InvalidArgumentError",RU=`vercel.ai.error.${AU}`,TU=Symbol.for(RU),CU;CU=TU;var _U="AI_InvalidStreamPartError",IU=`vercel.ai.error.${_U}`,SU=Symbol.for(IU),kU;kU=SU;var bU="AI_InvalidToolApprovalError",xU=`vercel.ai.error.${bU}`,vU=Symbol.for(xU),hU;hU=vU;var gU="AI_InvalidToolApprovalSignatureError",yU=`vercel.ai.error.${gU}`,fU=Symbol.for(yU),mU;mU=fU;var cU="AI_InvalidToolInputError",uU=`vercel.ai.error.${cU}`,pU=Symbol.for(uU),lU;lU=pU;var dU="AI_ToolCallNotFoundForApprovalError",iU=`vercel.ai.error.${dU}`,nU=Symbol.for(iU),oU;oU=nU;var rU="AI_MissingToolResultsError",sU=`vercel.ai.error.${rU}`,aU=Symbol.for(sU),tU;tU=aU;var eU="AI_NoImageGeneratedError",YH=`vercel.ai.error.${eU}`,XH=Symbol.for(YH),JH;JH=XH;var WG="AI_NoObjectGeneratedError",zG=`vercel.ai.error.${WG}`,QH=Symbol.for(zG),KG,Q1=class extends f{constructor({message:Y="No object generated.",cause:X,text:J,response:Q,usage:$,finishReason:G}){super({name:WG,message:Y,cause:X});this[KG]=!0,this.text=J,this.response=Q,this.usage=$,this.finishReason=G}static isInstance(Y){return f.hasMarker(Y,zG)}};KG=QH;var $H="AI_NoOutputGeneratedError",GH=`vercel.ai.error.${$H}`,WH=Symbol.for(GH),zH;zH=WH;var KH="AI_NoSpeechGeneratedError",UH=`vercel.ai.error.${KH}`,HH=Symbol.for(UH),LH;LH=HH;var NH="AI_NoTranscriptGeneratedError",VH=`vercel.ai.error.${NH}`,BH=Symbol.for(VH),ZH;ZH=BH;var OH="AI_NoTranslationGeneratedError",FH=`vercel.ai.error.${OH}`,qH=Symbol.for(FH),jH;jH=qH;var DH="AI_NoVideoGeneratedError",PH=`vercel.ai.error.${DH}`,wH=Symbol.for(PH),EH;EH=wH;var MH="AI_NoSuchToolError",AH=`vercel.ai.error.${MH}`,RH=Symbol.for(AH),TH;TH=RH;var CH="AI_ToolCallRepairError",_H=`vercel.ai.error.${CH}`,IH=Symbol.for(_H),SH;SH=IH;var kH="AI_UIMessageStreamError",bH=`vercel.ai.error.${kH}`,xH=Symbol.for(bH),vH;vH=xH;var hH="AI_InvalidDataContentError",gH=`vercel.ai.error.${hH}`,yH=Symbol.for(gH),fH;fH=yH;var mH="AI_InvalidMessageRoleError",cH=`vercel.ai.error.${mH}`,uH=Symbol.for(cH),pH;pH=uH;var lH="AI_MessageConversionError",dH=`vercel.ai.error.${lH}`,iH=Symbol.for(dH),nH;nH=iH;var oH="AI_RetryError",rH=`vercel.ai.error.${oH}`,sH=Symbol.for(rH),aH;aH=sH;var tH="7.0.59",eH=async({url:Y,maxBytes:X,abortSignal:J})=>{var Q;let $=Y.toString();try{let G=k1({},`ai-sdk/${tH}`,t$()),W=await s$({url:$,headers:G,abortSignal:J});if(!W.ok)throw await lY(W),new F0({url:$,statusCode:W.status,statusText:W.statusText});return{data:await a$({response:W,url:$,maxBytes:X!=null?X:E9}),mediaType:(Q=W.headers.get("content-type"))!=null?Q:void 0}}catch(G){if(F0.isInstance(G))throw G;throw new F0({url:$,cause:G})}};var z={array:N9,boolean:w$,custom:x$,discriminatedUnion:C$,enum:B9,instanceof:v$,lazy:b$,literal:I$,looseObject:R$,never:L9,null:E$,number:P$,object:A$,record:_$,string:j$,union:V9,unknown:t1},F1=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),F1.optional()),z.array(F1)])),A=z.record(z.string(),z.record(z.string(),F1.optional())),JY=z.union([z.string(),z.instanceof(Uint8Array),z.instanceof(ArrayBuffer),z.custom(e$,{message:"Must be a Buffer"})]),R9=z.record(z.string(),z.string()),UG=z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),YL=z.object({type:z.literal("image"),image:z.union([JY,z.instanceof(URL),R9]),mediaType:z.string().optional(),providerOptions:A.optional()}),HG=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:JY}),z.object({type:z.literal("url"),url:z.instanceof(URL)}),z.object({type:z.literal("reference"),reference:R9}),z.object({type:z.literal("text"),text:z.string()})]),XL=z.discriminatedUnion("type",[z.object({type:z.literal("data"),data:JY}),z.object({type:z.literal("url"),url:z.instanceof(URL)})]),LG=z.object({type:z.literal("file"),data:z.union([HG,JY,z.instanceof(URL),R9]),filename:z.string().optional(),mediaType:z.string(),providerOptions:A.optional()}),JL=z.object({type:z.literal("reasoning"),text:z.string(),providerOptions:A.optional()}),QL=z.object({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerOptions:A.optional()}),$L=z.object({type:z.literal("reasoning-file"),data:z.union([XL,JY,z.instanceof(URL)]),mediaType:z.string(),providerOptions:A.optional()}),GL=z.object({type:z.literal("tool-call"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerOptions:A.optional(),providerExecuted:z.boolean().optional()}),WL=z.discriminatedUnion("type",[z.object({type:z.literal("text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("json"),value:F1,providerOptions:A.optional()}),z.object({type:z.literal("execution-denied"),reason:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("error-text"),value:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("error-json"),value:F1,providerOptions:A.optional()}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("file"),data:HG,mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-data"),data:z.string(),mediaType:z.string(),filename:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-url"),url:z.string(),mediaType:z.string().optional(),providerOptions:A.optional()}),z.object({type:z.literal("file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("image-data"),data:z.string(),mediaType:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-url"),url:z.string(),providerOptions:A.optional()}),z.object({type:z.literal("image-file-id"),fileId:z.union([z.string(),z.record(z.string(),z.string())]),providerOptions:A.optional()}),z.object({type:z.literal("image-file-reference"),providerReference:z.record(z.string(),z.string()),providerOptions:A.optional()}),z.object({type:z.literal("custom"),providerOptions:A.optional()})]))})]),NG=z.object({type:z.literal("tool-result"),toolCallId:z.string(),toolName:z.string(),output:WL,providerOptions:A.optional()}),zL=z.object({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string()}),KL=z.object({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional()}),UL=z.object({role:z.literal("system"),content:z.string(),providerOptions:A.optional()}),HL=z.object({role:z.literal("user"),content:z.union([z.string(),z.array(z.union([UG,YL,LG]))]),providerOptions:A.optional()}),LL=z.object({role:z.literal("assistant"),content:z.union([z.string(),z.array(z.union([UG,QL,LG,JL,$L,GL,NG,zL]))]),providerOptions:A.optional()}),NL=z.object({role:z.literal("tool"),content:z.array(z.union([NG,KL])),providerOptions:A.optional()}),PO=z.union([UL,HL,LL,NL]);var VL={};MU(VL,{array:()=>FL,choice:()=>qL,json:()=>jL,object:()=>OL,text:()=>ZL});function BL(Y){let X=["ROOT"],J=-1,Q=null,$=0;function G(N){return N>="0"&&N<="9"||N>="A"&&N<="F"||N>="a"&&N<="f"}function W(N,O,B){switch(N){case'"':{J=O,X.pop(),X.push(B),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{J=O,Q=O,X.pop(),X.push(B),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(B),X.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=O,X.pop(),X.push(B),X.push("INSIDE_NUMBER");break}case"{":{J=O,X.pop(),X.push(B),X.push("INSIDE_OBJECT_START");break}case"[":{J=O,X.pop(),X.push(B),X.push("INSIDE_ARRAY_START");break}}}function K(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{J=O,X.pop();break}}}function H(N,O){switch(N){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=O,X.pop();break}}}for(let N=0;N<Y.length;N++){let O=Y[N];switch(X[X.length-1]){case"ROOT":W(O,N,"FINISH");break;case"INSIDE_OBJECT_START":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{J=N,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(O){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(O){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{W(O,N,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{K(O,N);break}case"INSIDE_STRING":{switch(O){case'"':{X.pop(),J=N;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:J=N}break}case"INSIDE_ARRAY_START":{switch(O){case"]":{J=N,X.pop();break}default:{J=N,W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(O){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{J=N,X.pop();break}default:{J=N;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{W(O,N,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{if(X.pop(),O==="u")$=0,X.push("INSIDE_STRING_UNICODE_ESCAPE");else J=N;break}case"INSIDE_STRING_UNICODE_ESCAPE":{if(G(O)){if($++,$===4)X.pop(),J=N}break}case"INSIDE_NUMBER":{switch(O){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{J=N;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(O,N);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(O,N);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let L=Y.substring(Q,N+1);if(!"false".startsWith(L)&&!"true".startsWith(L)&&!"null".startsWith(L)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")K(O,N);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")H(O,N)}else J=N;break}}}let U=Y.slice(0,J+1);for(let N=X.length-1;N>=0;N--)switch(X[N]){case"INSIDE_STRING":{U+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{U+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{U+="]";break}case"INSIDE_LITERAL":{let B=Y.substring(Q,Y.length);if("true".startsWith(B))U+="true".slice(B.length);else if("false".startsWith(B))U+="false".slice(B.length);else if("null".startsWith(B))U+="null".slice(B.length)}}return U}async function oY(Y){if(Y===void 0)return{value:void 0,state:"undefined-input"};let X=await J1({text:Y});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await J1({text:BL(Y)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var ZL=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Y}){return Y},async parsePartialOutput({text:Y}){return{partial:Y}},createElementStreamTransform(){return}}),OL=({schema:Y,name:X,description:J})=>{let Q=nY(Y);return{name:"object",responseFormat:A9(Q.jsonSchema).then(($)=>({type:"json",schema:$,...X!=null&&{name:X},...J!=null&&{description:J}})),async parseCompleteOutput({text:$},G){let W=await J1({text:$});if(!W.success)throw new Q1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let K=await YY({value:W.value,schema:Q});if(!K.success)throw new Q1({message:"No object generated: response did not match schema.",cause:K.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});return K.value},async parsePartialOutput({text:$}){let G=await oY($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:G.value}}},createElementStreamTransform(){return}}},FL=({element:Y,name:X,description:J})=>{let Q=nY(Y);return{name:"array",responseFormat:A9(Q.jsonSchema).then(($)=>{let{$schema:G,...W}=$;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:W}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}}),async parseCompleteOutput({text:$},G){let W=await J1({text:$});if(!W.success)throw new Q1({message:"No object generated: could not parse the response.",cause:W.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let K=W.value;if(K==null||typeof K!=="object"||!("elements"in K)||!Array.isArray(K.elements))throw new Q1({message:"No object generated: response did not match schema.",cause:new v0({value:K,cause:"response must be an object with an elements array"}),text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});let H=[];for(let U of K.elements){let N=await YY({value:U,schema:Q});if(!N.success)throw new Q1({message:"No object generated: response did not match schema.",cause:N.error,text:$,response:G.response,usage:G.usage,finishReason:G.finishReason});H.push(N.value)}return H},async parsePartialOutput({text:$}){let G=await oY($);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let W=G.value;if(W==null||typeof W!=="object"||!("elements"in W)||!Array.isArray(W.elements))return;let K=G.state==="repaired-parse"&&W.elements.length>0?W.elements.slice(0,-1):W.elements,H=[];for(let U of K){let N=await YY({value:U,schema:Q});if(N.success)H.push(N.value)}return{partial:H}}}},createElementStreamTransform(){let $=0;return new TransformStream({transform({partialOutput:G},W){if(G!=null)for(;$<G.length;$++)W.enqueue(G[$])}})}}},qL=({options:Y,name:X,description:J})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Y}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...J!=null&&{description:J}}),async parseCompleteOutput({text:Q},$){let G=await J1({text:Q});if(!G.success)throw new Q1({message:"No object generated: could not parse the response.",cause:G.error,text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});let W=G.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string"||!Y.includes(W.result))throw new Q1({message:"No object generated: response did not match schema.",cause:new v0({value:W,cause:"response must be an object that contains a choice value."}),text:Q,response:$.response,usage:$.usage,finishReason:$.finishReason});return W.result},async parsePartialOutput({text:Q}){let $=await oY(Q);switch($.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let G=$.value;if(G==null||typeof G!=="object"||!("result"in G)||typeof G.result!=="string")return;let W=Y.filter((K)=>K.startsWith(G.result));if($.state==="successful-parse")return W.includes(G.result)?{partial:G.result}:void 0;else return W.length===1?{partial:W[0]}:void 0}}},createElementStreamTransform(){return}}},jL=({name:Y,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Y!=null&&{name:Y},...X!=null&&{description:X}}),async parseCompleteOutput({text:J},Q){let $=await J1({text:J});if(!$.success)throw new Q1({message:"No object generated: could not parse the response.",cause:$.error,text:J,response:Q.response,usage:Q.usage,finishReason:Q.finishReason});return $.value},async parsePartialOutput({text:J}){let Q=await oY(J);switch(Q.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return Q.value===void 0?void 0:{partial:Q.value}}},createElementStreamTransform(){return}}};var AO=J0({prefix:"aitxt",size:24}),RO=J0({prefix:"call",size:24});var CO=class extends TransformStream{constructor(){super({transform(Y,X){X.enqueue(`data: ${JSON.stringify(Y)}
129
142
 
130
- `)},flush($){$.enqueue(`data: [DONE]
143
+ `)},flush(Y){Y.enqueue(`data: [DONE]
131
144
 
132
- `)}})}};var c1=O.record(O.string(),$4.optional()),bP=q0(()=>h1(O.union([O.looseObject({type:O.literal("text-start"),id:O.string(),providerMetadata:I.optional()}),O.looseObject({type:O.literal("text-delta"),id:O.string(),delta:O.string(),providerMetadata:I.optional()}),O.looseObject({type:O.literal("text-end"),id:O.string(),providerMetadata:I.optional()}),O.looseObject({type:O.literal("error"),errorText:O.string()}),O.looseObject({type:O.literal("tool-input-start"),toolCallId:O.string(),toolName:O.string(),providerExecuted:O.boolean().optional(),providerMetadata:I.optional(),toolMetadata:c1.optional(),dynamic:O.boolean().optional(),title:O.string().optional()}),O.looseObject({type:O.literal("tool-input-delta"),toolCallId:O.string(),inputTextDelta:O.string()}),O.looseObject({type:O.literal("tool-input-available"),toolCallId:O.string(),toolName:O.string(),input:O.unknown(),providerExecuted:O.boolean().optional(),providerMetadata:I.optional(),toolMetadata:c1.optional(),dynamic:O.boolean().optional(),title:O.string().optional()}),O.looseObject({type:O.literal("tool-input-error"),toolCallId:O.string(),toolName:O.string(),input:O.unknown(),providerExecuted:O.boolean().optional(),providerMetadata:I.optional(),toolMetadata:c1.optional(),dynamic:O.boolean().optional(),errorText:O.string(),title:O.string().optional()}),O.looseObject({type:O.literal("tool-approval-request"),approvalId:O.string(),toolCallId:O.string(),isAutomatic:O.boolean().optional(),signature:O.string().optional()}),O.looseObject({type:O.literal("tool-approval-response"),approvalId:O.string(),approved:O.boolean(),reason:O.string().optional(),providerExecuted:O.boolean().optional(),providerMetadata:I.optional()}),O.looseObject({type:O.literal("tool-output-available"),toolCallId:O.string(),output:O.unknown(),providerExecuted:O.boolean().optional(),providerMetadata:I.optional(),toolMetadata:c1.optional(),dynamic:O.boolean().optional(),preliminary:O.boolean().optional()}),O.looseObject({type:O.literal("tool-output-error"),toolCallId:O.string(),errorText:O.string(),providerExecuted:O.boolean().optional(),providerMetadata:I.optional(),toolMetadata:c1.optional(),dynamic:O.boolean().optional()}),O.looseObject({type:O.literal("tool-output-denied"),toolCallId:O.string()}),O.looseObject({type:O.literal("reasoning-start"),id:O.string(),providerMetadata:I.optional()}),O.looseObject({type:O.literal("reasoning-delta"),id:O.string(),delta:O.string(),providerMetadata:I.optional()}),O.looseObject({type:O.literal("reasoning-end"),id:O.string(),providerMetadata:I.optional()}),O.looseObject({type:O.literal("custom"),kind:O.string().transform(($)=>$),providerMetadata:I.optional()}),O.looseObject({type:O.literal("source-url"),sourceId:O.string(),url:O.string(),title:O.string().optional(),providerMetadata:I.optional()}),O.looseObject({type:O.literal("source-document"),sourceId:O.string(),mediaType:O.string(),title:O.string(),filename:O.string().optional(),providerMetadata:I.optional()}),O.looseObject({type:O.literal("file"),url:O.string(),mediaType:O.string(),providerMetadata:I.optional()}),O.looseObject({type:O.literal("reasoning-file"),url:O.string(),mediaType:O.string(),providerMetadata:I.optional()}),O.looseObject({type:O.custom(($)=>typeof $==="string"&&$.startsWith("data-"),{message:'Type must start with "data-"'}),id:O.string().optional(),data:O.unknown(),transient:O.boolean().optional()}),O.looseObject({type:O.literal("start-step")}),O.looseObject({type:O.literal("finish-step")}),O.looseObject({type:O.literal("start"),messageId:O.string().optional(),messageMetadata:O.unknown().optional()}),O.looseObject({type:O.literal("finish"),finishReason:O.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:O.unknown().optional()}),O.looseObject({type:O.literal("abort"),reason:O.string().optional()}),O.looseObject({type:O.literal("message-metadata"),messageMetadata:O.unknown()})])));var IP=V$({prefix:"aitxt",size:24}),SP=V$({prefix:"call",size:24});var kP=V$({prefix:"aitxt",size:24}),CP=V$({prefix:"call",size:24});var C$=O.record(O.string(),$4.optional()),MB=O.record(O.string(),O.string()),gP=q0(()=>h1(O.array(O.object({id:O.string(),role:O.enum(["system","user","assistant"]),metadata:O.unknown().optional(),parts:O.array(O.union([O.object({type:O.literal("text"),text:O.string(),state:O.enum(["streaming","done"]).optional(),providerMetadata:I.optional()}),O.object({type:O.literal("reasoning"),text:O.string(),state:O.enum(["streaming","done"]).optional(),providerMetadata:I.optional()}),O.object({type:O.literal("custom"),kind:O.string(),providerMetadata:I.optional()}),O.object({type:O.literal("source-url"),sourceId:O.string(),url:O.string(),title:O.string().optional(),providerMetadata:I.optional()}),O.object({type:O.literal("source-document"),sourceId:O.string(),mediaType:O.string(),title:O.string(),filename:O.string().optional(),providerMetadata:I.optional()}),O.object({type:O.literal("file"),mediaType:O.string(),filename:O.string().optional(),url:O.string(),providerReference:MB.optional(),providerMetadata:I.optional()}),O.object({type:O.literal("reasoning-file"),mediaType:O.string(),url:O.string(),providerMetadata:I.optional()}),O.object({type:O.literal("step-start")}),O.object({type:O.string().startsWith("data-"),id:O.string().optional(),data:O.unknown()}),O.object({type:O.literal("dynamic-tool"),toolName:O.string(),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("input-streaming"),input:O.unknown().optional(),providerExecuted:O.boolean().optional(),callProviderMetadata:I.optional(),output:O.never().optional(),errorText:O.never().optional(),approval:O.never().optional()}),O.object({type:O.literal("dynamic-tool"),toolName:O.string(),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("input-available"),input:O.unknown(),providerExecuted:O.boolean().optional(),output:O.never().optional(),errorText:O.never().optional(),callProviderMetadata:I.optional(),approval:O.never().optional()}),O.object({type:O.literal("dynamic-tool"),toolName:O.string(),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("approval-requested"),input:O.unknown(),providerExecuted:O.boolean().optional(),output:O.never().optional(),errorText:O.never().optional(),callProviderMetadata:I.optional(),approval:O.object({id:O.string(),approved:O.never().optional(),reason:O.never().optional(),isAutomatic:O.boolean().optional(),signature:O.string().optional()})}),O.object({type:O.literal("dynamic-tool"),toolName:O.string(),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("approval-responded"),input:O.unknown(),providerExecuted:O.boolean().optional(),output:O.never().optional(),errorText:O.never().optional(),callProviderMetadata:I.optional(),approval:O.object({id:O.string(),approved:O.boolean(),reason:O.string().optional(),isAutomatic:O.boolean().optional(),signature:O.string().optional()})}),O.object({type:O.literal("dynamic-tool"),toolName:O.string(),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("output-available"),input:O.unknown(),providerExecuted:O.boolean().optional(),output:O.unknown(),errorText:O.never().optional(),callProviderMetadata:I.optional(),resultProviderMetadata:I.optional(),preliminary:O.boolean().optional(),approval:O.object({id:O.string(),approved:O.literal(!0),reason:O.string().optional(),isAutomatic:O.boolean().optional(),signature:O.string().optional()}).optional()}),O.object({type:O.literal("dynamic-tool"),toolName:O.string(),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("output-error"),input:O.unknown().optional(),rawInput:O.unknown().optional(),providerExecuted:O.boolean().optional(),output:O.never().optional(),errorText:O.string(),callProviderMetadata:I.optional(),resultProviderMetadata:I.optional(),approval:O.object({id:O.string(),approved:O.literal(!0),reason:O.string().optional(),isAutomatic:O.boolean().optional(),signature:O.string().optional()}).optional()}),O.object({type:O.literal("dynamic-tool"),toolName:O.string(),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("output-denied"),input:O.unknown(),providerExecuted:O.boolean().optional(),output:O.never().optional(),errorText:O.never().optional(),callProviderMetadata:I.optional(),approval:O.object({id:O.string(),approved:O.literal(!1),reason:O.string().optional(),isAutomatic:O.boolean().optional(),signature:O.string().optional()})}),O.object({type:O.string().startsWith("tool-"),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("input-streaming"),providerExecuted:O.boolean().optional(),callProviderMetadata:I.optional(),input:O.unknown().optional(),output:O.never().optional(),errorText:O.never().optional(),approval:O.never().optional()}),O.object({type:O.string().startsWith("tool-"),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("input-available"),providerExecuted:O.boolean().optional(),input:O.unknown(),output:O.never().optional(),errorText:O.never().optional(),callProviderMetadata:I.optional(),approval:O.never().optional()}),O.object({type:O.string().startsWith("tool-"),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("approval-requested"),input:O.unknown(),providerExecuted:O.boolean().optional(),output:O.never().optional(),errorText:O.never().optional(),callProviderMetadata:I.optional(),approval:O.object({id:O.string(),approved:O.never().optional(),reason:O.never().optional(),isAutomatic:O.boolean().optional(),signature:O.string().optional()})}),O.object({type:O.string().startsWith("tool-"),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("approval-responded"),input:O.unknown(),providerExecuted:O.boolean().optional(),output:O.never().optional(),errorText:O.never().optional(),callProviderMetadata:I.optional(),approval:O.object({id:O.string(),approved:O.boolean(),reason:O.string().optional(),isAutomatic:O.boolean().optional(),signature:O.string().optional()})}),O.object({type:O.string().startsWith("tool-"),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("output-available"),providerExecuted:O.boolean().optional(),input:O.unknown(),output:O.unknown(),errorText:O.never().optional(),callProviderMetadata:I.optional(),resultProviderMetadata:I.optional(),preliminary:O.boolean().optional(),approval:O.object({id:O.string(),approved:O.literal(!0),reason:O.string().optional(),isAutomatic:O.boolean().optional(),signature:O.string().optional()}).optional()}),O.object({type:O.string().startsWith("tool-"),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("output-error"),providerExecuted:O.boolean().optional(),input:O.unknown().optional(),rawInput:O.unknown().optional(),output:O.never().optional(),errorText:O.string(),callProviderMetadata:I.optional(),resultProviderMetadata:I.optional(),approval:O.object({id:O.string(),approved:O.literal(!0),reason:O.string().optional(),isAutomatic:O.boolean().optional(),signature:O.string().optional()}).optional()}),O.object({type:O.string().startsWith("tool-"),toolCallId:O.string(),toolMetadata:C$.optional(),state:O.literal("output-denied"),providerExecuted:O.boolean().optional(),input:O.unknown(),output:O.never().optional(),errorText:O.never().optional(),callProviderMetadata:I.optional(),approval:O.object({id:O.string(),approved:O.literal(!1),reason:O.string().optional(),isAutomatic:O.boolean().optional(),signature:O.string().optional()})})]))}).superRefine(($,U)=>{if($.role!=="assistant"&&$.parts.length===0)U.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:$.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty")));var fP=V$({prefix:"call",size:24});var yP=V$({prefix:"call",size:24});var mP=V$({prefix:"aiobj",size:24});function LW($){return({url:U,abortSignal:z})=>jB({url:U,maxBytes:$==null?void 0:$.maxBytes,abortSignal:z})}var iP=V$({prefix:"aiobj",size:24});var lP=LW();var bB="AI_NoSuchProviderError",RB=`vercel.ai.error.${bB}`,IB=Symbol.for(RB),SB;SB=IB;var rP=V$({prefix:"call",size:24});var pP=LW();class n$ extends T4{name="ProviderResponseStreamError";constructor($,U){super({message:$,url:"",requestBodyValues:void 0,cause:U?.cause,isRetryable:!0})}}var Z$={};w6(Z$,{toWebSocketUrl:()=>dB,streamResponsesWebSocket:()=>sB,parseRateLimitSignal:()=>i1,normalizeHeaders:()=>oB,isUpgradeFailure:()=>tB,isAbortError:()=>GN,connectResponsesWebSocket:()=>aB,PROTOCOL_HEADER:()=>PW,OpenAIWebSocket:()=>Z$});function u1($){let U=Number($.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(U)?U:void 0}function P0($,U,z=!1){let J=Buffer.from($.slice(0,U)).toString("latin1").split(`\r
133
- `),j=J[0]??"",Y=u1(j);if(Y===void 0||Y===101)return;let N=Object.fromEntries(J.slice(1).flatMap((w)=>{let B=w.indexOf(":");return B===-1?[]:[[w.slice(0,B).trim().toLowerCase(),w.slice(B+1).trim()]]})),W=$.slice(U+4),G=N["content-length"],Q=Number(G);if(!z&&(G===void 0||Number.isFinite(Q)&&W.length<Q))return;let L=Buffer.from(W).toString("utf8"),H=(()=>{try{let w=JSON.parse(L);return k(w)?w:void 0}catch{return}})();return{message:`WS upgrade failed: ${j}`,status:Y,status_code:Y,headers:N,body:L,...k(H?.error)?{error:H.error}:{}}}var kB="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",BW=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class NN{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];writeQueue=[];constructor($,U,z){this.url=$,this.sessionID=z?.sessionID,this.connect($,U)}addEventListener($,U,z){this.listeners[$]?.add(U)}removeEventListener($,U){this.listeners[$]?.delete(U)}emit($,U){for(let z of[...this.listeners[$]??[]])try{z(U)}catch{}}async connect($,U){let z=new URL($.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),X=z.hostname,J=z.port?Number(z.port):z.protocol==="https:"?443:80,j=`${z.pathname}${z.search}`,Y=crypto.getRandomValues(new Uint8Array(16)),N=Buffer.from(Y).toString("base64"),W=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(N+kB));this.expectedAccept=Buffer.from(new Uint8Array(W)).toString("base64");let G={};for(let[H,w]of Object.entries(U))G[H.toLowerCase()]=w;let Q=[`GET ${j} HTTP/1.1`,`Host: ${X}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${N}`];for(let H of BW)if(G[H]!==void 0)Q.push(`${CB(H)}: ${G[H]}`);for(let[H,w]of Object.entries(U))if(!BW.includes(H.toLowerCase())&&H.toLowerCase()!=="content-length")Q.push(`${H}: ${w}`);let L=`${Q.join(`\r
145
+ `)}})}};var XY=z.record(z.string(),F1.optional()),IO=dY(()=>e1(z.union([z.looseObject({type:z.literal("text-start"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("text-end"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("error"),errorText:z.string()}),z.looseObject({type:z.literal("tool-input-start"),toolCallId:z.string(),toolName:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:XY.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-input-delta"),toolCallId:z.string(),inputTextDelta:z.string()}),z.looseObject({type:z.literal("tool-input-available"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:XY.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-input-error"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:XY.optional(),dynamic:z.boolean().optional(),errorText:z.string(),title:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}),z.looseObject({type:z.literal("tool-approval-response"),approvalId:z.string(),approved:z.boolean(),reason:z.string().optional(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:XY.optional(),dynamic:z.boolean().optional(),preliminary:z.boolean().optional()}),z.looseObject({type:z.literal("tool-output-error"),toolCallId:z.string(),errorText:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:A.optional(),toolMetadata:XY.optional(),dynamic:z.boolean().optional()}),z.looseObject({type:z.literal("tool-output-denied"),toolCallId:z.string()}),z.looseObject({type:z.literal("reasoning-start"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("custom"),kind:z.string().transform((Y)=>Y),providerMetadata:A.optional()}),z.looseObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.literal("reasoning-file"),url:z.string(),mediaType:z.string(),providerMetadata:A.optional()}),z.looseObject({type:z.custom((Y)=>typeof Y==="string"&&Y.startsWith("data-"),{message:'Type must start with "data-"'}),id:z.string().optional(),data:z.unknown(),transient:z.boolean().optional()}),z.looseObject({type:z.literal("start-step")}),z.looseObject({type:z.literal("finish-step")}),z.looseObject({type:z.literal("start"),messageId:z.string().optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("finish"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:z.unknown().optional()}),z.looseObject({type:z.literal("abort"),reason:z.string().optional()}),z.looseObject({type:z.literal("message-metadata"),messageMetadata:z.unknown()})])));var kO=J0({prefix:"aitxt",size:24}),bO=J0({prefix:"call",size:24});var xO=J0({prefix:"aitxt",size:24}),vO=J0({prefix:"call",size:24});var j0=z.record(z.string(),F1.optional()),DL=z.record(z.string(),z.string()),gO=dY(()=>e1(z.array(z.object({id:z.string(),role:z.enum(["system","user","assistant"]),metadata:z.unknown().optional(),parts:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),z.object({type:z.literal("reasoning"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:A.optional()}),z.object({type:z.literal("custom"),kind:z.string(),providerMetadata:A.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:A.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerReference:DL.optional(),providerMetadata:A.optional()}),z.object({type:z.literal("reasoning-file"),mediaType:z.string(),url:z.string(),providerMetadata:A.optional()}),z.object({type:z.literal("step-start")}),z.object({type:z.string().startsWith("data-"),id:z.string().optional(),data:z.unknown()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:A.optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-error"),input:z.unknown().optional(),rawInput:z.unknown().optional(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:A.optional(),input:z.unknown().optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-error"),providerExecuted:z.boolean().optional(),input:z.unknown().optional(),rawInput:z.unknown().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:A.optional(),resultProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:j0.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:A.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional(),isAutomatic:z.boolean().optional(),signature:z.string().optional()})})]))}).superRefine((Y,X)=>{if(Y.role!=="assistant"&&Y.parts.length===0)X.addIssue({origin:"array",code:"too_small",minimum:1,inclusive:!0,input:Y.parts,path:["parts"],message:"Message must contain at least one part"})})).nonempty("Messages array must not be empty")));var fO=J0({prefix:"call",size:24});var cO=J0({prefix:"call",size:24});var pO=J0({prefix:"aiobj",size:24});function VG(Y){return({url:X,abortSignal:J})=>eH({url:X,maxBytes:Y==null?void 0:Y.maxBytes,abortSignal:J})}var dO=J0({prefix:"aiobj",size:24});var iO=VG();var PL="AI_NoSuchProviderError",wL=`vercel.ai.error.${PL}`,EL=Symbol.for(wL),ML;ML=EL;var oO=J0({prefix:"call",size:24});var rO=VG();class R0 extends m1{name="ProviderResponseStreamError";constructor(Y,X){super({message:Y,url:"",requestBodyValues:void 0,cause:X?.cause,isRetryable:!0})}}var D0={};g8(D0,{toWebSocketUrl:()=>uL,streamResponsesWebSocket:()=>iL,parseRateLimitSignal:()=>$Y,normalizeHeaders:()=>pL,isUpgradeFailure:()=>lL,isAbortError:()=>I9,connectResponsesWebSocket:()=>dL,PROTOCOL_HEADER:()=>PG,OpenAIWebSocket:()=>D0});function QY(Y){let X=Number(Y.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1]);return Number.isFinite(X)?X:void 0}function rY(Y,X,J=!1){let $=Buffer.from(Y.slice(0,X)).toString("latin1").split(`\r
146
+ `),G=$[0]??"",W=QY(G);if(W===void 0||W===101)return;let K=Object.fromEntries($.slice(1).flatMap((L)=>{let Z=L.indexOf(":");return Z===-1?[]:[[L.slice(0,Z).trim().toLowerCase(),L.slice(Z+1).trim()]]})),H=Y.slice(X+4),U=K["content-length"],N=Number(U);if(!J&&(U===void 0||Number.isFinite(N)&&H.length<N))return;let O=Buffer.from(H).toString("utf8"),B=(()=>{try{let L=JSON.parse(O);return _(L)?L:void 0}catch{return}})();return{message:`WS upgrade failed: ${G}`,status:W,status_code:W,headers:K,body:O,..._(B?.error)?{error:B.error}:{}}}var AL="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",BG=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class T9{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];writeQueue=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),H=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+AL));this.expectedAccept=Buffer.from(new Uint8Array(H)).toString("base64");let U={};for(let[B,L]of Object.entries(X))U[B.toLowerCase()]=L;let N=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let B of BG)if(U[B]!==void 0)N.push(`${RL(B)}: ${U[B]}`);for(let[B,L]of Object.entries(X))if(!BG.includes(B.toLowerCase())&&B.toLowerCase()!=="content-length")N.push(`${B}: ${L}`);let O=`${N.join(`\r
134
147
  `)}\r
135
148
  \r
136
- `;try{this.log("connect_start",{host:X,port:J,tls:z.protocol==="https:"});let H=globalThis.Bun?.connect;if(!H)throw Error("Bun.connect is not available");this.socket=await H({hostname:X,port:J,tls:z.protocol==="https:"?{serverName:X}:void 0,socket:{open:(w)=>{this.socket=w,this.enqueueWrite(new TextEncoder().encode(L))},data:(w,B)=>this.onData(B),drain:()=>this.flushWrites(),error:(w,B)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let q=B instanceof Error?B.message:String(B);this.log("socket_error",{message:q}),this.emit("error",{message:q})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emit("close",{code:1006,reason:"socket closed"})}}})}catch(H){this.readyState=3;let w=H instanceof Error?H.message:String(H);this.log("connect_exception",{message:w}),this.emit("error",{message:w})}}onData($){if(this.rxBuffer=ZB(this.rxBuffer,$),!this.handshakeDone){let U=Buffer.from(this.rxBuffer).toString("latin1"),z=U.indexOf(`\r
149
+ `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let B=globalThis.Bun?.connect;if(!B)throw Error("Bun.connect is not available");this.socket=await B({hostname:Q,port:$,tls:J.protocol==="https:"?{serverName:Q}:void 0,socket:{open:(L)=>{this.socket=L,this.enqueueWrite(new TextEncoder().encode(O))},data:(L,Z)=>this.onData(Z),drain:()=>this.flushWrites(),error:(L,Z)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=Z instanceof Error?Z.message:String(Z);this.log("socket_error",{message:j}),this.emit("error",{message:j})},close:()=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close"),this.emit("close",{code:1006,reason:"socket closed"})}}})}catch(B){this.readyState=3;let L=B instanceof Error?B.message:String(B);this.log("connect_exception",{message:L}),this.emit("error",{message:L})}}onData(Y){if(this.rxBuffer=TL(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
137
150
  \r
138
- `);if(z===-1)return;let X=U.slice(0,z),J=X.split(`\r
139
- `)[0]??"",j=X.match(/sec-websocket-accept:\s*(\S+)/i),Y=u1(J);if(Y!==101){if(Y===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:J}),this.emit("error",{message:`WS upgrade failed: ${J}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!j||j[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:J}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(z+4),this.log("open",{statusLine:J}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade($=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let U=Buffer.from(this.rxBuffer).indexOf(`\r
151
+ `);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
152
+ `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=QY($);if(W!==101){if(W===void 0){this.readyState=3;try{this.socket?.end()}catch{}this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;try{this.socket?.end()}catch{}return}if(!G||G[1]!==this.expectedAccept){this.readyState=3;try{this.socket?.end()}catch{}this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
140
153
  \r
141
- `);if(U===-1)return!1;let z=P0(this.rxBuffer,U,$);if(!z)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:z.status,partial:$}),this.emit("error",z),!0}drainFrames(){for(;;){let $=this.rxBuffer;if($.length<2)return;let U=$[0],z=$[1],X=(U&128)!==0,J=U&15,j=(z&128)!==0,Y=z&127,N=2;if(Y===126){if($.length<4)return;Y=$[2]<<8|$[3],N=4}else if(Y===127){if($.length<10)return;Y=0;for(let G=0;G<8;G++)Y=Y*256+$[2+G];N=10}if(j)N+=4;if($.length<N+Y)return;let W=$.slice(N,N+Y);this.rxBuffer=$.slice(N+Y),this.handleFrame(X,J,W)}}handleFrame($,U,z){if(U===9){this.writeFrame(10,z);return}if(U===10)return;if(U===8){let J=1005,j="";if(z.length>=2)J=z[0]<<8|z[1],j=Buffer.from(z.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.log("close_frame",{code:J,reason:j}),this.emit("close",{code:J,reason:j});return}if(U===1||U===2)this.fragOpcode=U,this.fragChunks=[z];else if(U===0)this.fragChunks.push(z);if(!$)return;let X=TB(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let J=Buffer.from(X).toString("utf-8");this.emit("message",{data:J})}}send($){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode($))}writeFrame($,U){let z=U.length,X=crypto.getRandomValues(new Uint8Array(4)),J;if(z<126)J=[128|$,128|z];else if(z<65536)J=[128|$,254,z>>8&255,z&255];else{J=[128|$,255];for(let N=7;N>=0;N--)J.push(z/2**(8*N)&255)}let j=new Uint8Array(z);for(let N=0;N<z;N++)j[N]=U[N]^X[N%4];let Y=new Uint8Array(J.length+4+z);Y.set(J,0),Y.set(X,J.length),Y.set(j,J.length+4);try{this.enqueueWrite(Y)}catch{}}enqueueWrite($){this.writeQueue.push($),this.flushWrites()}flushWrites(){let $=this.socket;if(!$)return;while(this.writeQueue.length>0){let U=this.writeQueue[0],z=$.write(U);if(z<U.length){this.writeQueue[0]=U.slice(z),this.log("write_backpressure",{written:z,remaining:U.length-z});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log($,U){return G6({component:"raw-ws-bun",event:$,sessionID:this.sessionID,url:this.url,...U})}}function CB($){return $}function ZB($,U){let z=new Uint8Array($.length+U.length);return z.set($,0),z.set(U,$.length),z}function TB($){let U=0;for(let J of $)U+=J.length;let z=new Uint8Array(U),X=0;for(let J of $)z.set(J,X),X+=J.length;return z}import{connect as gB}from"node:net";import{connect as xB}from"node:tls";var fB="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",DW=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class ON{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor($,U,z){this.url=$,this.sessionID=z?.sessionID,this.connect($,U)}addEventListener($,U,z){this.listeners[$]?.add(U)}removeEventListener($,U){this.listeners[$]?.delete(U)}emit($,U){for(let z of[...this.listeners[$]??[]])try{z(U)}catch{}}async connect($,U){let z=new URL($.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),X=z.hostname,J=z.port?Number(z.port):z.protocol==="https:"?443:80,j=`${z.pathname}${z.search}`,Y=crypto.getRandomValues(new Uint8Array(16)),N=Buffer.from(Y).toString("base64"),W=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(N+fB));this.expectedAccept=Buffer.from(new Uint8Array(W)).toString("base64");let G={};for(let[H,w]of Object.entries(U))G[H.toLowerCase()]=w;let Q=[`GET ${j} HTTP/1.1`,`Host: ${X}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${N}`];for(let H of DW)if(G[H]!==void 0)Q.push(`${hB(H)}: ${G[H]}`);for(let[H,w]of Object.entries(U))if(!DW.includes(H.toLowerCase())&&H.toLowerCase()!=="content-length")Q.push(`${H}: ${w}`);let L=`${Q.join(`\r
154
+ `);if(X===-1)return!1;let J=rY(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];K=10}if(G)K+=4;if(Y.length<K+W)return;let H=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,H)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.log("close_frame",{code:$,reason:G}),this.emit("close",{code:$,reason:G});return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=CL(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let K=7;K>=0;K--)$.push(J/2**(8*K)&255)}let G=new Uint8Array(J);for(let K=0;K<J;K++)G[K]=X[K]^Q[K%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.enqueueWrite(W)}catch{}}enqueueWrite(Y){this.writeQueue.push(Y),this.flushWrites()}flushWrites(){let Y=this.socket;if(!Y)return;while(this.writeQueue.length>0){let X=this.writeQueue[0],J=Y.write(X);if(J<X.length){this.writeQueue[0]=X.slice(J),this.log("write_backpressure",{written:J,remaining:X.length-J});return}this.writeQueue.shift()}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return c0({component:"raw-ws-bun",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function RL(Y){return Y}function TL(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function CL(Y){let X=0;for(let $ of Y)X+=$.length;let J=new Uint8Array(X),Q=0;for(let $ of Y)J.set($,Q),Q+=$.length;return J}import{connect as _L}from"node:net";import{connect as IL}from"node:tls";var SL="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",ZG=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class C9{url;readyState=0;socket;sessionID;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;upgradeFailureEmitted=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor(Y,X,J){this.url=Y,this.sessionID=J?.sessionID,this.connect(Y,X)}addEventListener(Y,X,J){this.listeners[Y]?.add(X)}removeEventListener(Y,X){this.listeners[Y]?.delete(X)}emit(Y,X){for(let J of[...this.listeners[Y]??[]])try{J(X)}catch{}}async connect(Y,X){let J=new URL(Y.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),Q=J.hostname,$=J.port?Number(J.port):J.protocol==="https:"?443:80,G=`${J.pathname}${J.search}`,W=crypto.getRandomValues(new Uint8Array(16)),K=Buffer.from(W).toString("base64"),H=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(K+SL));this.expectedAccept=Buffer.from(new Uint8Array(H)).toString("base64");let U={};for(let[B,L]of Object.entries(X))U[B.toLowerCase()]=L;let N=[`GET ${G} HTTP/1.1`,`Host: ${Q}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${K}`];for(let B of ZG)if(U[B]!==void 0)N.push(`${kL(B)}: ${U[B]}`);for(let[B,L]of Object.entries(X))if(!ZG.includes(B.toLowerCase())&&B.toLowerCase()!=="content-length")N.push(`${B}: ${L}`);let O=`${N.join(`\r
142
155
  `)}\r
143
156
  \r
144
- `;try{this.log("connect_start",{host:X,port:J,tls:z.protocol==="https:"});let H=()=>{this.socket?.write(L)},w=z.protocol==="https:"?xB({host:X,port:J,servername:X},H):gB({host:X,port:J},H);this.socket=w,w.on("data",(B)=>{this.onData(typeof B==="string"?Buffer.from(B,"binary"):B)}),w.on("error",(B)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let q=B instanceof Error?B.message:String(B);this.log("socket_error",{message:q}),this.emit("error",{message:q})}),w.on("close",(B)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:B}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(H){this.readyState=3,this.log("connect_exception",{message:H instanceof Error?H.message:String(H)}),this.emit("error",{message:H instanceof Error?H.message:String(H)})}}onData($){if(this.rxBuffer=yB(this.rxBuffer,$),!this.handshakeDone){let U=Buffer.from(this.rxBuffer).toString("latin1"),z=U.indexOf(`\r
157
+ `;try{this.log("connect_start",{host:Q,port:$,tls:J.protocol==="https:"});let B=()=>{this.socket?.write(O)},L=J.protocol==="https:"?IL({host:Q,port:$,servername:Q},B):_L({host:Q,port:$},B);this.socket=L,L.on("data",(Z)=>{this.onData(typeof Z==="string"?Buffer.from(Z,"binary"):Z)}),L.on("error",(Z)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3;let j=Z instanceof Error?Z.message:String(Z);this.log("socket_error",{message:j}),this.emit("error",{message:j})}),L.on("close",(Z)=>{if(this.emitRejectedUpgrade(!0))return;this.readyState=3,this.log("socket_close",{hadError:Z}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(B){this.readyState=3,this.log("connect_exception",{message:B instanceof Error?B.message:String(B)}),this.emit("error",{message:B instanceof Error?B.message:String(B)})}}onData(Y){if(this.rxBuffer=bL(this.rxBuffer,Y),!this.handshakeDone){let X=Buffer.from(this.rxBuffer).toString("latin1"),J=X.indexOf(`\r
145
158
  \r
146
- `);if(z===-1)return;let X=U.slice(0,z),J=X.split(`\r
147
- `)[0]??"",j=X.match(/sec-websocket-accept:\s*(\S+)/i),Y=u1(J);if(Y!==101){if(Y===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:J}),this.emit("error",{message:`WS upgrade failed: ${J}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!j||j[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:J}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(z+4),this.log("open",{statusLine:J}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade($=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let U=Buffer.from(this.rxBuffer).indexOf(`\r
159
+ `);if(J===-1)return;let Q=X.slice(0,J),$=Q.split(`\r
160
+ `)[0]??"",G=Q.match(/sec-websocket-accept:\s*(\S+)/i),W=QY($);if(W!==101){if(W===void 0){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:$}),this.emit("error",{message:`WS upgrade failed: ${$}`});return}if(!this.emitRejectedUpgrade())return;this.socket?.destroy?.();return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:$}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(J+4),this.log("open",{statusLine:$}),this.emit("open",{})}this.drainFrames()}emitRejectedUpgrade(Y=!1){if(this.upgradeFailureEmitted)return!0;if(this.handshakeDone)return!1;let X=Buffer.from(this.rxBuffer).indexOf(`\r
148
161
  \r
149
- `);if(U===-1)return!1;let z=P0(this.rxBuffer,U,$);if(!z)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:z.status,partial:$}),this.emit("error",z),!0}drainFrames(){for(;;){let $=this.rxBuffer;if($.length<2)return;let U=$[0],z=$[1],X=(U&128)!==0,J=U&15,j=(z&128)!==0,Y=z&127,N=2;if(Y===126){if($.length<4)return;Y=$[2]<<8|$[3],N=4}else if(Y===127){if($.length<10)return;Y=0;for(let G=0;G<8;G++)Y=Y*256+$[2+G];N=10}if(j)N+=4;if($.length<N+Y)return;let W=$.slice(N,N+Y);this.rxBuffer=$.slice(N+Y),this.handleFrame(X,J,W)}}handleFrame($,U,z){if(U===9){this.writeFrame(10,z);return}if(U===10)return;if(U===8){let J=1005,j="";if(z.length>=2)J=z[0]<<8|z[1],j=Buffer.from(z.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:J,reason:j});return}if(U===1||U===2)this.fragOpcode=U,this.fragChunks=[z];else if(U===0)this.fragChunks.push(z);if(!$)return;let X=cB(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let J=Buffer.from(X).toString("utf-8");this.emit("message",{data:J})}}send($){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode($))}writeFrame($,U){let z=U.length,X=crypto.getRandomValues(new Uint8Array(4)),J;if(z<126)J=[128|$,128|z];else if(z<65536)J=[128|$,254,z>>8&255,z&255];else{J=[128|$,255];for(let N=7;N>=0;N--)J.push(z/2**(8*N)&255)}let j=new Uint8Array(z);for(let N=0;N<z;N++)j[N]=U[N]^X[N%4];let Y=new Uint8Array(J.length+4+z);Y.set(J,0),Y.set(X,J.length),Y.set(j,J.length+4);try{this.socket?.write(Y)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log($,U){return G6({component:"raw-ws-node",event:$,sessionID:this.sessionID,url:this.url,...U})}}function hB($){return $}function yB($,U){let z=new Uint8Array($.length+U.length);return z.set($,0),z.set(U,$.length),z}function cB($){let U=0;for(let J of $)U+=J.length;let z=new Uint8Array(U),X=0;for(let J of $)z.set(J,X),X+=J.length;return z}function mB(){return typeof globalThis.Bun?.connect==="function"}var KW=mB()?NN:ON;function A0($){return process.env[$]??process.env[$.toLowerCase()]}function uB($){let U=A0("NO_PROXY");if(!U)return!1;let z=$.hostname.toLowerCase(),X=U.split(",").map((J)=>J.trim().toLowerCase()).filter(Boolean);for(let J of X){if(J==="*")return!0;if(J.startsWith(".")){if(z===J.slice(1)||z.endsWith(J))return!0}else if(z===J||z.endsWith(`.${J}`))return!0}return!1}function iB($){let U=new URL($);if(uB(U))return;if(U.protocol==="http:")return A0("HTTP_PROXY");if(U.protocol==="https:")return A0("HTTPS_PROXY")??A0("HTTP_PROXY");return}var qW={getProxyForUrl:iB};var lB=q$("quota"),PW="responses_websockets=2026-02-06",_W=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"],nB=new Set([E6,"x-opencode-title"]);function rB($){let U=new Map;for(let X of Object.keys($))U.set(X.toLowerCase(),X);let z={};for(let X of _W){let J=U.get(X),j=J===void 0?void 0:$[J];if(J!==void 0&&j!==void 0)z[J]=j}for(let[X,J]of Object.entries($))if(!_W.includes(X.toLowerCase()))z[X]=J;return z}function pB($){let U={};for(let[z,X]of Object.entries($)){if(nB.has(z.toLowerCase()))continue;U[z]=X}return U}function dB($){return $.replace(/^http/,"ws")}function oB($){let U={};if(!$)return U;if($ instanceof Headers)return $.forEach((z,X)=>{U[X.toLowerCase()]=z}),U;if(Array.isArray($)){for(let[z,X]of $)U[z.toLowerCase()]=X;return U}for(let[z,X]of Object.entries($))if(X!=null)U[z.toLowerCase()]=String(X);return U}function GN($){return $ instanceof DOMException&&$.name==="AbortError"}var AW=new WeakSet;function tB($){return typeof $==="object"&&$!==null&&AW.has($)}function vW($,U){let z=Error($,U===void 0?void 0:{cause:U});return AW.add(z),z}function aB($){return new Promise((U,z)=>{if($.signal?.aborted){z(WN($.signal));return}let X={...$.headers,"openai-beta":$.headers["openai-beta"]??PW},J=X[E6]??X["session-id"];delete X["content-length"],X=rB(pB(X));let j=typeof Bun>"u"?void 0:qW.getProxyForUrl($.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),Y=!0,N=$.rawWebSocket?new KW($.url,X,{sessionID:J}):new globalThis.WebSocket($.url,{headers:X,...j?{proxy:j}:{},perMessageDeflate:Y}),W=$.timeout?setTimeout(()=>{G(),N.close(),z(Error("WebSocket connect timed out"))},$.timeout):void 0;function G(){if(W)clearTimeout(W);N.removeEventListener("open",Q),N.removeEventListener("error",L),N.removeEventListener("close",H),$.signal?.removeEventListener("abort",w)}function Q(){G(),U(N)}function L(B){G(),z(vW(A6(B),B))}function H(B){G(),z(vW(MW("WebSocket closed before open",B.code,B.reason)))}function w(){G(),N.close(),z(WN($.signal))}N.addEventListener("open",Q,{once:!0}),N.addEventListener("error",L,{once:!0}),N.addEventListener("close",H,{once:!0}),$.signal?.addEventListener("abort",w,{once:!0})})}function sB($){let U=new TextEncoder,z=$.socket,X,J=()=>{},j=!1,Y=!1,N,W=new Set;function G(){if(N)clearTimeout(N);J(),$.signal?.removeEventListener("abort",b)}function Q(Z=z){Z.close()}function L(){G(),X?.enqueue(U.encode(`data: [DONE]
162
+ `);if(X===-1)return!1;let J=rY(this.rxBuffer,X,Y);if(!J)return!1;return this.upgradeFailureEmitted=!0,this.readyState=3,this.log("upgrade_failed",{status:J.status,partial:Y}),this.emit("error",J),!0}drainFrames(){for(;;){let Y=this.rxBuffer;if(Y.length<2)return;let X=Y[0],J=Y[1],Q=(X&128)!==0,$=X&15,G=(J&128)!==0,W=J&127,K=2;if(W===126){if(Y.length<4)return;W=Y[2]<<8|Y[3],K=4}else if(W===127){if(Y.length<10)return;W=0;for(let U=0;U<8;U++)W=W*256+Y[2+U];K=10}if(G)K+=4;if(Y.length<K+W)return;let H=Y.slice(K,K+W);this.rxBuffer=Y.slice(K+W),this.handleFrame(Q,$,H)}}handleFrame(Y,X,J){if(X===9){this.writeFrame(10,J);return}if(X===10)return;if(X===8){let $=1005,G="";if(J.length>=2)$=J[0]<<8|J[1],G=Buffer.from(J.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:$,reason:G});return}if(X===1||X===2)this.fragOpcode=X,this.fragChunks=[J];else if(X===0)this.fragChunks.push(J);if(!Y)return;let Q=xL(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let $=Buffer.from(Q).toString("utf-8");this.emit("message",{data:$})}}send(Y){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode(Y))}writeFrame(Y,X){let J=X.length,Q=crypto.getRandomValues(new Uint8Array(4)),$;if(J<126)$=[128|Y,128|J];else if(J<65536)$=[128|Y,254,J>>8&255,J&255];else{$=[128|Y,255];for(let K=7;K>=0;K--)$.push(J/2**(8*K)&255)}let G=new Uint8Array(J);for(let K=0;K<J;K++)G[K]=X[K]^Q[K%4];let W=new Uint8Array($.length+4+J);W.set($,0),W.set(Q,$.length),W.set(G,$.length+4);try{this.socket?.write(W)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log(Y,X){return c0({component:"raw-ws-node",event:Y,sessionID:this.sessionID,url:this.url,...X})}}function kL(Y){return Y}function bL(Y,X){let J=new Uint8Array(Y.length+X.length);return J.set(Y,0),J.set(X,Y.length),J}function xL(Y){let X=0;for(let $ of Y)X+=$.length;let J=new Uint8Array(X),Q=0;for(let $ of Y)J.set($,Q),Q+=$.length;return J}function vL(){return typeof globalThis.Bun?.connect==="function"}var OG=vL()?T9:C9;function sY(Y){return process.env[Y]??process.env[Y.toLowerCase()]}function hL(Y){let X=sY("NO_PROXY");if(!X)return!1;let J=Y.hostname.toLowerCase(),Q=X.split(",").map(($)=>$.trim().toLowerCase()).filter(Boolean);for(let $ of Q){if($==="*")return!0;if($.startsWith(".")){if(J===$.slice(1)||J.endsWith($))return!0}else if(J===$||J.endsWith(`.${$}`))return!0}return!1}function gL(Y){let X=new URL(Y);if(hL(X))return;if(X.protocol==="http:")return sY("HTTP_PROXY");if(X.protocol==="https:")return sY("HTTPS_PROXY")??sY("HTTP_PROXY");return}var FG={getProxyForUrl:gL};var yL=L0("quota"),PG="responses_websockets=2026-02-06",qG=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"],fL=new Set([r0,"x-opencode-title"]);function mL(Y){let X=new Map;for(let Q of Object.keys(Y))X.set(Q.toLowerCase(),Q);let J={};for(let Q of qG){let $=X.get(Q),G=$===void 0?void 0:Y[$];if($!==void 0&&G!==void 0)J[$]=G}for(let[Q,$]of Object.entries(Y))if(!qG.includes(Q.toLowerCase()))J[Q]=$;return J}function cL(Y){let X={};for(let[J,Q]of Object.entries(Y)){if(fL.has(J.toLowerCase()))continue;X[J]=Q}return X}function uL(Y){return Y.replace(/^http/,"ws")}function pL(Y){let X={};if(!Y)return X;if(Y instanceof Headers)return Y.forEach((J,Q)=>{X[Q.toLowerCase()]=J}),X;if(Array.isArray(Y)){for(let[J,Q]of Y)X[J.toLowerCase()]=Q;return X}for(let[J,Q]of Object.entries(Y))if(Q!=null)X[J.toLowerCase()]=String(Q);return X}function I9(Y){return Y instanceof DOMException&&Y.name==="AbortError"}var wG=new WeakSet;function lL(Y){return typeof Y==="object"&&Y!==null&&wG.has(Y)}function jG(Y,X){let J=Error(Y,X===void 0?void 0:{cause:X});return wG.add(J),J}function dL(Y){return new Promise((X,J)=>{if(Y.signal?.aborted){J(_9(Y.signal));return}let Q={...Y.headers,"openai-beta":Y.headers["openai-beta"]??PG},$=Q[r0]??Q["session-id"];delete Q["content-length"],Q=mL(cL(Q));let G=typeof Bun>"u"?void 0:FG.getProxyForUrl(Y.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:")),W=!0,K=Y.rawWebSocket?new OG(Y.url,Q,{sessionID:$}):new globalThis.WebSocket(Y.url,{headers:Q,...G?{proxy:G}:{},perMessageDeflate:W}),H=Y.timeout?setTimeout(()=>{U(),K.close(),J(Error("WebSocket connect timed out"))},Y.timeout):void 0;function U(){if(H)clearTimeout(H);K.removeEventListener("open",N),K.removeEventListener("error",O),K.removeEventListener("close",B),Y.signal?.removeEventListener("abort",L)}function N(){U(),X(K)}function O(Z){U(),J(jG(o0(Z),Z))}function B(Z){U(),J(jG(MG("WebSocket closed before open",Z.code,Z.reason)))}function L(){U(),K.close(),J(_9(Y.signal))}K.addEventListener("open",N,{once:!0}),K.addEventListener("error",O,{once:!0}),K.addEventListener("close",B,{once:!0}),Y.signal?.addEventListener("abort",L,{once:!0})})}function iL(Y){let X=new TextEncoder,J=Y.socket,Q,$=()=>{},G=!1,W=!1,K,H=new Set;function U(){if(K)clearTimeout(K);$(),Y.signal?.removeEventListener("abort",P)}function N(S=J){S.close()}function O(){U(),Q?.enqueue(X.encode(`data: [DONE]
150
163
 
151
- `)),X?.close()}function H(Z){if(j)return;j=!0,G(),$.onConnectionInvalid?.(Z),X?.error(Z)}function w(Z){if(j)return;if(!$.idleTimeout)return;if(N)clearTimeout(N);N=setTimeout(()=>H(new n$(Z)),$.idleTimeout)}async function B(Z){if(j)return;if(typeof Z.data!=="string"){H(new n$("Unexpected binary WebSocket frame"));return}let N$=Z.data,r=(()=>{try{let X$=JSON.parse(N$);return typeof X$==="object"&&X$!==null?X$:void 0}catch{return}})();if(r?.type==="codex.rate_limits"){lB.debug("codex.rate_limits frame received",{pid:process.pid}),w("idle timeout waiting for websocket");let X$=FW(r);$.onQuota?.(X$);return}let e=!Y?i1(r):void 0;if(e&&r){j=!0,G(),$.onRateLimitReached?.(e.window,e.resetAt),$.onTerminal?.(r),$.onFirstEvent?.(),X?.error(new n$(`OpenAI account rate limit reached at admission (${e.window})`));return}if(r?.type==="error"&&$.onRetryableTerminal){if(J(),N)clearTimeout(N);N=void 0;try{let X$=await $.onRetryableTerminal(r);if(j){if(X$)Q(X$);return}if(X$){y(X$);return}}catch(X$){H(new n$(X$ instanceof Error?X$.message:String(X$),{cause:X$}));return}}let v$=zD(r,N$);if(v$&&r){if(!Y)$.onFirstEvent?.(v$);j=!0,G(),$.onTerminal?.(r),X?.error(new T4({message:v$.message,url:z.url,requestBodyValues:$.body,statusCode:v$.status,responseHeaders:v$.headers,responseBody:v$.body}));return}if(k(r)&&r.type==="response.failed"){let X$=k(r.response)?r.response.failed:void 0,j6=k(X$)?X$.rate_limit_reached_type:void 0;if(typeof j6==="string"){if(j=!0,G(),$.onRateLimitReached?.(j6),$.onTerminal?.(r),!Y)$.onFirstEvent?.(),X?.error(new n$(`OpenAI account rate limit reached mid-stream (${j6})`));else L();return}}if(r)eB(r,$.sessionID),UD(r,W);let Q$=r?$J(r):r;if(!Q$){if(!Y)$.onFirstEvent?.();w("idle timeout waiting for websocket");return}let c$=Q$===r?N$:JSON.stringify(Q$);if(!Y)$.onFirstEvent?.();if(X?.enqueue(U.encode(`${c$.split(/\r?\n/).map((X$)=>`data: ${X$}`).join(`
164
+ `)),Q?.close()}function B(S){if(G)return;G=!0,U(),Y.onConnectionInvalid?.(S),Q?.error(S)}function L(S){if(G)return;if(!Y.idleTimeout)return;if(K)clearTimeout(K);K=setTimeout(()=>B(new R0(S)),Y.idleTimeout)}async function Z(S){if(G)return;if(typeof S.data!=="string"){B(new R0("Unexpected binary WebSocket frame"));return}let d=S.data,m=(()=>{try{let u=JSON.parse(d);return typeof u==="object"&&u!==null?u:void 0}catch{return}})();if(m?.type==="codex.rate_limits"){yL.debug("codex.rate_limits frame received",{pid:process.pid}),L("idle timeout waiting for websocket");let u=DG(m);Y.onQuota?.(u);return}let e=!W?$Y(m):void 0;if(e&&m){G=!0,U(),Y.onRateLimitReached?.(e.window,e.resetAt),Y.onTerminal?.(m),Y.onFirstEvent?.(),Q?.error(new R0(`OpenAI account rate limit reached at admission (${e.window})`));return}if(m?.type==="error"&&Y.onRetryableTerminal){if($(),K)clearTimeout(K);K=void 0;try{let u=await Y.onRetryableTerminal(m);if(G){if(u)N(u);return}if(u){x(u);return}}catch(u){B(new R0(u instanceof Error?u.message:String(u),{cause:u}));return}}let y=aL(m,d);if(y&&m){if(!W)Y.onFirstEvent?.(y);G=!0,U(),Y.onTerminal?.(m),Q?.error(new m1({message:y.message,url:J.url,requestBodyValues:Y.body,statusCode:y.status,responseHeaders:y.headers,responseBody:y.body}));return}if(_(m)&&m.type==="response.failed"){let u=_(m.response)?m.response.failed:void 0,g0=_(u)?u.rate_limit_reached_type:void 0;if(typeof g0==="string"){if(G=!0,U(),Y.onRateLimitReached?.(g0),Y.onTerminal?.(m),!W)Y.onFirstEvent?.(),Q?.error(new R0(`OpenAI account rate limit reached mid-stream (${g0})`));else O();return}}if(m)nL(m,Y.sessionID),rL(m,H);let s=m?I8(m):m;if(!s){if(!W)Y.onFirstEvent?.();L("idle timeout waiting for websocket");return}let j1=s===m?d:JSON.stringify(s);if(!W)Y.onFirstEvent?.();if(Q?.enqueue(X.encode(`${j1.split(/\r?\n/).map((u)=>`data: ${u}`).join(`
152
165
  `)}
153
166
 
154
- `)),Y=!0,w("idle timeout waiting for websocket"),!Q$)return;if(Q$.type==="response.completed"||Q$.type==="response.done"){j=!0,JD(Q$,W),$.onComplete?.(Q$,W),$.onTerminal?.(Q$),L();return}if(Q$.type==="response.failed"||Q$.type==="response.incomplete"||Q$.type==="error")j=!0,$.onTerminal?.(Q$),L()}function q(Z){H(new n$(A6(Z),{cause:Z}))}function T(Z){if(j)return;H(new n$(MW("WebSocket closed before response.completed",Z.code,Z.reason)))}function b(){let Z=WN($.signal);if(j)return;j=!0,G(),Q(),$.onAbort?.(Z),X?.error(Z)}function g(Z){if(j)return;j=!0,G(),Q(),$.onAbort?.(XD(Z))}function y(Z){J(),z=Z,z.addEventListener("message",B),z.addEventListener("error",q,{once:!0}),z.addEventListener("close",T,{once:!0}),J=()=>{z.removeEventListener("message",B),z.removeEventListener("error",q),z.removeEventListener("close",T)};let{background:N$,...r}=$.body;w("idle timeout sending websocket request");try{z.send(JSON.stringify({type:"response.create",...r})),w("idle timeout waiting for websocket")}catch(e){if(j)return;H(new n$(e instanceof Error?e.message:String(e),{cause:e}))}}return new Response(new ReadableStream({start(Z){if(X=Z,$.signal?.addEventListener("abort",b,{once:!0}),$.signal?.aborted){b();return}y(z)},cancel(Z){g(Z)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function eB($,U){if(!$D($))return;await G6({component:"ws",event:"provider_native_web_search_event",sessionID:U,serverEventType:$.type,itemType:k($.item)?$.item.type:void 0,serverEvent:$})}function $D($){if(typeof $.type==="string"&&($.type.startsWith("response.web_search_call.")||$.type.startsWith("response.web_search_preview_call.")))return!0;if(k($.item)&&typeof $.item.type==="string")return $.item.type==="web_search_call"||$.item.type==="web_search_preview_call";return!1}function UD($,U){if($.type!=="response.output_item.done")return;if(!k($.item))return;EW($.item,U)}function JD($,U){let z=$.response;if(!k(z)||!Array.isArray(z.output))return;for(let X of z.output)if(k(X))EW(X,U)}function EW($,U){if($.type!=="function_call"&&$.type!=="custom_tool_call")return;let z=typeof $.call_id==="string"?$.call_id:typeof $.id==="string"?$.id:void 0;if(z)U.add(z)}function zD($,U){if($?.type!=="error")return;let z=$.status??$.status_code;if(typeof z!=="number"||z>=200&&z<300)return;return{status:z,headers:k($.headers)?Object.fromEntries(Object.entries($.headers).flatMap(([X,J])=>typeof J==="string"||typeof J==="number"||typeof J==="boolean"?[[X,String(J)]]:[])):void 0,body:U,message:k($.error)&&typeof $.error.message==="string"?$.error.message:`${z}`}}function i1($){if(typeof $==="string")try{return i1(JSON.parse($))}catch{return}if(!k($))return;let U=i1($.cause);if(U)return U;let z=i1($.body);if(z)return z;let X=k($.error)?$.error:$,J=typeof X.type==="string"?X.type:void 0,j=$.status??$.status_code;if(J!=="usage_limit_reached"&&j!==429)return;let{resets_at:Y,resets_in_seconds:N}=X,W=typeof Y==="number"&&Number.isFinite(Y)&&Y>0?Y*1000:typeof N==="number"&&Number.isFinite(N)&&N>0?Date.now()+N*1000:void 0;return{window:J??"primary",resetAt:W}}function XD($){if(GN($))return $;if($ instanceof Error)return $;return new DOMException(typeof $==="string"?$:"Aborted","AbortError")}function WN($){let U=$?.reason;if(GN(U))return U;if(jD(U))return U;return new DOMException(U instanceof Error?U.message:"Aborted","AbortError")}function jD($){return $ instanceof Error&&($.name==="ProviderHeaderTimeoutError"||$.name==="ProviderResponseStreamError")}function MW($,U,z){let X=[`code ${U}`];if(U===1009)X.push("message too big");if(z.length>0)X.push(z.toString());return`${$} (${X.join(": ")})`}var wN="x-opencode-title",E0="x-openai-auth-quota-account",QN=new Set([wN,E6,E0,"x-opencode-session"]),ND=15000,OD=300000,WD=3300000,bW="websocket_connection_limit_reached";function GD($){let U=typeof $.authorization==="string"&&$.authorization.startsWith("Bearer ")?$.authorization.slice(7):"",z=typeof $["chatgpt-account-id"]==="string"?$["chatgpt-account-id"]:"";return YD("sha256").update(`${U}:${z}`).digest("hex").slice(0,12)}function QD($){let U=$?.httpFetch??globalThis.fetch,z=new Map,X=$?.connectTimeout??ND,J=$?.idleTimeout??OD,j=$?.maxConnectionAge??WD,Y=$?.streamRetries??5,N=$?.firstEventGraceMs??250,W=$?.rawWebSocket??!1,G=$?.onQuota,Q=$?.onRateLimitReached,L=setInterval(()=>B(),Math.min(J,60000));if(typeof L==="object"&&"unref"in L&&typeof L.unref==="function")L.unref();async function H(b,g){let y=b instanceof URL?b.toString():typeof b==="string"?b:b.url,Z=Z$.normalizeHeaders(g?.headers),N$=xW(g),r=e1(N$);if(g?.method!=="POST"||!new URL(y).pathname.endsWith("/responses"))return U(b,r);let e=(()=>{try{if(typeof g?.body!=="string")return;let O$=JSON.parse(g.body);return typeof O$==="object"&&O$!==null?O$:void 0}catch{return}})();if(!e?.stream)return U(b,r);if(Z[wN]==="true")return U(b,r);let v$=Z[E6]??Z["x-session-affinity"]??Z["session-id"],Q$=v$;if(!v$)return U(b,r);let c$=Z$.normalizeHeaders(N$?.headers),X$=GD(c$),j6=`${v$}:${X$}:conversation`,k4=typeof Z[E0]==="string"?Z[E0]:void 0,U4=Q?(O$,F$)=>Q(O$,k4,F$):void 0,f=z.get(j6)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(z.set(j6,f),f.fallback)return U(b,r);if(f.busy)return U(b,r);f.busy=!0,f.lastUsedAt=Date.now();try{let O$=vD(e),F$=Z$.normalizeHeaders(N$?.headers),J4=typeof F$.authorization==="string"&&F$.authorization.startsWith("Bearer ")?F$.authorization.slice(7):"",r1=typeof F$["chatgpt-account-id"]==="string"?F$["chatgpt-account-id"]:void 0,p1=G?(w$)=>G(w$,J4,k4,r1):void 0,z4=!f.socket&&!f.continuation?_D(F$):F$;if(f.socket=await LD(f,$?.url??y,z4,X,j,W,g?.signal),ED(f,O$))await BD(f,O$,J,{signal:g?.signal??void 0,sessionID:Q$,url:$?.url??y,headers:N$?.headers,onRateLimitReached:U4});let a$=()=>{},y6=()=>{},k0=new Promise((w$,N6)=>{a$=w$,y6=N6}),c6=AD(f,O$),Y6=l1(ZW(f,c6,O$)),m6=typeof Y6.previous_response_id==="string";await Y4({sessionID:Q$,transport:"websocket",phase:"main",bodyText:JSON.stringify(Y6),url:$?.url??y,method:N$?.method,headers:N$?.headers});let d1=Z$.streamResponsesWebSocket({socket:f.socket,body:Y6,sessionID:Q$??void 0,idleTimeout:J,signal:g?.signal??void 0,onQuota:p1,onRateLimitReached:U4,onFirstEvent:(w$)=>a$(w$??!0),onComplete:(w$,N6)=>{let C0=IW(w$);G6({component:"ws-pool",event:"main_completed",sessionID:Q$,responseID:RW(w$),usage:C0}),CW(f,O$,w$,N6,m6)},onTerminal:(w$)=>{if(f.busy=!1,f.lastUsedAt=Date.now(),f.streamFailures=0,w$.type!=="response.completed"&&w$.type!=="response.done")f.continuation=void 0,P6(f)},onConnectionInvalid:()=>{if(f.busy=!1,f.lastUsedAt=Date.now(),!f.fallback)w(f);f.continuation=void 0,P6(f),a$(!1)},onAbort:(w$)=>{f.busy=!1,f.lastUsedAt=Date.now(),f.streamFailures=0,f.continuation=void 0,P6(f),y6(w$)},onRetryableTerminal:async(w$)=>{let N6=wD(w$);if(!N6)return;throw f.fallback=!0,N6}}),p$=await HD(k0,N);if(p$!==!1){if(p$===!0||p$.status<200||p$.status>599)return d1;return new Response(p$.body,{status:p$.status,headers:{"content-type":"application/json",...p$.headers}})}if(!f.fallback)return d1;return U(b,r)}catch(O$){if(f.busy=!1,f.lastUsedAt=Date.now(),Z$.isAbortError(O$))throw f.streamFailures=0,f.continuation=void 0,P6(f),O$;let F$=Z$.parseRateLimitSignal(O$);if(F$)U4?.(F$.window,F$.resetAt);if(Z$.isUpgradeFailure(O$)&&!W)f.fallback=!0;if(w(f),f.continuation=void 0,P6(f),f.fallback)return U(b,r);return VD(new n$(O$ instanceof Error?O$.message:String(O$),{cause:O$}))}}function w(b){if(b.streamFailures++,b.streamFailures>Y)b.fallback=!0}function B(){let b=Date.now();for(let[g,y]of z){if(y.busy)continue;if(b-y.lastUsedAt<J)continue;P6(y),z.delete(g)}}function q(){clearInterval(L);for(let b of z.values())P6(b);z.clear()}function T(b){let g=`${b}:`;for(let[y,Z]of z){if(!y.startsWith(g))continue;P6(Z),z.delete(y)}}return Object.assign(H,{close:q,remove:T})}function wD($){if($.type!=="error"||!k($.error)||$.error.code!==bW)return;return Error(typeof $.error.message==="string"?$.error.message:bW)}async function HD($,U){if(U<=0)return!1;return new Promise((z,X)=>{let J=setTimeout(()=>z(!1),U);$.then((j)=>{clearTimeout(J),z(j)},(j)=>{clearTimeout(J),X(j)})})}function VD($){return new Response(new ReadableStream({start(U){U.error($)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function LD($,U,z,X,J,j,Y){if($.socket?.readyState===WebSocket.OPEN&&$.connectedAt&&Date.now()-$.connectedAt<J)return $.socket;P6($);let N=await Z$.connectResponsesWebSocket({url:Z$.toWebSocketUrl(U),headers:z,timeout:X,rawWebSocket:j,signal:Y??void 0});return $.connectedAt=Date.now(),N}function P6($){if($.socket)$.socket.close(),$.socket=void 0;$.connectedAt=void 0,$.continuation=void 0}async function BD($,U,z,X){if(!$.socket||!Array.isArray(U.input)||U.input.length===0)return;let J=KD(U);await Y4({sessionID:X.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify(J),url:X.url,method:"POST",headers:X.headers});let j=Z$.streamResponsesWebSocket({socket:$.socket,body:J,sessionID:X.sessionID,idleTimeout:z,signal:X.signal,onRateLimitReached:X.onRateLimitReached,onComplete:(Y,N)=>{G6({component:"ws-pool",event:"prewarm_completed",sessionID:X.sessionID,responseID:RW(Y),usage:IW(Y)}),CW($,J,Y,N,!1)},onTerminal:(Y)=>{if(Y.type!=="response.completed"&&Y.type!=="response.done")$.continuation=void 0},onConnectionInvalid:()=>{$.continuation=void 0},onAbort:()=>{$.continuation=void 0}});await DD(j)}function RW($){let U=$.response;if(!k(U))return;return typeof U.id==="string"?U.id:void 0}function IW($){let U=$.response;if(!k(U))return;return k(U.usage)?U.usage:void 0}async function DD($){let U=$.body?.getReader();if(!U)return;while(!0)if((await U.read()).done)return}function KD($){return l1({...$,generate:!1,input:[],previous_response_id:void 0,client_metadata:qD($.client_metadata)})}function SW($){return JSON.stringify({session_id:$.session_id,thread_id:$.thread_id,thread_source:$.thread_source,turn_id:"",sandbox:$.sandbox,request_kind:"prewarm",window_id:$.window_id})}function qD($){if(!k($))return $;if(typeof $["x-codex-turn-metadata"]!=="string")return $;try{let U=JSON.parse($["x-codex-turn-metadata"]);if(!k(U))return $;return{...$,"x-codex-turn-metadata":SW(U),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return $}}function _D($){let U=$["x-codex-turn-metadata"];if(!U)return $;try{let z=JSON.parse(U);if(!k(z))return $;return{...$,"x-codex-turn-metadata":SW(z)}}catch{return $}}var kW=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function vD($){let U={...$};if(Array.isArray($.input))U.input=$.input.map(FD);return U}function l1($){let U={};for(let z of kW)if(z in $)U[z]=$[z];for(let z of Object.keys($))if(!(z in U))U[z]=$[z];return U}function FD($){if(!k($))return $;if(typeof $.type==="string")return $;if(typeof $.role!=="string")return $;if(!("content"in $))return $;return{...$,type:"message"}}function CW($,U,z,X,J){let j=z.response,Y=k(j)&&typeof j.id==="string"?j.id:void 0;if(!Y||!Array.isArray(U.input)){$.continuation=void 0;return}let N=J?new Set($.continuation?.finalizedCallIds):new Set;for(let W of X)N.add(W);$.continuation={responseID:Y,input:U.input,signature:HN(U),finalizedCallIds:N}}function ZW($,U,z=U){let X=Array.isArray(U.input)?U.input:[],J=Array.isArray(z.input)?z.input:X,j=HN(z),Y=$.turnInput&&$.turnSignature===j?PD($.turnInput,J):void 0,N=Y===void 0?X:J.slice(Y);if(N.length>0&&N.some(TW)||!$.turnID)$.turnID=i6(),$.turnStartedAt=Date.now();$.turnInput=J.slice(),$.turnSignature=j;let G=U.client_metadata;if(!k(G)||typeof G["x-codex-turn-metadata"]!=="string")return U;let Q;try{Q=JSON.parse(G["x-codex-turn-metadata"])}catch{return U}if(!k(Q))return U;let L=JSON.stringify({session_id:Q.session_id,thread_id:Q.thread_id,thread_source:Q.thread_source,turn_id:$.turnID,sandbox:Q.sandbox,turn_started_at_unix_ms:$.turnStartedAt,request_kind:"turn",window_id:Q.window_id});return{...U,client_metadata:{...G,"x-codex-turn-metadata":L}}}function PD($,U){if($.length>U.length)return;for(let z=0;z<$.length;z++)if(Q6($[z])!==Q6(U[z]))return;return $.length}function AD($,U){let z=Array.isArray(U.input)?U.input:void 0;if(!z||!$.continuation)return U;if($.continuation.signature!==HN(U))return $.continuation=void 0,U;if(!gW($.continuation.input,z))return $.continuation=void 0,U;if($.continuation.input.length===0)return{...U,previous_response_id:$.continuation.responseID};let X=z.slice($.continuation.input.length),J=MD(X,$.continuation.finalizedCallIds);if(J.length===0)return U;return{...U,previous_response_id:$.continuation.responseID,input:J}}function ED($,U){let z=Array.isArray(U.input)?U.input:void 0;if(!$.continuation)return!0;if(!z)return!1;if(!gW($.continuation.input,z))return!0;return z.slice($.continuation.input.length).some(TW)}function TW($){if(!k($))return!1;if(!($.type==="message"||("role"in $)))return!1;return $.role==="user"||$.role==="developer"}function MD($,U){return $.filter((z)=>{if(!k(z))return!0;if(typeof z.type==="string"&&z.type.endsWith("_output"))return!0;if(z.type==="function_call_output"||z.type==="custom_tool_call_output")return!0;if(z.type==="function_call"||z.type==="custom_tool_call"){let X=typeof z.call_id==="string"?z.call_id:typeof z.id==="string"?z.id:void 0;return X?!U.has(X):!0}if(z.type==="message")return z.role!=="assistant";if(typeof z.role==="string")return z.role!=="assistant";return!1})}function HN($){return Q6(bD(Object.fromEntries(Object.entries($).filter(([U])=>U!=="input"&&U!=="stream"&&U!=="background"&&U!=="previous_response_id"&&U!=="generate"))))}function bD($){if(!k($.client_metadata))return $;let U=Object.fromEntries(Object.entries($.client_metadata).filter(([z])=>z!=="x-codex-turn-metadata"&&z!=="x-codex-ws-stream-request-start-ms"));return{...$,client_metadata:U}}function gW($,U){if($.length>=U.length)return!1;for(let z=0;z<$.length;z++)if(Q6($[z])!==Q6(U[z]))return!1;return!0}function xW($){if(!$?.headers)return $;if($.headers instanceof Headers){let U=new Headers($.headers);for(let z of QN)U.delete(z);return{...$,headers:U}}if(Array.isArray($.headers))return{...$,headers:$.headers.filter((U)=>!QN.has(U[0].toLowerCase()))};return{...$,headers:Object.fromEntries(Object.entries($.headers).filter(([U])=>!QN.has(U.toLowerCase())))}}var TD=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),gD=new Set(["gpt-5.6"]),xD=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),fD="opencode-oauth-dummy-key",hD="terminal_resize_reflow",_N="0.144.0",yD=`codex_exec/${_N} (Debian 12.0.0; aarch64) unknown (codex_exec; ${_N})`,cD="seccomp",mD="main-refresh",uD=120000,iD=90000,lD=4000,fW=50,hW=3,nD=25,rD=60000,pD="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",yW=!1,cW=q$("models"),mW=!1,uW=!1;class FN extends Error{code="OPENAI_AUTH_PERSIST_FAILED";constructor($){super("OpenAI OAuth token refreshed but could not be persisted; re-login required",{cause:$});this.name="AuthPersistError"}}function LN($){return $ instanceof FN}function iW(){throw Error(pD)}function dD($){return Math.floor(Math.random()*$)}function oD($){if(typeof $!=="string")return;try{let U=JSON.parse($);return typeof U==="object"&&U!==null&&!Array.isArray(U)?U:void 0}catch{return}}function tD($,U,z){let X=$.get(U);if(X)return X;let J=i6(),j={threadID:J,turnID:i6(),windowID:`${J}:0`};return $.set(U,j),z?.(),j}function q2(){return ZD(a1(),"openai-auth-sessions.json")}function aD(){let $=new Map;try{let U=JSON.parse(ID(q2(),"utf8"));if(!k(U.sessions))return $;for(let[z,X]of Object.entries(U.sessions)){if(!k(X)||typeof X.threadID!=="string")continue;$.set(z,{threadID:X.threadID,turnID:i6(),windowID:`${X.threadID}:0`})}}catch{}return $}function sD($){let U=q2(),z=`${U}.tmp-${process.pid}`;try{RD(a1(),{recursive:!0});let X={version:1,sessions:Object.fromEntries([...$.entries()].map(([J,j])=>[J,{threadID:j.threadID}]))};CD(z,`${JSON.stringify(X,null,2)}
155
- `,"utf8"),SD(z,U)}catch{}}function lW($,U){return k($)&&($.type==="message"||("role"in $))&&$.role===U}function eD($,U){if($.length>U.length)return!1;for(let z=0;z<$.length;z++)if(Q6($[z])!==Q6(U[z]))return!1;return!0}function $K($,U){if(!$.input)return U.length>0;if(!eD($.input,U))return!0;return U.slice($.input.length).some((X)=>lW(X,"user")||lW(X,"developer"))}function UK($,U){let z=Array.isArray(U?.input)?U.input:void 0;if(z&&($K($,z)||!$.turnID))$.turnID=i6(),$.turnStartedAt=Date.now();else if(!$.turnStartedAt)$.turnStartedAt=Date.now();if(z)$.input=z}function JK($){if(!$.metadata)return{init:$.init};let U=oD($.init?.body);if(!$.websocket)UK($.metadata,U);else if(!$.metadata.turnStartedAt)$.metadata.turnStartedAt=Date.now();if(!$.metadata.turnStartedAt)$.metadata.turnStartedAt=Date.now();let z=JSON.stringify({session_id:$.metadata.threadID,thread_id:$.metadata.threadID,thread_source:"user",turn_id:$.metadata.turnID,sandbox:cD,turn_started_at_unix_ms:$.metadata.turnStartedAt,request_kind:"turn",window_id:$.metadata.windowID});if($.headers.set("originator","codex_exec"),$.websocket)$.headers.delete("accept"),$.headers.delete("content-type");else $.headers.set("accept","text/event-stream");if($.headers.set("session-id",$.metadata.threadID),$.headers.delete("x-session-id"),$.headers.delete("x-session-affinity"),$.headers.set("thread-id",$.metadata.threadID),$.headers.set("x-codex-window-id",$.metadata.windowID),$.headers.set("x-client-request-id",$.metadata.threadID),$.headers.set("x-codex-beta-features",hD),$.headers.set("x-codex-turn-metadata",z),$.headers.set("user-agent",yD),$.headers.set("version",_N),$.dumpSessionID)$.headers.set(E6,$.dumpSessionID);let X=U;if(!X)return{init:$.init};let J=$.responsesLite&&typeof X.model==="string"&&xD.has(X.model);if(J&&!$.websocket)$.headers.set("x-openai-internal-codex-responses-lite","true");if(X.prompt_cache_key=$.metadata.threadID,X.parallel_tool_calls??=!0,Array.isArray(X.tools))X.tools=X.tools.map(WK);if(NK(X),OK(X),sN(X),jK(X),J)YK(X);let j={...typeof X.client_metadata==="object"&&X.client_metadata!==null?X.client_metadata:{},"x-codex-installation-id":$.installationID,"x-codex-window-id":$.metadata.windowID};if($.websocket){if(j["x-codex-turn-metadata"]=z,j["x-codex-ws-stream-request-start-ms"]=String(Date.now()),J)j.ws_request_header_x_openai_internal_codex_responses_lite="true"}return X.client_metadata=j,$.headers.delete("content-length"),$.headers.delete("Content-Length"),{init:{...$.init,body:JSON.stringify(l1(X))}}}function zK($,U){return $.find((z)=>z.enabled!==!1&&S4(z)&&(z.id===U||z.accountId===U))}function nW($,U){if($.resetCreditsAvailable!==void 0||U?.resetCreditsAvailable===void 0)return $;return{...$,resetCreditsAvailable:U.resetCreditsAvailable}}function _2($,U,z=Date.now()){let X=$.getMain()?.quota;return{main:{quota:X??null,killed:!1,...X?.resetCreditsAvailable!==void 0?{resetCredits:X.resetCreditsAvailable}:{}},fallbacks:U.accounts.filter((J)=>J.enabled).map((J)=>{let j=$.getFallback(J.id)?.quota;return{id:J.id,label:J.label,quota:j??null,killed:!1,enabled:!0,...j?.resetCreditsAvailable!==void 0?{resetCredits:j.resetCreditsAvailable}:{}}}),route:U.routing?.mode??"main-first",lastUpdated:z}}function YE($,U,z,X=Date.now()){return{..._2($,U,X),activeId:z}}function rW($,U){if(U?.headers!==void 0)return new Headers(U.headers);if($ instanceof Request)return new Headers($.headers);return new Headers}async function XK($,U){if(!($ instanceof Request))return U;let z=new Request($,U),X=z.method.toUpperCase(),J=X==="GET"||X==="HEAD"||z.body===null?void 0:await z.text();return{method:z.method,headers:new Headers(z.headers),body:J,signal:z.signal,cache:z.cache,credentials:z.credentials,integrity:z.integrity,keepalive:z.keepalive,mode:z.mode,redirect:z.redirect,referrer:z.referrer,referrerPolicy:z.referrerPolicy}}function pW($){return $.get("x-session-affinity")??$.get("x-opencode-session")??$.get("x-session-id")??$.get("session-id")??void 0}function jK($){if(!g$().webSearch)return;if(!Array.isArray($.tools)||$.tools.length===0)return;if($.tools.some((U)=>k(U)&&U.type==="web_search"))return;$.tools=[...$.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function vN($){if(Array.isArray($)){for(let U of $)vN(U);return}if(!k($))return;if($.type==="input_image")delete $.detail;for(let U of Object.values($))vN(U)}function YK($){let U=k($.reasoning)?{...$.reasoning}:{};U.context="all_turns",$.reasoning=U,$.parallel_tool_calls=!1;let z=Array.isArray($.input)?$.input:[];vN(z);let J=[{type:"additional_tools",role:"developer",tools:Array.isArray($.tools)?$.tools.filter((j)=>!(k(j)&&j.type==="web_search")):[]}];if(typeof $.instructions==="string"&&$.instructions.length>0)J.push({type:"message",role:"developer",content:[{type:"input_text",text:$.instructions}]});$.input=[...J,...z],delete $.tools,delete $.instructions}function NK($){if(!Array.isArray($.tools))return;$.tools=$.tools.filter((U)=>!(k(U)&&U.type==="function"&&U.name==="web_search"))}function OK($){if(!Array.isArray($.tools))return;$.tools=$.tools.filter((U)=>!(k(U)&&U.type==="function"&&U.name==="websearch_web_search_exa"))}function WK($){if(!k($))return $;if($.type!=="function")return $;let U=k($.parameters)&&"$schema"in $.parameters?(()=>{let{$schema:W,...G}=$.parameters;return G})():$.parameters,{type:z,name:X,description:J,strict:j,parameters:Y,...N}=$;return{type:z,name:X,description:J,strict:j??!1,parameters:U,...N}}async function GK($,U={}){let z=U.codexApiEndpoint??g$().codexApiEndpoint,X=crypto.randomUUID(),J=aD(),j=()=>sD(J),Y=!1,N=[],W=null,G=null,Q;async function L(H,w){let B=$.client.session;if(typeof B?.promptAsync==="function"){let q=await Y8($.client,H),T={noReply:!0,parts:[{type:"text",text:w,ignored:!0}]};if(q?.agent)T.agent=q.agent;if(q?.model)T.model=q.model;if(q?.variant)T.variant=q.variant;await B.promptAsync({path:{id:H},body:T});return}}return{async dispose(){for(let H of N)H.close();if(N.length=0,G){await G.stop().catch(()=>{});let H=globalThis;if(H.__openaiAuthRpcServer===G)H.__openaiAuthRpcServer=void 0;G=null}},async event(H){if(H.event.type!=="session.deleted")return;let w=H.event.properties.info,B=J.get(w.id);if(B)W?.cacheKeepManager?.remove(B.threadID);if(J.delete(w.id))j();if(Q){let q=(await r$(D$()))?.accounts??[];await K2(w.id,q,Q)}for(let q of N)q.remove(w.id)},provider:{id:"openai",async models(H,w){if(w.auth?.type!=="oauth")return H.models;let B=await r$(D$()),q=!B||G2(B),T=q?null:await J8();if(!q&&T&&!mW)mW=!0,cW.debug("restoring OAuth model costs from models.dev catalog");if(!q&&!T&&!uW)uW=!0,cW.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(H.models).filter(([,b])=>{if(b.options.reasoningMode==="pro")return!1;if(TD.has(b.api.id))return!0;if(gD.has(b.api.id))return!1;let y=b.api.id.match(/^gpt-(\d+\.\d+)/)?.[1];return y?parseFloat(y)>5.4:!1}).map(([b,g])=>[b,{...g,cost:q?{input:0,output:0,cache:{read:0,write:0}}:T?.[g.api.id]??T?.[b]??g.cost,limit:g.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:g.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:g.limit}]))}},tool:{web_search:tN},auth:{provider:"openai",async loader(H){let w=await H();if(w.type!=="oauth")return{};await w2({type:"oauth",access:w.access??"",refresh:w.refresh??"",expires:w.expires??0},D$());let B=await r$(D$()).catch((K)=>{let E=D$();throw Error(`OpenAI auth store at ${E} is corrupt or unreadable: ${K instanceof Error?K.message:String(K)}. Fix or remove it to continue.`,{cause:K})}),q;async function T(){let K=D$();try{let E=kD(K);if(q?.path===K&&q.mtimeMs===E.mtimeMs&&q.size===E.size)return q.storage;let S=await r$(K);return q={path:K,mtimeMs:E.mtimeMs,size:E.size,storage:S},S}catch{return q=void 0,r$(K)}}function b(){q=void 0}if(B&&w.access){let K=M0({id_token:"",access_token:w.access,refresh_token:w.refresh??""});if(K&&K!==B.mainAccountId)await L$((E)=>{return E.mainAccountId=K,E},D$()),B.mainAccountId=K,b()}let g=B?.logging?.level;if(g&&typeof g==="string")s1(g);let y=q$("transport"),Z=q$("quota"),N$=q$("refresh"),r=q$("accounts");y.info("codex auth loader ready",{codexApiEndpoint:z,transport:g$().rawWebSocket?"raw-websocket":g$().webSockets?"websocket":"http",webSearch:g$().webSearch});let e=new W2({storage:B,fetchQuotaFn:void 0}),v$,Q$=0,c$=new H2({refreshFn:(K)=>n1({refreshToken:K.refreshToken,fetchImpl:K.fetchImpl,now:K.now}),quotaManager:e,onFallbackStorageChanged:b});if(B&&B.accounts.length>0)c$.startBackgroundRefresh();let X$=q$("cachekeep"),j6=B?.cachekeep?.enabled===!0,k4=B?.cachekeep?.subagents===!0,U4=yN(B),f;async function O$(K){await new Promise((E)=>setTimeout(E,K))}async function F$(K){let E;for(let S=1;S<=hW;S++)try{await $.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:K.refresh,access:K.access,expires:K.expires}});return}catch(l){if(E=l,S<hW)await O$(nD*S)}throw new FN(E)}async function J4(K){await L$((E)=>{return E.refresh=E.refresh??{},K(E),E},D$()),b()}async function r1(K){let E=Date.now()+lD;while(Date.now()<E){await new Promise((h)=>setTimeout(h,fW+dD(fW)));let S=await H();if(S.type!=="oauth"||!S.access)continue;if((S.access!==K.access||S.refresh!==K.refresh||(S.expires??0)>(K.expires??0)+60000)&&(!S.expires||S.expires>Date.now()))return N$.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:S.expires?S.expires-Date.now():void 0}),{access:S.access,refresh:S.refresh??K.refresh??"",expires:S.expires??0}}return null}async function p1(){if(!f)f=(async()=>{let K=await H();if(K.type!=="oauth")throw Error("not oauth");if(!K.refresh)throw Error("Token refresh failed: missing refresh token");let E=dW(K.refresh),S=await r$(D$()),l=S?.refresh?.mainLastRefreshError;if(l&&tW(l,K.refresh,Date.now()))throw Error(aW(l,Date.now()));if(S?.refresh?.mainRefreshLeaseUntil&&S.refresh.mainRefreshLeaseUntil>Date.now()&&S.refresh.mainRefreshLeaseTokenHash===E){let p=await r1(K);if(p)return p;throw Error("Codex OAuth refresh is already in progress")}let h=await N2({name:mD,ttlMs:uD,path:D$(),renew:!0});if(!h){let p=await r1(K);if(p)return p;throw Error("Codex OAuth refresh is already in progress")}let n=crypto.randomUUID(),m=E;try{await J4((d)=>{d.refresh=d.refresh??{},d.refresh.mainRefreshLeaseId=n,d.refresh.mainRefreshLeaseUntil=Date.now()+iD,d.refresh.mainRefreshLeaseTokenHash=E});let p=await r$(D$());if(p?.refresh?.mainRefreshLeaseId!==n||p.refresh.mainRefreshLeaseTokenHash!==E)throw Error("Codex OAuth refresh is already in progress");let t=await n1({refreshToken:K.refresh,fetchImpl:fetch,now:Date.now});return await F$(t),await J4((d)=>{if(d.refresh=d.refresh??{},d.refresh.mainLastRefreshError=void 0,d.refresh.mainRefreshLeaseId===n)d.refresh.mainRefreshLeaseId=void 0,d.refresh.mainRefreshLeaseUntil=void 0,d.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),m=void 0,t}catch(p){if(K.refresh&&!LN(p))await J4((t)=>{t.refresh=t.refresh??{},t.refresh.mainLastRefreshError=oW({error:p,now:Date.now(),refreshToken:K.refresh??"",previous:t.refresh.mainLastRefreshError})}).catch(()=>{});throw p}finally{if(m)await J4((p)=>{if(p.refresh?.mainRefreshLeaseId===n&&p.refresh.mainRefreshLeaseTokenHash===m)p.refresh.mainRefreshLeaseId=void 0,p.refresh.mainRefreshLeaseUntil=void 0,p.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await h.release().catch(()=>{})}})().finally(()=>{f=void 0});return f}let z4=globalThis;z4.__openaiAuthCacheKeepManager?.stop();let a$=new r0({fetchImpl:fetch,getMainToken:async()=>{let K=await H();if(K.type!=="oauth")throw Error("not oauth");if(!K.access||(K.expires??0)<Date.now())try{return(await p1()).access}catch(E){if(LN(E))throw E;if(K.access)return K.access;throw Error("main token refresh failed")}return K.access},refreshFallback:async(K)=>{let E=await T(),S=E?zK(E.accounts,K):void 0;if(!S)throw Error(`fallback account ${K} not found`);let l=await c$.refreshAccount(S,E??{version:1,accounts:[S]});if(!l.access)throw Error(`no access token for ${K}`);return l.access},codexResponsesUrl:z,logger:X$,now:Date.now,getWindow:()=>U4});z4.__openaiAuthCacheKeepManager=a$;async function y6(K,E,S,l,h=!1){if(Object.keys(K).length===0&&!h)return;let n=Date.now(),m=K,p={quota:m,refreshAfter:n+300000,checkedAt:n};if(S&&S!=="main"){let d=e.peekFallbackForPolicy(S)?.quota,W$=nW(m,d);p={...p,quota:W$},e.setFallback(S,p,E,h)}else{let d=l;if(!d&&E){let P$=I0(E);d=P$?S0(P$):void 0}if(d&&v$&&d!==v$){Z.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:d,currentMainIdentity:v$});return}let W$=e.peekMainForPolicy(d)?.quota,O6=nW(m,W$);p={...p,quota:O6},e.setMain(E,p,d,h)}Z.debug("quota pushed",{pid:process.pid,accountId:S??"main",snapshot:p.quota});let t=await T();await m6(e,t)}function k0(K,E,S){let l=K==="main"?e.peekMainForPolicy()?.quota:e.peekFallbackForPolicy(K)?.quota;return O2(l,E,Date.now(),rD,S)}let c6=U.experimentalWebSockets?h6.createWebSocketFetch({httpFetch:fetch,rawWebSocket:g$().rawWebSocket,onQuota:(K,E,S,l)=>{y6(K,E,S,!S||S==="main"?l:void 0,!0)},onRateLimitReached:(K,E,S)=>{if(!E)Z.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:K});let l=E??"main",h=k0(l,K,S);e.markRateLimited(l,h),Z.debug("mid-stream rate limit mark",{pid:process.pid,accountId:l,window:K})}}):void 0;if(c6)N.push(c6),Y=!0;let Y6=L2();Q=Y6;async function m6(K,E){if(!E)return;await B2(_2(K,E),Y6)}async function d1(K,E,S,l,h){let n={activeId:S,route:l,updatedAt:Date.now()};if(K){if(await qN({sessionId:K,...n},h,Y6),E&&E!==K)await qN({sessionId:E,...n},h,Y6);return}await D2(n,Y6)}W={accountStoragePath:D$(),quotaManager:e,loadAccounts:r$,client:$.client,cacheKeepManager:a$,setCacheKeepEnabled:(K)=>{j6=K},setCacheKeepSubagents:(K)=>{k4=K},setCacheKeepWindow:(K)=>{U4=K},refreshSidebar:async()=>{let K=await r$(D$());await m6(e,K)},refreshAllQuota:async()=>p0({getAuth:H,codexRefreshFn:n1,fallbackManager:c$,quotaManager:e,loadAccounts:r$,writeSidebarState:m6,client:$.client,fetchImpl:fetch,now:Date.now,configPath:D$(),storageMainAccountId:B?.mainAccountId,isOAuthAccountFn:S4,whamFn:BN})};let p$=null;if($.directory){let K=globalThis;if(K.__openaiAuthRpcServer)await K.__openaiAuthRpcServer.stop().catch(()=>{}),K.__openaiAuthRpcServer=void 0;try{p$=await Q8({dir:V2($.directory),drain:O8,apply:async(E)=>{let S=await m0(E.command,E.arguments,W);return{text:S.text,knobs:S.knobs}}}),K.__openaiAuthRpcServer=p$,G=p$}catch{}}async function w$(K,E,S,l,h="main"){let n=rW(K,E);if(n.delete("x-api-key"),n.delete("api-key"),n.set("authorization",`Bearer ${S}`),l)n.set("ChatGPT-Account-Id",l);n.set(h6.QUOTA_ACCOUNT_HEADER,h);let m=pW(n),p=m?tD(J,m,j):void 0,t=K instanceof URL?K:new URL(typeof K==="string"?K:K.url),d=t.pathname.includes("/v1/responses")||t.pathname.includes("/chat/completions")?new URL(z):t,O6=JK({init:{...E,headers:n},headers:n,metadata:p,installationID:X,websocket:Boolean(c6&&t.pathname.endsWith("/responses")),responsesLite:U.responsesLite??!1,dumpSessionID:m}).init,P$=j6,m$=new Headers(O6?.headers),A$=hN({enabled:P$,includeSubagents:k4,headers:m$,body:O6?.body});if(P$)X$.trace("cachekeep headers",{pid:process.pid,hasParent:m$.has("x-parent-session-id"),sessionKey:A$?.sessionKey,captured:Boolean(A$),affinity:m$.get("x-session-affinity"),opencodeSession:m$.get("x-opencode-session"),sessionId:m$.get("session-id")});if(c6&&t.pathname.endsWith("/responses")){if(y.debug("WS transport",{pid:process.pid,pathname:t.pathname}),A$)a$.track(A$.sessionKey,A$.bodyText,h,l,A$.replayHeaders,A$.isSubagent);return c6(d,O6)}let u$=h6.withoutInternalHeaders(O6);if(typeof u$?.body!=="string")return fetch(d,u$);if(A$)a$.track(A$.sessionKey,A$.bodyText,h,l,A$.replayHeaders,A$.isSubagent);y.debug("HTTP transport",{pid:process.pid,pathname:t.pathname});try{let T$=await fetch(d,u$);return await Y4({sessionID:m,transport:"http",phase:"http",bodyText:u$.body,url:d.toString(),method:u$.method,headers:u$.headers,status:T$.status}),aN(T$)}catch(T$){throw await Y4({sessionID:m,transport:"http",phase:"http",bodyText:u$.body,url:d.toString(),method:u$.method,headers:u$.headers,error:T$ instanceof Error?T$.message:String(T$)}),T$}}function N6(K,E){if((E?.method??(K instanceof Request?K.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof E?.body!=="string")return!1;try{let l=K instanceof URL?K.toString():typeof K==="string"?K:K.url;return new URL(l).pathname.endsWith("/responses")}catch{return!1}}function C0(K){return e.peekMainForPolicy(K)?.quota}function v2(K,E="killswitch",S){let l=Date.now(),h=e.getMain()?.quota,n=(K?.accounts??[]).filter((W$)=>W$.enabled!==!1&&S4(W$)).map((W$)=>({accountId:W$.id,quota:e.getFallback(W$.id)?.quota})),m=Q2(h,n,l,K);if(E==="mid-stream-rate-limit"&&S!==void 0){let W$=Math.max(1,Math.ceil((S-l)/1000));m=Math.min(m,W$)}let p=Math.floor(m/60),t=m%60,d=E==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${p}m ${t}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${p}m ${t}s.`;return new Response(JSON.stringify({error:{message:d,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(m)}})}async function PN(K){let E=await c$.getUsableFallbackAccounts(K),S=[];for(let h of E)if(h.access)S.push({access:h.access,accountId:h.accountId,keepwarmAccountKey:h.id,quotaAccountId:h.id,fallback:h});let l=S.filter((h)=>!e.isRateLimited(h.quotaAccountId));if(!DN(K))return l;return l.filter((h)=>KN(e.peekFallbackForPolicy(h.quotaAccountId)?.quota,K,h.quotaAccountId,Date.now()))}async function AN(K,E){try{let S=C4(K.headers);await y6(S,E.access,E.quotaAccountId,void 0,b0(K.headers))}catch{}}async function F2(K,E,S){let l=await PN(S);for(let h of l){let n;try{n=await w$(K,E,h.access,h.accountId,h.keepwarmAccountKey)}catch(m){if(m instanceof DOMException&&m.name==="AbortError")throw m;if(E?.signal?.aborted)throw m;throw r.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:h.quotaAccountId}),m}if(!R0(n.status,S))return await c$.markUsed(h.fallback),{response:n,accessToken:h.access,quotaAccountId:h.quotaAccountId,activeId:h.keepwarmAccountKey};await AN(n,h),n.body?.cancel().catch(()=>{})}return}async function P2(K,E,S,l){if(!N6(K,E))return{response:S};let h=await T(),n=await PN(h);if(!n.length)return{response:S};let m=S,p;for(let t of n){let d;try{d=await w$(K,E,t.access,t.accountId,t.keepwarmAccountKey)}catch(W$){if(W$ instanceof DOMException&&W$.name==="AbortError")throw W$;if(E?.signal?.aborted)throw W$;return r.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:t.quotaAccountId}),{response:m,...p}}if(m.body?.cancel().catch(()=>{}),m=d,p={accessToken:t.access,accountId:t.quotaAccountId},!R0(d.status,h))return await c$.markUsed(t.fallback),{response:d,...p};await AN(d,t)}return{response:m,...p}}if(!yW){if(yW=!0,B){let K=[];for(let E of B.accounts)if(S4(E))K.push(E);e.seedFallbacksFromAccounts(K)}m6(e,B).catch(()=>{}),p0({getAuth:H,codexRefreshFn:n1,fallbackManager:c$,quotaManager:e,loadAccounts:r$,writeSidebarState:m6,client:$.client,fetchImpl:fetch,now:Date.now,configPath:D$(),storageMainAccountId:B?.mainAccountId,isOAuthAccountFn:S4,whamFn:BN,respectBackoff:!0}).catch((K)=>Z.warn("boot quota seed failed",{pid:process.pid,error:A6(K)}))}return{apiKey:fD,async fetch(K,E){let S=rW(K,E),l=pW(S),h=S.get("x-parent-session-id")?.trim()||void 0,n=await T(),m=await H(),p=++Q$;if(m.type!=="oauth")return fetch(K,E);E=await XK(K,E);let t=m.access??"";if(!m.access||(m.expires??0)<Date.now()){N$.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(m.access),expiresInMs:m.expires?m.expires-Date.now():void 0});try{let Y$=await p1();m.access=Y$.access,m.refresh=Y$.refresh,m.expires=Y$.expires}catch(Y$){if(LN(Y$))throw Y$}}t=m.access??"";let W$=m.accountId??(t?S0(I0(t)??{}):void 0);if(p===Q$)v$=W$;let O6=n?.routing?.mode??"main-first",P$,m$,A$=!1;if(O6==="fallback-first"&&N6(K,E)){A$=!0;let Y$=await F2(K,E,n);if(Y$)P$=Y$.response,m$={accessToken:Y$.accessToken,accountId:Y$.quotaAccountId,activeId:Y$.activeId}}if(!P$){let Y$=DN(n)&&!KN(C0(W$),n,void 0,Date.now()),X4=e.isRateLimited("main");if(Y$||X4){let RN=X4&&!Y$?"mid-stream-rate-limit":"killswitch";r.debug("killswitch blocked primary",{pid:process.pid,activeId:"main",reason:RN}),P$=v2(n,RN,X4?e.rateLimitedUntil("main"):void 0)}else P$=await w$(K,E,t,W$,"main")}let u$=Boolean(m$),T$=P$,EN=m$?.accessToken??t,MN=m$?.accountId,bN=m$?.activeId??"main";if(!m$&&!A$&&R0(P$.status,n)){r.debug("reactive fallback triggered",{pid:process.pid,status:P$.status});let Y$=await P2(K,E,P$,void 0),X4=Y$.response;if(X4!==P$){if(u$=!0,T$=X4,EN=Y$.accessToken??t,MN=Y$.accountId,Y$.accountId)bN=Y$.accountId}}try{let Y$=C4(T$.headers);if(u$)await y6(Y$,EN,MN,void 0,b0(T$.headers));else await y6(Y$,t,void 0,W$,b0(T$.headers))}catch{}return await d1(l,h,bN,O6,n?.accounts??[]).catch(()=>{}),T$},async dispose(){if(a$.stop(),z4.__openaiAuthCacheKeepManager===a$)z4.__openaiAuthCacheKeepManager=void 0;if(c$.stopBackgroundRefresh(),G){await G.stop().catch(()=>{});let K=globalThis;if(K.__openaiAuthRpcServer===G)K.__openaiAuthRpcServer=void 0;G=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:H}=await z2(),w=await $2(),B=eW(crypto.getRandomValues(new Uint8Array(32)).buffer),q=U2(H,w,B),T=X2(w,B);return{url:q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let b=await T,g=M0(b);return{type:"success",refresh:b.refresh_token,access:b.access_token,expires:Date.now()+(b.expires_in??3600)*1000,accountId:g}}finally{J2(B)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:H,url:w,instructions:B}=await j2();return{url:w,instructions:B,method:"auto",async callback(){try{let q=await Y2(H);return{type:"success",refresh:q.refresh_token,access:q.access_token,expires:Date.now()+(q.expires_in??3600)*1000,accountId:M0(q)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(H,w)=>{if(H.model.providerID!=="openai")return;if(w.headers.originator="opencode",w.headers["User-Agent"]=`${sW} (${VN.platform()} ${VN.release()}; ${VN.arch()})`,w.headers["session-id"]=H.sessionID,Y&&H.agent==="title")w.headers[h6.TITLE_HEADER]="true"},"chat.params":async(H,w)=>{if(H.model.providerID!=="openai")return;w.maxOutputTokens=void 0},config:async(H)=>{H.command={...H.command??{},[T0]:{template:T0,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[g0]:{template:g0,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[x0]:{template:x0,description:"Show or change OpenAI account routing between main-first and fallback-first."},[f0]:{template:f0,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[h0]:{template:h0,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[y0]:{template:y0,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[c0]:{template:c0,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."}}},"command.execute.before":async(H)=>{if(!ZN.includes(H.command))return;if(!W)await L(H.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),iW();let w=H.command,B={...W,sessionId:H.sessionID,notify:(T)=>{zJ(T,H.sessionID)}},q=await m0(w,H.arguments,B);if(W8(H.sessionID))zJ(q,H.sessionID);else await L(H.sessionID,q.text);iW()}}}var QK=async($)=>{let U=g$();return GK($,{codexApiEndpoint:U.codexApiEndpoint,experimentalWebSockets:U.webSockets,responsesLite:U.responsesLite})},NE={id:"cortexkit-openai-auth",server:QK};export{pW as resolveSidebarSessionId,I0 as parseJwtClaims,nW as mergePushedQuotaMetadata,zK as findCachekeepFallbackAccount,S0 as extractAccountIdFromClaims,NE as default,YE as buildSidebarState,_2 as buildSidebarMachineState,QK as OpenAIAuthPlugin,uD as MAIN_REFRESH_LOCK_TTL_MS,iD as MAIN_REFRESH_LEASE_TTL_MS,GK as CodexAuthPlugin,FN as AuthPersistError};
167
+ `)),W=!0,L("idle timeout waiting for websocket"),!s)return;if(s.type==="response.completed"||s.type==="response.done"){G=!0,sL(s,H),Y.onComplete?.(s,H),Y.onTerminal?.(s),O();return}if(s.type==="response.failed"||s.type==="response.incomplete"||s.type==="error")G=!0,Y.onTerminal?.(s),O()}function j(S){B(new R0(o0(S),{cause:S}))}function w(S){if(G)return;B(new R0(MG("WebSocket closed before response.completed",S.code,S.reason)))}function P(){let S=_9(Y.signal);if(G)return;G=!0,U(),N(),Y.onAbort?.(S),Q?.error(S)}function k(S){if(G)return;G=!0,U(),N(),Y.onAbort?.(tL(S))}function x(S){$(),J=S,J.addEventListener("message",Z),J.addEventListener("error",j,{once:!0}),J.addEventListener("close",w,{once:!0}),$=()=>{J.removeEventListener("message",Z),J.removeEventListener("error",j),J.removeEventListener("close",w)};let{background:d,...m}=Y.body;L("idle timeout sending websocket request");try{J.send(JSON.stringify({type:"response.create",...m})),L("idle timeout waiting for websocket")}catch(e){if(G)return;B(new R0(e instanceof Error?e.message:String(e),{cause:e}))}}return new Response(new ReadableStream({start(S){if(Q=S,Y.signal?.addEventListener("abort",P,{once:!0}),Y.signal?.aborted){P();return}x(J)},cancel(S){k(S)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function nL(Y,X){if(!oL(Y))return;await c0({component:"ws",event:"provider_native_web_search_event",sessionID:X,serverEventType:Y.type,itemType:_(Y.item)?Y.item.type:void 0,serverEvent:Y})}function oL(Y){if(typeof Y.type==="string"&&(Y.type.startsWith("response.web_search_call.")||Y.type.startsWith("response.web_search_preview_call.")))return!0;if(_(Y.item)&&typeof Y.item.type==="string")return Y.item.type==="web_search_call"||Y.item.type==="web_search_preview_call";return!1}function rL(Y,X){if(Y.type!=="response.output_item.done")return;if(!_(Y.item))return;EG(Y.item,X)}function sL(Y,X){let J=Y.response;if(!_(J)||!Array.isArray(J.output))return;for(let Q of J.output)if(_(Q))EG(Q,X)}function EG(Y,X){if(Y.type!=="function_call"&&Y.type!=="custom_tool_call")return;let J=typeof Y.call_id==="string"?Y.call_id:typeof Y.id==="string"?Y.id:void 0;if(J)X.add(J)}function aL(Y,X){if(Y?.type!=="error")return;let J=Y.status??Y.status_code;if(typeof J!=="number"||J>=200&&J<300)return;return{status:J,headers:_(Y.headers)?Object.fromEntries(Object.entries(Y.headers).flatMap(([Q,$])=>typeof $==="string"||typeof $==="number"||typeof $==="boolean"?[[Q,String($)]]:[])):void 0,body:X,message:_(Y.error)&&typeof Y.error.message==="string"?Y.error.message:`${J}`}}function $Y(Y){if(typeof Y==="string")try{return $Y(JSON.parse(Y))}catch{return}if(!_(Y))return;let X=$Y(Y.cause);if(X)return X;let J=$Y(Y.body);if(J)return J;let Q=_(Y.error)?Y.error:Y,$=typeof Q.type==="string"?Q.type:void 0,G=Y.status??Y.status_code;if($!=="usage_limit_reached"&&G!==429)return;let{resets_at:W,resets_in_seconds:K}=Q,H=typeof W==="number"&&Number.isFinite(W)&&W>0?W*1000:typeof K==="number"&&Number.isFinite(K)&&K>0?Date.now()+K*1000:void 0;return{window:$??"primary",resetAt:H}}function tL(Y){if(I9(Y))return Y;if(Y instanceof Error)return Y;return new DOMException(typeof Y==="string"?Y:"Aborted","AbortError")}function _9(Y){let X=Y?.reason;if(I9(X))return X;if(eL(X))return X;return new DOMException(X instanceof Error?X.message:"Aborted","AbortError")}function eL(Y){return Y instanceof Error&&(Y.name==="ProviderHeaderTimeoutError"||Y.name==="ProviderResponseStreamError")}function MG(Y,X,J){let Q=[`code ${X}`];if(X===1009)Q.push("message too big");if(J.length>0)Q.push(J.toString());return`${Y} (${Q.join(": ")})`}var k9="x-opencode-title",aY="x-openai-auth-quota-account",S9=new Set([k9,r0,aY,"x-opencode-session"]),XN=15000,JN=300000,QN=3300000,AG="websocket_connection_limit_reached";function $N(Y){let X=typeof Y.authorization==="string"&&Y.authorization.startsWith("Bearer ")?Y.authorization.slice(7):"",J=typeof Y["chatgpt-account-id"]==="string"?Y["chatgpt-account-id"]:"";return YN("sha256").update(`${X}:${J}`).digest("hex").slice(0,12)}function GN(Y){let X=Y?.httpFetch??globalThis.fetch,J=new Map,Q=Y?.connectTimeout??XN,$=Y?.idleTimeout??JN,G=Y?.maxConnectionAge??QN,W=Y?.streamRetries??5,K=Y?.firstEventGraceMs??250,H=Y?.rawWebSocket??!1,U=Y?.onQuota,N=Y?.onRateLimitReached,O=setInterval(()=>Z(),Math.min($,60000));if(typeof O==="object"&&"unref"in O&&typeof O.unref==="function")O.unref();async function B(P,k){let x=P instanceof URL?P.toString():typeof P==="string"?P:P.url,S=D0.normalizeHeaders(k?.headers),d=xG(k),m=wY(d);if(k?.method!=="POST"||!new URL(x).pathname.endsWith("/responses"))return X(P,m);let e=(()=>{try{if(typeof k?.body!=="string")return;let a=JSON.parse(k.body);return typeof a==="object"&&a!==null?a:void 0}catch{return}})();if(!e?.stream)return X(P,m);if(S[k9]==="true")return X(P,m);let y=S[r0]??S["x-session-affinity"]??S["session-id"],s=y;if(!y)return X(P,m);let j1=D0.normalizeHeaders(d?.headers),u=$N(j1),g0=`${y}:${u}:conversation`,x1=typeof S[aY]==="string"?S[aY]:void 0,D1=N?(a,z0)=>N(a,x1,z0):void 0,g=J.get(g0)??{lastUsedAt:Date.now(),busy:!1,fallback:!1,streamFailures:0};if(J.set(g0,g),g.fallback)return X(P,m);if(g.busy)return X(P,m);g.busy=!0,g.lastUsedAt=Date.now();try{let a=ZN(e),z0=D0.normalizeHeaders(d?.headers),J8=typeof z0.authorization==="string"&&z0.authorization.startsWith("Bearer ")?z0.authorization.slice(7):"",Q8=typeof z0["chatgpt-account-id"]==="string"?z0["chatgpt-account-id"]:void 0,P1=U?(Q0)=>U(Q0,J8,x1,Q8):void 0,VY=!g.socket&&!g.continuation?BN(z0):z0;if(g.socket=await UN(g,Y?.url??x,VY,Q,G,H,k?.signal),jN(g,a))await HN(g,a,$,{signal:k?.signal??void 0,sessionID:s,url:Y?.url??x,headers:d?.headers,onRateLimitReached:D1});let y0=()=>{},G1=()=>{},n0=new Promise((Q0,k0)=>{y0=Q0,G1=k0}),W1=qN(g,a),v1=GY(SG(g,W1,a)),z1=typeof v1.previous_response_id==="string";await A1({sessionID:s,transport:"websocket",phase:"main",bodyText:JSON.stringify(v1),url:Y?.url??x,method:d?.method,headers:d?.headers});let B0=D0.streamResponsesWebSocket({socket:g.socket,body:v1,sessionID:s??void 0,idleTimeout:$,signal:k?.signal??void 0,onQuota:P1,onRateLimitReached:D1,onFirstEvent:(Q0)=>y0(Q0??!0),onComplete:(Q0,k0)=>{let K1=TG(Q0);c0({component:"ws-pool",event:"main_completed",sessionID:s,responseID:RG(Q0),usage:K1}),IG(g,a,Q0,k0,z1)},onTerminal:(Q0)=>{if(g.busy=!1,g.lastUsedAt=Date.now(),g.streamFailures=0,Q0.type!=="response.completed"&&Q0.type!=="response.done")g.continuation=void 0,i0(g)},onConnectionInvalid:()=>{if(g.busy=!1,g.lastUsedAt=Date.now(),!g.fallback)L(g);g.continuation=void 0,i0(g),y0(!1)},onAbort:(Q0)=>{g.busy=!1,g.lastUsedAt=Date.now(),g.streamFailures=0,g.continuation=void 0,i0(g),G1(Q0)},onRetryableTerminal:async(Q0)=>{let k0=WN(Q0);if(!k0)return;throw g.fallback=!0,k0}}),q0=await zN(n0,K);if(q0!==!1){if(q0===!0||q0.status<200||q0.status>599)return B0;return new Response(q0.body,{status:q0.status,headers:{"content-type":"application/json",...q0.headers}})}if(!g.fallback)return B0;return X(P,m)}catch(a){if(g.busy=!1,g.lastUsedAt=Date.now(),D0.isAbortError(a))throw g.streamFailures=0,g.continuation=void 0,i0(g),a;let z0=D0.parseRateLimitSignal(a);if(z0)D1?.(z0.window,z0.resetAt);if(D0.isUpgradeFailure(a)&&!H)g.fallback=!0;if(L(g),g.continuation=void 0,i0(g),g.fallback)return X(P,m);return KN(new R0(a instanceof Error?a.message:String(a),{cause:a}))}}function L(P){if(P.streamFailures++,P.streamFailures>W)P.fallback=!0}function Z(){let P=Date.now();for(let[k,x]of J){if(x.busy)continue;if(P-x.lastUsedAt<$)continue;i0(x),J.delete(k)}}function j(){clearInterval(O);for(let P of J.values())i0(P);J.clear()}function w(P){let k=`${P}:`;for(let[x,S]of J){if(!x.startsWith(k))continue;i0(S),J.delete(x)}}return Object.assign(B,{close:j,remove:w})}function WN(Y){if(Y.type!=="error"||!_(Y.error)||Y.error.code!==AG)return;return Error(typeof Y.error.message==="string"?Y.error.message:AG)}async function zN(Y,X){if(X<=0)return!1;return new Promise((J,Q)=>{let $=setTimeout(()=>J(!1),X);Y.then((G)=>{clearTimeout($),J(G)},(G)=>{clearTimeout($),Q(G)})})}function KN(Y){return new Response(new ReadableStream({start(X){X.error(Y)}}),{status:200,headers:{"content-type":"text/event-stream"}})}async function UN(Y,X,J,Q,$,G,W){if(Y.socket?.readyState===WebSocket.OPEN&&Y.connectedAt&&Date.now()-Y.connectedAt<$)return Y.socket;i0(Y);let K=await D0.connectResponsesWebSocket({url:D0.toWebSocketUrl(X),headers:J,timeout:Q,rawWebSocket:G,signal:W??void 0});return Y.connectedAt=Date.now(),K}function i0(Y){if(Y.socket)Y.socket.close(),Y.socket=void 0;Y.connectedAt=void 0,Y.continuation=void 0}async function HN(Y,X,J,Q){if(!Y.socket||!Array.isArray(X.input)||X.input.length===0)return;let $=NN(X);await A1({sessionID:Q.sessionID,transport:"websocket",phase:"prewarm",bodyText:JSON.stringify($),url:Q.url,method:"POST",headers:Q.headers});let G=D0.streamResponsesWebSocket({socket:Y.socket,body:$,sessionID:Q.sessionID,idleTimeout:J,signal:Q.signal,onRateLimitReached:Q.onRateLimitReached,onComplete:(W,K)=>{c0({component:"ws-pool",event:"prewarm_completed",sessionID:Q.sessionID,responseID:RG(W),usage:TG(W)}),IG(Y,$,W,K,!1)},onTerminal:(W)=>{if(W.type!=="response.completed"&&W.type!=="response.done")Y.continuation=void 0},onConnectionInvalid:()=>{Y.continuation=void 0},onAbort:()=>{Y.continuation=void 0}});await LN(G)}function RG(Y){let X=Y.response;if(!_(X))return;return typeof X.id==="string"?X.id:void 0}function TG(Y){let X=Y.response;if(!_(X))return;return _(X.usage)?X.usage:void 0}async function LN(Y){let X=Y.body?.getReader();if(!X)return;while(!0)if((await X.read()).done)return}function NN(Y){return GY({...Y,generate:!1,input:[],previous_response_id:void 0,client_metadata:VN(Y.client_metadata)})}function CG(Y){return JSON.stringify({session_id:Y.session_id,thread_id:Y.thread_id,thread_source:Y.thread_source,turn_id:"",sandbox:Y.sandbox,request_kind:"prewarm",window_id:Y.window_id})}function VN(Y){if(!_(Y))return Y;if(typeof Y["x-codex-turn-metadata"]!=="string")return Y;try{let X=JSON.parse(Y["x-codex-turn-metadata"]);if(!_(X))return Y;return{...Y,"x-codex-turn-metadata":CG(X),"x-codex-ws-stream-request-start-ms":String(Date.now())}}catch{return Y}}function BN(Y){let X=Y["x-codex-turn-metadata"];if(!X)return Y;try{let J=JSON.parse(X);if(!_(J))return Y;return{...Y,"x-codex-turn-metadata":CG(J)}}catch{return Y}}var _G=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function ZN(Y){let X={...Y};if(Array.isArray(Y.input))X.input=Y.input.map(ON);return X}function GY(Y){let X={};for(let J of _G)if(J in Y)X[J]=Y[J];for(let J of Object.keys(Y))if(!(J in X))X[J]=Y[J];return X}function ON(Y){if(!_(Y))return Y;if(typeof Y.type==="string")return Y;if(typeof Y.role!=="string")return Y;if(!("content"in Y))return Y;return{...Y,type:"message"}}function IG(Y,X,J,Q,$){let G=J.response,W=_(G)&&typeof G.id==="string"?G.id:void 0;if(!W||!Array.isArray(X.input)){Y.continuation=void 0;return}let K=$?new Set(Y.continuation?.finalizedCallIds):new Set;for(let H of Q)K.add(H);Y.continuation={responseID:W,input:X.input,signature:b9(X),finalizedCallIds:K}}function SG(Y,X,J=X){let Q=Array.isArray(X.input)?X.input:[],$=Array.isArray(J.input)?J.input:Q,G=b9(J),W=Y.turnInput&&Y.turnSignature===G?FN(Y.turnInput,$):void 0,K=W===void 0?Q:$.slice(W);if(K.length>0&&K.some(kG)||!Y.turnID)Y.turnID=N1(),Y.turnStartedAt=Date.now();Y.turnInput=$.slice(),Y.turnSignature=G;let U=X.client_metadata;if(!_(U)||typeof U["x-codex-turn-metadata"]!=="string")return X;let N;try{N=JSON.parse(U["x-codex-turn-metadata"])}catch{return X}if(!_(N))return X;let O=JSON.stringify({session_id:N.session_id,thread_id:N.thread_id,thread_source:N.thread_source,turn_id:Y.turnID,sandbox:N.sandbox,turn_started_at_unix_ms:Y.turnStartedAt,request_kind:"turn",window_id:N.window_id});return{...X,client_metadata:{...U,"x-codex-turn-metadata":O}}}function FN(Y,X){if(Y.length>X.length)return;for(let J=0;J<Y.length;J++)if(u0(Y[J])!==u0(X[J]))return;return Y.length}function qN(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!J||!Y.continuation)return X;if(Y.continuation.signature!==b9(X))return Y.continuation=void 0,X;if(!bG(Y.continuation.input,J))return Y.continuation=void 0,X;if(Y.continuation.input.length===0)return{...X,previous_response_id:Y.continuation.responseID};let Q=J.slice(Y.continuation.input.length),$=DN(Q,Y.continuation.finalizedCallIds);if($.length===0)return X;return{...X,previous_response_id:Y.continuation.responseID,input:$}}function jN(Y,X){let J=Array.isArray(X.input)?X.input:void 0;if(!Y.continuation)return!0;if(!J)return!1;if(!bG(Y.continuation.input,J))return!0;return J.slice(Y.continuation.input.length).some(kG)}function kG(Y){if(!_(Y))return!1;if(!(Y.type==="message"||("role"in Y)))return!1;return Y.role==="user"||Y.role==="developer"}function DN(Y,X){return Y.filter((J)=>{if(!_(J))return!0;if(typeof J.type==="string"&&J.type.endsWith("_output"))return!0;if(J.type==="function_call_output"||J.type==="custom_tool_call_output")return!0;if(J.type==="function_call"||J.type==="custom_tool_call"){let Q=typeof J.call_id==="string"?J.call_id:typeof J.id==="string"?J.id:void 0;return Q?!X.has(Q):!0}if(J.type==="message")return J.role!=="assistant";if(typeof J.role==="string")return J.role!=="assistant";return!1})}function b9(Y){return u0(PN(Object.fromEntries(Object.entries(Y).filter(([X])=>X!=="input"&&X!=="stream"&&X!=="background"&&X!=="previous_response_id"&&X!=="generate"))))}function PN(Y){if(!_(Y.client_metadata))return Y;let X=Object.fromEntries(Object.entries(Y.client_metadata).filter(([J])=>J!=="x-codex-turn-metadata"&&J!=="x-codex-ws-stream-request-start-ms"));return{...Y,client_metadata:X}}function bG(Y,X){if(Y.length>=X.length)return!1;for(let J=0;J<Y.length;J++)if(u0(Y[J])!==u0(X[J]))return!1;return!0}function xG(Y){if(!Y?.headers)return Y;if(Y.headers instanceof Headers){let X=new Headers(Y.headers);for(let J of S9)X.delete(J);return{...Y,headers:X}}if(Array.isArray(Y.headers))return{...Y,headers:Y.headers.filter((X)=>!S9.has(X[0].toLowerCase()))};return{...Y,headers:Object.fromEntries(Object.entries(Y.headers).filter(([X])=>!S9.has(X.toLowerCase())))}}var CN=new Set(["gpt-5.5","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini"]),_N=new Set(["gpt-5.6"]),IN=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),SN="opencode-oauth-dummy-key",kN="terminal_resize_reflow",g9="0.144.0",bN=`codex_exec/${g9} (Debian 12.0.0; aarch64) unknown (codex_exec; ${g9})`,xN="seccomp",vN="main-refresh",hN=120000,gN=90000,yN=4000,vG=50,hG=3,fN=25,mN=60000,cN="__OPENCODE_OPENAI_AUTH_COMMAND_HANDLED__",gG=!1,yG=L0("models"),fG=!1,mG=!1;class f9 extends Error{code="OPENAI_AUTH_PERSIST_FAILED";constructor(Y){super("OpenAI OAuth token refreshed but could not be persisted; re-login required",{cause:Y});this.name="AuthPersistError"}}function v9(Y){return Y instanceof f9}function cG(){throw Error(cN)}function uN(Y){return Math.floor(Math.random()*Y)}function pN(Y){if(typeof Y!=="string")return;try{let X=JSON.parse(Y);return typeof X==="object"&&X!==null&&!Array.isArray(X)?X:void 0}catch{return}}function lN(Y,X,J){let Q=Y.get(X);if(Q)return Q;let $=N1(),G={threadID:$,turnID:N1(),windowID:`${$}:0`};return Y.set(X,G),J?.(),G}function PW(){return TN(jY(),"openai-auth-sessions.json")}function dN(){let Y=new Map;try{let X=JSON.parse(EN(PW(),"utf8"));if(!_(X.sessions))return Y;for(let[J,Q]of Object.entries(X.sessions)){if(!_(Q)||typeof Q.threadID!=="string")continue;Y.set(J,{threadID:Q.threadID,turnID:N1(),windowID:`${Q.threadID}:0`})}}catch{}return Y}function iN(Y){let X=PW(),J=`${X}.tmp-${process.pid}`;try{wN(jY(),{recursive:!0});let Q={version:1,sessions:Object.fromEntries([...Y.entries()].map(([$,G])=>[$,{threadID:G.threadID}]))};RN(J,`${JSON.stringify(Q,null,2)}
168
+ `,"utf8"),MN(J,X)}catch{}}function uG(Y,X){return _(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===X}function nN(Y,X){if(Y.length>X.length)return!1;for(let J=0;J<Y.length;J++)if(u0(Y[J])!==u0(X[J]))return!1;return!0}function oN(Y,X){if(!Y.input)return X.length>0;if(!nN(Y.input,X))return!0;return X.slice(Y.input.length).some((Q)=>uG(Q,"user")||uG(Q,"developer"))}function rN(Y,X){let J=Array.isArray(X?.input)?X.input:void 0;if(J&&(oN(Y,J)||!Y.turnID))Y.turnID=N1(),Y.turnStartedAt=Date.now();else if(!Y.turnStartedAt)Y.turnStartedAt=Date.now();if(J)Y.input=J}function sN(Y){if(!Y.metadata)return{init:Y.init};let X=pN(Y.init?.body);if(!Y.websocket)rN(Y.metadata,X);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Date.now();let J=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:xN,turn_started_at_unix_ms:Y.metadata.turnStartedAt,request_kind:"turn",window_id:Y.metadata.windowID});if(Y.headers.set("originator","codex_exec"),Y.websocket)Y.headers.delete("accept"),Y.headers.delete("content-type");else Y.headers.set("accept","text/event-stream");if(Y.headers.set("session-id",Y.metadata.threadID),Y.headers.delete("x-session-id"),Y.headers.delete("x-session-affinity"),Y.headers.set("thread-id",Y.metadata.threadID),Y.headers.set("x-codex-window-id",Y.metadata.windowID),Y.headers.set("x-client-request-id",Y.metadata.threadID),Y.headers.set("x-codex-beta-features",kN),Y.headers.set("x-codex-turn-metadata",J),Y.headers.set("user-agent",bN),Y.headers.set("version",g9),Y.dumpSessionID)Y.headers.set(r0,Y.dumpSessionID);let Q=X;if(!Q)return{init:Y.init};let $=Y.responsesLite&&typeof Q.model==="string"&&IN.has(Q.model);if($&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if(Q.prompt_cache_key=Y.metadata.threadID,Q.parallel_tool_calls??=!0,Array.isArray(Q.tools))Q.tools=Q.tools.map(QV);if(XV(Q),JV(Q),SX(Q),eN(Q),$)YV(Q);let G={...typeof Q.client_metadata==="object"&&Q.client_metadata!==null?Q.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(G["x-codex-turn-metadata"]=J,G["x-codex-ws-stream-request-start-ms"]=String(Date.now()),$)G.ws_request_header_x_openai_internal_codex_responses_lite="true"}return Q.client_metadata=G,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(GY(Q))}}}function aN(Y,X){return Y.find((J)=>J.enabled!==!1&&q1(J)&&(J.id===X||J.accountId===X))}function pG(Y,X){if(Y.resetCreditsAvailable!==void 0||X?.resetCreditsAvailable===void 0)return Y;return{...Y,resetCreditsAvailable:X.resetCreditsAvailable}}function tY(Y,X){if(!Y)return Y;if(typeof Y.checkedAt==="number"&&Number.isFinite(Y.checkedAt))return Y;return{...Y,checkedAt:X}}function wW(Y,X,J=Date.now(),Q=X.mainAccountId){let $=Y.getMain(),G=$?.quota;return{main:{quota:G?{...G,checkedAt:$.checkedAt,primary:tY(G.primary,$.checkedAt),secondary:tY(G.secondary,$.checkedAt)}:null,...typeof Q==="string"?{mainAccountId:Q}:{},killed:!1,...G?.resetCreditsAvailable!==void 0?{resetCredits:G.resetCreditsAvailable}:{}},fallbacks:X.accounts.filter((W)=>W.enabled).map((W)=>{let K=Y.getFallback(W.id),H=K?.quota;return{id:W.id,label:W.label,accountId:K?.accountId??W.accountId,quota:H?{...H,checkedAt:K.checkedAt,primary:tY(H.primary,K.checkedAt),secondary:tY(H.secondary,K.checkedAt)}:null,killed:!1,enabled:!0,...H?.resetCreditsAvailable!==void 0?{resetCredits:H.resetCreditsAvailable}:{}}}),route:X.routing?.mode??"main-first",lastUpdated:J}}function H4(Y,X,J,Q=Date.now()){return{...wW(Y,X,Q),activeId:J}}function lG(Y,X){if(X?.headers!==void 0)return new Headers(X.headers);if(Y instanceof Request)return new Headers(Y.headers);return new Headers}async function tN(Y,X){if(!(Y instanceof Request))return X;let J=new Request(Y,X),Q=J.method.toUpperCase(),$=Q==="GET"||Q==="HEAD"||J.body===null?void 0:await J.text();return{method:J.method,headers:new Headers(J.headers),body:$,signal:J.signal,cache:J.cache,credentials:J.credentials,integrity:J.integrity,keepalive:J.keepalive,mode:J.mode,redirect:J.redirect,referrer:J.referrer,referrerPolicy:J.referrerPolicy}}function dG(Y){return Y.get("x-session-affinity")??Y.get("x-opencode-session")??Y.get("x-session-id")??Y.get("session-id")??void 0}function eN(Y){if(!w0().webSearch)return;if(!Array.isArray(Y.tools)||Y.tools.length===0)return;if(Y.tools.some((X)=>_(X)&&X.type==="web_search"))return;Y.tools=[...Y.tools,{type:"web_search",external_web_access:!1,search_content_types:["text","image"]}]}function y9(Y){if(Array.isArray(Y)){for(let X of Y)y9(X);return}if(!_(Y))return;if(Y.type==="input_image")delete Y.detail;for(let X of Object.values(Y))y9(X)}function YV(Y){let X=_(Y.reasoning)?{...Y.reasoning}:{};X.context="all_turns",Y.reasoning=X,Y.parallel_tool_calls=!1;let J=Array.isArray(Y.input)?Y.input:[];y9(J);let $=[{type:"additional_tools",role:"developer",tools:Array.isArray(Y.tools)?Y.tools.filter((G)=>!(_(G)&&G.type==="web_search")):[]}];if(typeof Y.instructions==="string"&&Y.instructions.length>0)$.push({type:"message",role:"developer",content:[{type:"input_text",text:Y.instructions}]});Y.input=[...$,...J],delete Y.tools,delete Y.instructions}function XV(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(_(X)&&X.type==="function"&&X.name==="web_search"))}function JV(Y){if(!Array.isArray(Y.tools))return;Y.tools=Y.tools.filter((X)=>!(_(X)&&X.type==="function"&&X.name==="websearch_web_search_exa"))}function QV(Y){if(!_(Y))return Y;if(Y.type!=="function")return Y;let X=_(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:H,...U}=Y.parameters;return U})():Y.parameters,{type:J,name:Q,description:$,strict:G,parameters:W,...K}=Y;return{type:J,name:Q,description:$,strict:G??!1,parameters:X,...K}}async function $V(Y,X={}){let J=X.codexApiEndpoint??w0().codexApiEndpoint,Q=crypto.randomUUID(),$=dN(),G=()=>iN($),W=!1,K=[],H=null,U=null,N,O=new Z8;async function B(L,Z){let j=Y.client.session;if(typeof j?.promptAsync==="function"){let w=await fX(Y.client,L),P={noReply:!0,parts:[{type:"text",text:Z,ignored:!0}]};if(w?.agent)P.agent=w.agent;if(w?.model)P.model=w.model;if(w?.variant)P.variant=w.variant;await j.promptAsync({path:{id:L},body:P});return}}return{async dispose(){O.stop();for(let L of K)L.close();if(K.length=0,U){await U.stop().catch(()=>{});let L=globalThis;if(L.__openaiAuthRpcServer===U)L.__openaiAuthRpcServer=void 0;U=null}},async event(L){if(L.event.type!=="session.deleted")return;let Z=L.event.properties.info,j=$.get(Z.id);if(j)H?.cacheKeepManager?.remove(j.threadID);if($.delete(Z.id))G();if(N){let w=(await A0(U0()))?.accounts;await FW(Z.id,w,N)}for(let w of K)w.remove(Z.id)},provider:{id:"openai",async models(L,Z){if(Z.auth?.type!=="oauth")return L.models;let j=await A0(U0()),w=!j||zW(j),P=w?null:await vX();if(!w&&P&&!fG)fG=!0,yG.debug("restoring OAuth model costs from models.dev catalog");if(!w&&!P&&!mG)mG=!0,yG.warn("models.dev catalog unavailable; OAuth model costs could not be restored");return Object.fromEntries(Object.entries(L.models).filter(([,k])=>{if(k.options.reasoningMode==="pro")return!1;if(CN.has(k.api.id))return!0;if(_N.has(k.api.id))return!1;let S=k.api.id.match(/^gpt-(\d+\.\d+)/)?.[1];return S?parseFloat(S)>5.4:!1}).map(([k,x])=>[k,{...x,cost:w?{input:0,output:0,cache:{read:0,write:0}}:P?.[x.api.id]??P?.[k]??x.cost,limit:x.id.includes("gpt-5.5")?{context:400000,input:272000,output:128000}:x.id.includes("gpt-5.6")?{context:372000,input:244000,output:128000}:x.limit}]))}},tool:{web_search:_X},auth:{provider:"openai",async loader(L){let Z=await L();if(Z.type!=="oauth")return{};await UW({type:"oauth",access:Z.access??"",refresh:Z.refresh??"",expires:Z.expires??0},U0());let j=await A0(U0()).catch((V)=>{let F=U0();throw Error(`OpenAI auth store at ${F} is corrupt or unreadable: ${V instanceof Error?V.message:String(V)}. Fix or remove it to continue.`,{cause:V})}),w;async function P(){let V=U0();try{let F=AN(V);if(w?.path===V&&w.mtimeMs===F.mtimeMs&&w.size===F.size)return w.storage;let D=await A0(V);return w={path:V,mtimeMs:F.mtimeMs,size:F.size,storage:D},D}catch{return w=void 0,A0(V)}}function k(){w=void 0}if(j&&Z.access){let V=eY({id_token:"",access_token:Z.access,refresh_token:Z.refresh??""});if(V&&V!==j.mainAccountId)await X0((F)=>{return F.mainAccountId=V,F},U0()),j.mainAccountId=V,k()}let x=j?.logging?.level;if(x&&typeof x==="string")DY(x);let S=L0("transport"),d=L0("quota"),m=L0("refresh"),e=L0("accounts");S.info("codex auth loader ready",{codexApiEndpoint:J,transport:w0().rawWebSocket?"raw-websocket":w0().webSockets?"websocket":"http",webSearch:w0().webSearch});let y=new WW({storage:j,fetchQuotaFn:void 0}),s,j1=0,u=new HW({refreshFn:(V)=>b1({refreshToken:V.refreshToken,fetchImpl:V.fetchImpl,now:V.now}),quotaManager:y,onFallbackStorageChanged:k});if(j&&j.accounts.length>0)u.startBackgroundRefresh();let g0=L0("cachekeep"),x1=j?.cachekeep?.enabled===!0,D1=j?.cachekeep?.subagents===!0,g=j?.cachekeep?.sustain===!0,a=BX(j),z0;async function J8(V){await new Promise((F)=>setTimeout(F,V))}async function Q8(V){let F;for(let D=1;D<=hG;D++)try{await Y.client.auth.set({path:{id:"openai"},body:{type:"oauth",refresh:V.refresh,access:V.access,expires:V.expires}});return}catch(R){if(F=R,D<hG)await J8(fN*D)}throw new f9(F)}async function P1(V){await X0((F)=>{return F.refresh=F.refresh??{},V(F),F},U0()),k()}async function VY(V){let F=Date.now()+yN;while(Date.now()<F){await new Promise((I)=>setTimeout(I,vG+uN(vG)));let D=await L();if(D.type!=="oauth"||!D.access)continue;if((D.access!==V.access||D.refresh!==V.refresh||(D.expires??0)>(V.expires??0)+60000)&&(!D.expires||D.expires>Date.now()))return m.debug("joined concurrent main refresh",{pid:process.pid,expiresInMs:D.expires?D.expires-Date.now():void 0}),{access:D.access,refresh:D.refresh??V.refresh??"",expires:D.expires??0}}return null}async function y0(){if(!z0)z0=(async()=>{let V=await L();if(V.type!=="oauth")throw Error("not oauth");if(!V.refresh)throw Error("Token refresh failed: missing refresh token");let F=iG(V.refresh),D=await A0(U0()),R=D?.refresh?.mainLastRefreshError;if(R&&oG(R,V.refresh,Date.now()))throw Error(rG(R,Date.now()));if(D?.refresh?.mainRefreshLeaseUntil&&D.refresh.mainRefreshLeaseUntil>Date.now()&&D.refresh.mainRefreshLeaseTokenHash===F){let M=await VY(V);if(M)return M;throw Error("Codex OAuth refresh is already in progress")}let I=await PY({name:vN,ttlMs:hN,path:U0(),renew:!0});if(!I){let M=await VY(V);if(M)return M;throw Error("Codex OAuth refresh is already in progress")}let T=crypto.randomUUID(),C=F;try{await P1((h)=>{h.refresh=h.refresh??{},h.refresh.mainRefreshLeaseId=T,h.refresh.mainRefreshLeaseUntil=Date.now()+gN,h.refresh.mainRefreshLeaseTokenHash=F});let M=await A0(U0());if(M?.refresh?.mainRefreshLeaseId!==T||M.refresh.mainRefreshLeaseTokenHash!==F)throw Error("Codex OAuth refresh is already in progress");let E=await b1({refreshToken:V.refresh,fetchImpl:fetch,now:Date.now});return await Q8(E),await P1((h)=>{if(h.refresh=h.refresh??{},h.refresh.mainLastRefreshError=void 0,h.refresh.mainRefreshLeaseId===T)h.refresh.mainRefreshLeaseId=void 0,h.refresh.mainRefreshLeaseUntil=void 0,h.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{}),C=void 0,E}catch(M){if(V.refresh&&!v9(M))await P1((E)=>{E.refresh=E.refresh??{},E.refresh.mainLastRefreshError=nG({error:M,now:Date.now(),refreshToken:V.refresh??"",previous:E.refresh.mainLastRefreshError})}).catch(()=>{});throw M}finally{if(C)await P1((M)=>{if(M.refresh?.mainRefreshLeaseId===T&&M.refresh.mainRefreshLeaseTokenHash===C)M.refresh.mainRefreshLeaseId=void 0,M.refresh.mainRefreshLeaseUntil=void 0,M.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await I.release().catch(()=>{})}})().finally(()=>{z0=void 0});return z0}let G1=globalThis;G1.__openaiAuthCacheKeepManager?.stop();let n0=new D8({fetchImpl:fetch,getMainToken:async()=>{let V=await L();if(V.type!=="oauth")throw Error("not oauth");if(!V.access||(V.expires??0)<Date.now())try{return(await y0()).access}catch(F){if(v9(F))throw F;if(V.access)return V.access;throw Error("main token refresh failed")}return V.access},refreshFallback:async(V)=>{let F=await P(),D=F?aN(F.accounts,V):void 0;if(!D)throw Error(`fallback account ${V} not found`);let R=await u.refreshAccount(D,F??{version:1,accounts:[D]});if(!R.access)throw Error(`no access token for ${V}`);return R.access},codexResponsesUrl:J,logger:g0,now:Date.now,getWindow:()=>a,getSustain:()=>g});G1.__openaiAuthCacheKeepManager=n0;async function W1(V,F,D,R,I=!1){if(Object.keys(V).length===0&&!I)return;let T=Date.now(),C=V,M={quota:C,refreshAfter:T+300000,checkedAt:T},E;if(D&&D!=="main"){let b=F?LY(F):null,Y0=b?NY(b):void 0,Z0=y.peekFallbackForPolicy(D)?.quota,b0=pG(C,Z0);M={...M,quota:b0},y.setFallback(D,M,F,I,Y0)}else{if(E=R,!E&&F){let Z0=LY(F);E=Z0?NY(Z0):void 0}if(E&&s&&E!==s){d.debug("stale main quota frame dropped",{pid:process.pid,frameAccountId:E,currentMainIdentity:s});return}let b=y.peekMainForPolicy(E)?.quota,Y0=pG(C,b);M={...M,quota:Y0},y.setMain(F,M,E,I)}d.debug("quota pushed",{pid:process.pid,accountId:D??"main",snapshot:M.quota});let h=await P();await q0(y,h,D&&D!=="main"?h?.mainAccountId:E)}function v1(V,F,D){let R=V==="main"?y.peekMainForPolicy()?.quota:y.peekFallbackForPolicy(V)?.quota;return GW(R,F,Date.now(),mN,D)}let z1=X.experimentalWebSockets?$1.createWebSocketFetch({httpFetch:fetch,rawWebSocket:w0().rawWebSocket,onQuota:(V,F,D,R)=>{W1(V,F,D,!D||D==="main"?R:void 0,!0)},onRateLimitReached:(V,F,D)=>{if(!F)d.warn("mid-stream rate-limit mark missing internal account id; defaulting to main",{pid:process.pid,window:V});let R=F??"main",I=v1(R,V,D);y.markRateLimited(R,I),d.debug("mid-stream rate limit mark",{pid:process.pid,accountId:R,window:V})}}):void 0;if(z1)K.push(z1),W=!0;let B0=LW();N=B0;async function q0(V,F,D=F?.mainAccountId){if(!F)return;await ZW(wW(V,F,Date.now(),D),B0)}async function Q0(V,F,D,R,I){let T={activeId:D,route:R,updatedAt:Date.now()};if(V){if(await X8({sessionId:V,...T},I,B0),F&&F!==V){if(R==="sticky-balanced"){let C=(await L1(B0)).stickyAssignments?.[HY(F)]?.accountId,M=I===void 0||C==="main"||I.some((E)=>E.enabled!==!1&&E.id===C);if(!C||!M)return;await X8({sessionId:F,activeId:C,route:R,updatedAt:Date.now()},I,B0);return}await X8({sessionId:F,...T},I,B0)}return}await OW(T,B0)}H={accountStoragePath:U0(),quotaManager:y,loadAccounts:A0,client:Y.client,cacheKeepManager:n0,setCacheKeepEnabled:(V)=>{x1=V},setCacheKeepSubagents:(V)=>{D1=V},setCacheKeepSustain:(V)=>{g=V},setCacheKeepWindow:(V)=>{a=V},clearStickyRouting:(V)=>jW(V,B0),getStickyRouting:async(V)=>BW(await L1(B0),V),refreshSidebar:async()=>{let V=await A0(U0());await q0(y,V)},refreshAllQuota:async()=>y1({getAuth:L,codexRefreshFn:b1,refreshMainWithLease:y0,fallbackManager:u,quotaManager:y,loadAccounts:A0,writeSidebarState:q0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:U0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:q1,whamFn:Y8})};let k0=null;if(Y.directory){let V=await DW(Y.directory),F=globalThis;if(F.__openaiAuthRpcServer)await F.__openaiAuthRpcServer.stop().catch(()=>{}),F.__openaiAuthRpcServer=void 0;try{k0=await iX({dir:V.dir,secureDir:V.secureDir,sweepRoot:V.sweepRoot,drain:cX,apply:async(D)=>{let R={...H,sessionId:D.sessionId},I=await B8(D.command,D.arguments,R);return{text:I.text,knobs:I.knobs}}}),F.__openaiAuthRpcServer=k0,U=k0}catch{}}async function K1(V,F,D,R,I="main"){let T=lG(V,F);if(T.delete("x-api-key"),T.delete("api-key"),T.set("authorization",`Bearer ${D}`),R)T.set("ChatGPT-Account-Id",R);T.set($1.QUOTA_ACCOUNT_HEADER,I);let C=dG(T),M=C?lN($,C,G):void 0,E=V instanceof URL?V:new URL(typeof V==="string"?V:V.url),h=E.pathname.includes("/v1/responses")||E.pathname.includes("/chat/completions")?new URL(J):E,Y0=sN({init:{...F,headers:T},headers:T,metadata:M,installationID:Q,websocket:Boolean(z1&&E.pathname.endsWith("/responses")),responsesLite:X.responsesLite??!1,dumpSessionID:C}).init,Z0=x1,b0=new Headers(Y0?.headers),$0=VX({enabled:Z0,includeSubagents:D1,headers:b0,body:Y0?.body});if(Z0)g0.trace("cachekeep headers",{pid:process.pid,hasParent:b0.has("x-parent-session-id"),sessionKey:$0?.sessionKey,captured:Boolean($0),affinity:b0.get("x-session-affinity"),opencodeSession:b0.get("x-opencode-session"),sessionId:b0.get("session-id")});if(z1&&E.pathname.endsWith("/responses")){if(S.debug("WS transport",{pid:process.pid,pathname:E.pathname,accountId:I}),$0)n0.track($0.sessionKey,$0.bodyText,I,R,$0.replayHeaders,$0.isSubagent);return z1(h,Y0)}let V0=$1.withoutInternalHeaders(Y0);if(typeof V0?.body!=="string")return fetch(h,V0);if($0)n0.track($0.sessionKey,$0.bodyText,I,R,$0.replayHeaders,$0.isSubagent);S.debug("HTTP transport",{pid:process.pid,pathname:E.pathname,accountId:I});try{let T0=await fetch(h,V0);return await A1({sessionID:C,transport:"http",phase:"http",bodyText:V0.body,accountId:I,url:h.toString(),method:V0.method,headers:V0.headers,status:T0.status}),IX(T0)}catch(T0){throw await A1({sessionID:C,transport:"http",phase:"http",bodyText:V0.body,accountId:I,url:h.toString(),method:V0.method,headers:V0.headers,error:T0 instanceof Error?T0.message:String(T0)}),T0}}function BY(V,F){if((F?.method??(V instanceof Request?V.method:"GET")).toUpperCase()!=="POST")return!1;if(typeof F?.body!=="string")return!1;try{let R=V instanceof URL?V.toString():typeof V==="string"?V:V.url;return new URL(R).pathname.endsWith("/responses")}catch{return!1}}function EW(V){return y.peekMainForPolicy(V)?.quota}function m9(V,F){for(let D of[V?.primary?.checkedAt,V?.secondary?.checkedAt,V?.checkedAt,F])if(typeof D==="number"&&Number.isFinite(D))return D;return}function h1(V,F,D,R,I){let T=m9(V,F),C=m9(D),M=R===I&&D!=null&&(V===void 0||C!==void 0&&(T===void 0||C>T));return{quota:M?D:V,quotaCheckedAt:M?C:T,source:M?"file":"memory"}}function c9(V,F,D,R,I){let T=V?.quota,C=h1(T,V?.checkedAt,F,R,I),M=C.source,E=C.quota;if(!VW(E,D))return{exhausted:!1};let h=NW(E,D);if(!h)return{exhausted:!1};return{exhausted:!0,source:M,...h}}function u9(V,F){d.debug("admission skip: exhausted account",{accountId:V,source:F.source,resetsAt:F.resetsAt})}function MW(V,F="killswitch",D){let R=Date.now(),I=y.getMain()?.quota,T=(V?.accounts??[]).filter((b)=>b.enabled!==!1&&q1(b)).map((b)=>({accountId:b.id,quota:y.getFallback(b.id)?.quota})),C=KW(I,T,R,V);if(F==="quota-exhausted"&&D!==void 0)C=Math.max(1,Math.ceil((D-R)/1000));else if(F==="mid-stream-rate-limit"&&D!==void 0){let b=Math.max(1,Math.ceil((D-R)/1000));C=Math.min(C,b)}let M=Math.floor(C/60),E=C%60,h=F==="mid-stream-rate-limit"?`OpenAI rate limit reached — retrying on another account. Retry in ${M}m ${E}s.`:F==="quota-exhausted"?`OpenAI quota exhausted — retrying on another account. Retry in ${M}m ${E}s.`:`Killswitch: all OpenAI accounts are below their configured quota threshold. Retry in ${M}m ${E}s.`;return new Response(JSON.stringify({error:{message:h,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(C)}})}function p9(V){let F=V?.resetCreditsAvailable;return typeof F==="number"&&Number.isFinite(F)?F:void 0}async function AW(V){let F=KY(V.storage),D=Date.now(),R=y.peekMainForPolicy(V.mainAccountIdentity),I=h1(R?.quota,R?.checkedAt,V.sidebarState.main.quota,V.sidebarState.main.mainAccountId,V.mainAccountIdentity),T=F?UY(R?.quota,V.storage,void 0,D):void 0,C=[{accountId:"main",wireAccountId:V.mainAccountIdentity,access:V.primaryAccess,keepwarmAccountKey:"main",quota:I.quota,quotaCheckedAt:I.quotaCheckedAt,reservePercent:h9(V.storage),configuredOrder:0,resetCreditsApplicable:p9(I.quota),killswitchPasses:T}],M=await u.getUsableFallbackAccounts(V.storage);for(let E of M){if(!E.access)continue;let h=V.sidebarState.fallbacks.find((b0)=>b0.id===E.id),b=y.peekFallbackForPolicy(E.id,E.accountId),Y0=h1(b?.quota,b?.checkedAt,h?.quota,h?.accountId,E.accountId),Z0=F?UY(b?.quota,V.storage,E.id,D):void 0;C.push({accountId:E.id,wireAccountId:E.accountId,access:E.access,keepwarmAccountKey:E.id,fallback:E,quota:Y0.quota,quotaCheckedAt:Y0.quotaCheckedAt,reservePercent:h9(V.storage,E.id),configuredOrder:C.length,resetCreditsApplicable:p9(Y0.quota),killswitchPasses:Z0})}return C}function l9(V,F,D,R,I){let T=KY(I)?V.killswitchPasses:void 0;if(V.accountId==="main"){let h=y.peekMainForPolicy(V.wireAccountId),b=h1(h?.quota,h?.checkedAt,F.main.quota,F.main.mainAccountId,V.wireAccountId);return E8({quota:b.quota,quotaCheckedAt:b.quotaCheckedAt,status:D,now:R,killswitchPasses:T})}let C=F.fallbacks.find((h)=>h.id===V.accountId),M=y.peekFallbackForPolicy(V.accountId,V.wireAccountId),E=h1(M?.quota,M?.checkedAt,C?.quota,C?.accountId,V.wireAccountId);return E8({quota:E.quota,quotaCheckedAt:E.quotaCheckedAt,status:D,now:R,killswitchPasses:T})}function RW(V){return V.accountId==="main"?"main":V.keepwarmAccountKey}function d9(V){return y.isRateLimited(RW(V))}async function $8(V){let F=V.candidates.filter((M)=>!d9(M)),D=new Map(F.map((M)=>[M.accountId,M])),R=Object.fromEntries(F.map((M)=>[M.accountId,M.quotaCheckedAt])),I=new Set(V.excludeAccountIds),T,C=await qW({sessionId:V.sessionId,requestBytes:V.requestBytes,now:V.now,validPinnedAccountIds:[...D.keys()],excludeAccountIds:V.excludeAccountIds,quotaCheckedAtByAccount:R,choose:(M)=>{let E=F.filter((b)=>!I.has(b.accountId));if(E.length===0)return;let h=PX({candidates:E,pendingBytes:M,requestBytes:V.requestBytes,now:V.now,onEmptyWeightedSet:()=>{e.debug("sticky routing: no fresh weighted candidates; using configured order")}});if(!h)return;return T={accountId:h.accountId,source:h.source,pendingBytes:M.get(h.accountId)??0},h}},B0);if(T&&C?.accountId===T.accountId)e.debug("sticky routing: placed session pin",{pid:process.pid,sessionHash:HY(V.sessionId),accountId:T.accountId,source:T.source,requestBytes:V.requestBytes,pendingBytes:T.pendingBytes});return C?D.get(C.accountId):void 0}async function TW(V,F){let D=await u.getUsableFallbackAccounts(V),R=[];for(let b of D)if(b.access)R.push({access:b.access,accountId:b.accountId,keepwarmAccountKey:b.id,quotaAccountId:b.id,fallback:b});let I=R.filter((b)=>!y.isRateLimited(b.quotaAccountId)),T=KY(V)?I.filter((b)=>UY(y.peekFallbackForPolicy(b.quotaAccountId,b.accountId)?.quota,V,b.quotaAccountId,Date.now())):I,C=new Map(F.fallbacks.map((b)=>[b.id,{quota:b.quota,accountId:b.accountId}])),M=[],E=[],h=Date.now();for(let b of T){let Y0=C.get(b.quotaAccountId),Z0=c9(y.peekFallbackForPolicy(b.quotaAccountId,b.accountId),Y0?.quota,h,Y0?.accountId,b.accountId);if(Z0.exhausted)E.push({candidate:b,decision:Z0});else M.push(b)}return{current:T,retained:M,skipped:E}}function i9(V,F){if(V.retained.length===0&&!F)return V.current;for(let{candidate:D,decision:R}of V.skipped)u9(D.quotaAccountId,R);return V.retained}async function n9(V,F){try{let D=E1(V.headers);await W1(D,F.access,F.quotaAccountId,void 0,WY(V.headers))}catch{}}async function CW(V,F,D,R){for(let I of R){let T;try{T=await K1(V,F,I.access,I.accountId,I.keepwarmAccountKey)}catch(C){if(C instanceof DOMException&&C.name==="AbortError")throw C;if(F?.signal?.aborted)throw C;throw e.debug("fallback-first transport failed; request not replayed",{pid:process.pid,accountId:I.quotaAccountId}),C}if(!zY(T.status,D))return await u.markUsed(I.fallback),{response:T,accessToken:I.access,quotaAccountId:I.quotaAccountId,activeId:I.keepwarmAccountKey};await n9(T,I),T.body?.cancel().catch(()=>{})}return}async function _W(V,F,D,R,I){if(!BY(V,F))return{response:D};if(!I.length)return{response:D};let T=D,C;for(let M of I){let E;try{E=await K1(V,F,M.access,M.accountId,M.keepwarmAccountKey)}catch(h){if(h instanceof DOMException&&h.name==="AbortError")throw h;if(F?.signal?.aborted)throw h;return e.debug("reactive fallback candidate threw; stopping",{pid:process.pid,accountId:M.quotaAccountId}),{response:T,...C}}if(T.body?.cancel().catch(()=>{}),T=E,C={accessToken:M.access,accountId:M.quotaAccountId},!zY(E.status,R))return await u.markUsed(M.fallback),{response:E,...C};await n9(E,M)}return{response:T,...C}}if(!gG){if(gG=!0,j){let V=[];for(let F of j.accounts)if(q1(F))V.push(F);y.seedFallbacksFromAccounts(V)}q0(y,j).catch(()=>{}),y1({getAuth:L,codexRefreshFn:b1,refreshMainWithLease:y0,fallbackManager:u,quotaManager:y,loadAccounts:A0,writeSidebarState:q0,client:Y.client,fetchImpl:fetch,now:Date.now,configPath:U0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:q1,whamFn:Y8,respectBackoff:!0}).catch((V)=>d.warn("boot quota seed failed",{pid:process.pid,error:o0(V)}))}return O.start(async()=>{let F=(await KX({getAuth:L,codexRefreshFn:b1,refreshMainWithLease:y0,fallbackManager:u,quotaManager:y,loadAccounts:A0,writeSidebarState:(D,R)=>O.isStopped()?Promise.resolve():q0(D,R),client:Y.client,fetchImpl:fetch,now:Date.now,configPath:U0(),storageMainAccountId:j?.mainAccountId,isOAuthAccountFn:q1,whamFn:Y8,readSidebarState:()=>L1(B0)})).filter((D)=>!D.ok);if(F.length>0)d.warn("background quota refresh completed with failures",{pid:process.pid,failures:F})},(V)=>{d.warn("background quota refresh failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}),{apiKey:SN,async fetch(V,F){let D=lG(V,F),R=dG(D),I=D.get("x-parent-session-id")?.trim()||void 0,T=await P(),C=await L(),M=++j1;if(C.type!=="oauth")return fetch(V,F);F=await tN(V,F);let E=C.access??"";if(!C.access||(C.expires??0)<Date.now()){m.debug("token refresh triggered",{pid:process.pid,hasAccess:Boolean(C.access),expiresInMs:C.expires?C.expires-Date.now():void 0});try{let t=await y0();C.access=t.access,C.refresh=t.refresh,C.expires=t.expires}catch(t){if(v9(t))throw t}}E=C.access??"";let b=C.accountId??(E?NY(LY(E)??{}):void 0);if(M===j1)s=b;let Y0=T?.routing?.mode??"main-first",Z0,$0=await(()=>{return Z0??=L1(B0),Z0})();if(Y0==="sticky-balanced"&&R&&BY(V,F)&&typeof F?.body==="string"){let t=Buffer.byteLength(F.body,"utf8"),H0=await AW({storage:T,sidebarState:$0,primaryAccess:E,mainAccountIdentity:b}),K0=await $8({sessionId:R,requestBytes:t,candidates:H0,now:Date.now()});if(K0){let YX=d9(K0)?{action:"migrate",reason:"exhausted"}:l9(K0,$0,void 0,Date.now(),T);if(YX.action==="migrate"){let P0=await $8({sessionId:R,requestBytes:t,candidates:H0,excludeAccountIds:[K0.accountId],now:Date.now()});if(P0)e.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:HY(R),fromAccountId:K0.accountId,toAccountId:P0.accountId,reason:YX.reason}),K0=P0}let x0=await K1(V,F,K0.access,K0.wireAccountId,K0.keepwarmAccountKey),XX=async(P0,U1)=>{try{let IW=E1(P0.headers);await W1(IW,U1.access,U1.accountId==="main"?void 0:U1.accountId,U1.accountId==="main"?U1.wireAccountId:void 0,WY(P0.headers))}catch{}};await XX(x0,K0);let JX=l9(K0,$0,x0.status,Date.now(),T);if((x0.status===401||x0.status===403||x0.status===429)&&JX.action==="migrate"){let P0=await $8({sessionId:R,requestBytes:t,candidates:H0,excludeAccountIds:[K0.accountId],now:Date.now()});if(P0){e.debug("sticky routing: migrated session pin",{pid:process.pid,sessionHash:HY(R),fromAccountId:K0.accountId,toAccountId:P0.accountId,reason:JX.reason});let U1=x0;x0=await K1(V,F,P0.access,P0.wireAccountId,P0.keepwarmAccountKey),U1.body?.cancel().catch(()=>{}),K0=P0,await XX(x0,K0)}}if(K0.fallback&&!zY(x0.status,T))await u.markUsed(K0.fallback);return await Q0(R,I,K0.accountId,Y0,T?.accounts).catch(()=>{}),x0}}let V0=c9(y.peekMainForPolicy(b),$0.main.quota,Date.now(),$0.main.mainAccountId,b),T0=KY(T)&&!UY(EW(b),T,void 0,Date.now()),ZY=y.isRateLimited("main"),o9,G8=()=>{return o9??=TW(T,$0),o9},f0,w1,r9=!1,OY;if(Y0==="fallback-first"&&BY(V,F)){r9=!0;let t=await G8();OY=i9(t,!T0&&!ZY&&!V0.exhausted);let H0=await CW(V,F,T,OY);if(H0)f0=H0.response,w1={accessToken:H0.accessToken,accountId:H0.quotaAccountId,activeId:H0.activeId}}if(!f0){let t=V0.exhausted&&BY(V,F)&&(await G8()).retained.length>0;if(T0||ZY||t){let H0=T0?"killswitch":ZY?"mid-stream-rate-limit":"quota-exhausted";if(H0==="quota-exhausted"&&V0.exhausted)u9("main",V0);e.debug("admission blocked primary",{pid:process.pid,activeId:"main",reason:H0}),f0=MW(T,H0,H0==="quota-exhausted"&&V0.exhausted?V0.resetAtMs:ZY?y.rateLimitedUntil("main"):void 0)}else f0=await K1(V,F,E,b,"main")}let s9=Boolean(w1),g1=f0,a9=w1?.accessToken??E,t9=w1?.accountId,e9=w1?.activeId??"main";if(!w1&&!r9&&zY(f0.status,T)){e.debug("reactive fallback triggered",{pid:process.pid,status:f0.status}),OY??=i9(await G8(),!1);let t=await _W(V,F,f0,T,OY),H0=t.response;if(H0!==f0){if(s9=!0,g1=H0,a9=t.accessToken??E,t9=t.accountId,t.accountId)e9=t.accountId}}try{let t=E1(g1.headers);if(s9)await W1(t,a9,t9,void 0,WY(g1.headers));else await W1(t,E,void 0,b,WY(g1.headers))}catch{}return await Q0(R,I,e9,Y0,T?.accounts).catch(()=>{}),g1},async dispose(){if(O.stop(),n0.stop(),G1.__openaiAuthCacheKeepManager===n0)G1.__openaiAuthCacheKeepManager=void 0;if(u.stopBackgroundRefresh(),U){await U.stop().catch(()=>{});let V=globalThis;if(V.__openaiAuthRpcServer===U)V.__openaiAuthRpcServer=void 0;U=null}}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:L}=await XW(),Z=await tG(),j=aG(crypto.getRandomValues(new Uint8Array(32)).buffer),w=eG(L,Z,j),P=JW(Z,j);return{url:w,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let k=await P,x=eY(k);return{type:"success",refresh:k.refresh_token,access:k.access_token,expires:Date.now()+(k.expires_in??3600)*1000,accountId:x}}finally{YW(j)}}}}},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:async()=>{let{deviceData:L,url:Z,instructions:j}=await QW();return{url:Z,instructions:j,method:"auto",async callback(){try{let w=await $W(L);return{type:"success",refresh:w.refresh_token,access:w.access_token,expires:Date.now()+(w.expires_in??3600)*1000,accountId:eY(w)}}catch{return{type:"failed"}}}}}},{label:"Manually enter API Key",type:"api"}]},"chat.headers":async(L,Z)=>{if(L.model.providerID!=="openai")return;if(Z.headers.originator="opencode",Z.headers["User-Agent"]=`${sG} (${x9.platform()} ${x9.release()}; ${x9.arch()})`,Z.headers["session-id"]=L.sessionID,W&&L.agent==="title")Z.headers[$1.TITLE_HEADER]="true"},"chat.params":async(L,Z)=>{if(L.model.providerID!=="openai")return;Z.maxOutputTokens=void 0},config:async(L)=>{L.command={...L.command??{},[z8]:{template:z8,description:"Show current OpenAI Codex OAuth quota usage for all accounts."},[K8]:{template:K8,description:"Manage OpenAI accounts — add, switch, remove, or reorder."},[U8]:{template:U8,description:"Show or change OpenAI account routing between main-first, fallback-first, and sticky-balanced."},[H8]:{template:H8,description:"Manage killswitch — hard-block requests when quota drops below per-account thresholds."},[L8]:{template:L8,description:"Show or toggle OpenAI Codex request dump capture for debugging."},[N8]:{template:N8,description:"Show or change the plugin log level (error, warn, info, debug, trace)."},[V8]:{template:V8,description:"Keep Codex prompt cache alive during idle by shadow-replaying the last request."}}},"command.execute.before":async(L)=>{if(!zX.includes(L.command))return;if(!H)await B(L.sessionID,"OpenAI auth plugin is still initializing. Send a request first, then try again."),cG();let Z=L.command,j={...H,sessionId:L.sessionID,notify:(P)=>{b8(P,L.sessionID)}},w=await B8(Z,L.arguments,j);if(uX(L.sessionID))b8(w,L.sessionID);else await B(L.sessionID,w.text);cG()}}}var GV=async(Y)=>{let X=w0();return $V(Y,{codexApiEndpoint:X.codexApiEndpoint,experimentalWebSockets:X.webSockets,responsesLite:X.responsesLite})},L4={id:"cortexkit-openai-auth",server:GV};export{dG as resolveSidebarSessionId,LY as parseJwtClaims,pG as mergePushedQuotaMetadata,aN as findCachekeepFallbackAccount,NY as extractAccountIdFromClaims,L4 as default,H4 as buildSidebarState,wW as buildSidebarMachineState,GV as OpenAIAuthPlugin,hN as MAIN_REFRESH_LOCK_TTL_MS,gN as MAIN_REFRESH_LEASE_TTL_MS,$V as CodexAuthPlugin,f9 as AuthPersistError};