context-mode 1.0.162 → 1.0.163
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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.openclaw-plugin/openclaw.plugin.json +1 -1
- package/.openclaw-plugin/package.json +1 -1
- package/README.md +142 -28
- package/bin/statusline.mjs +24 -4
- package/build/adapters/antigravity/index.d.ts +1 -1
- package/build/adapters/antigravity-cli/index.d.ts +51 -0
- package/build/adapters/antigravity-cli/index.js +341 -0
- package/build/adapters/claude-code/hooks.d.ts +1 -0
- package/build/adapters/claude-code/hooks.js +3 -0
- package/build/adapters/claude-code/index.js +24 -5
- package/build/adapters/client-map.js +5 -0
- package/build/adapters/codex/hooks.d.ts +5 -1
- package/build/adapters/codex/hooks.js +5 -1
- package/build/adapters/codex/index.d.ts +9 -1
- package/build/adapters/codex/index.js +87 -5
- package/build/adapters/copilot-cli/hooks.d.ts +33 -0
- package/build/adapters/copilot-cli/hooks.js +64 -0
- package/build/adapters/copilot-cli/index.d.ts +48 -0
- package/build/adapters/copilot-cli/index.js +341 -0
- package/build/adapters/detect.d.ts +1 -1
- package/build/adapters/detect.js +71 -3
- package/build/adapters/openclaw/mcp-tools.js +1 -1
- package/build/adapters/opencode/index.js +31 -17
- package/build/adapters/opencode/zod3tov4.js +27 -6
- package/build/adapters/pi/extension.d.ts +2 -12
- package/build/adapters/pi/extension.js +114 -96
- package/build/adapters/types.d.ts +5 -4
- package/build/adapters/types.js +4 -3
- package/build/cache-heal.d.ts +48 -0
- package/build/cache-heal.js +150 -0
- package/build/cli.js +37 -97
- package/build/executor.d.ts +25 -0
- package/build/executor.js +143 -22
- package/build/opencode-plugin.js +5 -2
- package/build/routing-block.d.ts +8 -0
- package/build/routing-block.js +86 -0
- package/build/runtime.d.ts +0 -36
- package/build/runtime.js +107 -27
- package/build/search/flood-guard.d.ts +57 -0
- package/build/search/flood-guard.js +80 -0
- package/build/security.d.ts +8 -3
- package/build/security.js +155 -29
- package/build/server.d.ts +14 -0
- package/build/server.js +368 -350
- package/build/session/analytics.d.ts +1 -1
- package/build/session/analytics.js +5 -1
- package/build/session/db.js +23 -3
- package/build/session/extract.js +8 -0
- package/build/store.d.ts +1 -1
- package/build/store.js +139 -25
- package/build/tool-naming.d.ts +4 -0
- package/build/tool-naming.js +24 -0
- package/build/util/jsonc.d.ts +14 -0
- package/build/util/jsonc.js +104 -0
- package/cli.bundle.mjs +254 -252
- package/configs/antigravity/GEMINI.md +2 -2
- package/configs/antigravity-cli/hooks/hooks.json +37 -0
- package/configs/antigravity-cli/hooks.json +37 -0
- package/configs/antigravity-cli/mcp_config.json +10 -0
- package/configs/antigravity-cli/plugin.json +14 -0
- package/configs/antigravity-cli/rules/context-mode.md +77 -0
- package/configs/antigravity-cli/skills/context-mode/SKILL.md +77 -0
- package/configs/claude-code/CLAUDE.md +2 -2
- package/configs/codex/AGENTS.md +2 -2
- package/configs/copilot-cli/.github/plugin/plugin.json +23 -0
- package/configs/copilot-cli/.mcp.json +12 -0
- package/configs/copilot-cli/README.md +47 -0
- package/configs/copilot-cli/hooks.json +41 -0
- package/configs/copilot-cli/skills/context-mode/SKILL.md +38 -0
- package/configs/gemini-cli/GEMINI.md +2 -2
- package/configs/jetbrains-copilot/copilot-instructions.md +2 -2
- package/configs/kilo/AGENTS.md +2 -2
- package/configs/kiro/KIRO.md +2 -2
- package/configs/omp/SYSTEM.md +2 -2
- package/configs/openclaw/AGENTS.md +2 -2
- package/configs/opencode/AGENTS.md +2 -2
- package/configs/qwen-code/QWEN.md +2 -2
- package/configs/vscode-copilot/copilot-instructions.md +2 -2
- package/configs/zed/AGENTS.md +2 -2
- package/hooks/antigravity-cli/payload.mjs +98 -0
- package/hooks/antigravity-cli/posttooluse.mjs +138 -0
- package/hooks/antigravity-cli/pretooluse.mjs +78 -0
- package/hooks/antigravity-cli/stop.mjs +58 -0
- package/hooks/codex/pretooluse.mjs +14 -4
- package/hooks/codex/stop.mjs +12 -4
- package/hooks/copilot-cli/posttooluse.mjs +79 -0
- package/hooks/copilot-cli/precompact.mjs +66 -0
- package/hooks/copilot-cli/pretooluse.mjs +41 -0
- package/hooks/copilot-cli/sessionstart.mjs +121 -0
- package/hooks/copilot-cli/stop.mjs +59 -0
- package/hooks/copilot-cli/userpromptsubmit.mjs +77 -0
- package/hooks/core/codex-caps.mjs +112 -0
- package/hooks/core/formatters.mjs +158 -7
- package/hooks/core/mcp-ready.mjs +37 -8
- package/hooks/core/routing.mjs +94 -8
- package/hooks/core/tool-naming.mjs +3 -0
- package/hooks/hooks.json +12 -1
- package/hooks/pretooluse.mjs +6 -2
- package/hooks/routing-block.mjs +2 -2
- package/hooks/security.bundle.mjs +2 -1
- package/hooks/session-db.bundle.mjs +5 -5
- package/hooks/session-directive.mjs +88 -20
- package/hooks/session-extract.bundle.mjs +1 -1
- package/hooks/session-helpers.mjs +21 -0
- package/hooks/sessionstart.mjs +37 -5
- package/hooks/stop.mjs +49 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +4 -10
- package/scripts/install-antigravity-cli-plugin.mjs +141 -0
- package/server.bundle.mjs +208 -203
- package/skills/ctx-insight/SKILL.md +12 -17
- package/build/util/db-lock.d.ts +0 -65
- package/build/util/db-lock.js +0 -166
- package/insight/index.html +0 -13
- package/insight/package.json +0 -55
- package/insight/server.mjs +0 -1265
- package/insight/src/components/analytics.tsx +0 -112
- package/insight/src/components/ui/badge.tsx +0 -52
- package/insight/src/components/ui/button.tsx +0 -58
- package/insight/src/components/ui/card.tsx +0 -103
- package/insight/src/components/ui/chart.tsx +0 -371
- package/insight/src/components/ui/collapsible.tsx +0 -19
- package/insight/src/components/ui/input.tsx +0 -20
- package/insight/src/components/ui/progress.tsx +0 -83
- package/insight/src/components/ui/scroll-area.tsx +0 -55
- package/insight/src/components/ui/separator.tsx +0 -23
- package/insight/src/components/ui/table.tsx +0 -114
- package/insight/src/components/ui/tabs.tsx +0 -82
- package/insight/src/components/ui/tooltip.tsx +0 -64
- package/insight/src/lib/api.ts +0 -144
- package/insight/src/lib/utils.ts +0 -6
- package/insight/src/main.tsx +0 -22
- package/insight/src/routeTree.gen.ts +0 -189
- package/insight/src/router.tsx +0 -19
- package/insight/src/routes/__root.tsx +0 -55
- package/insight/src/routes/enterprise.tsx +0 -316
- package/insight/src/routes/index.tsx +0 -1482
- package/insight/src/routes/knowledge.tsx +0 -221
- package/insight/src/routes/knowledge_.$dbHash.$sourceId.tsx +0 -137
- package/insight/src/routes/search.tsx +0 -97
- package/insight/src/routes/sessions.tsx +0 -179
- package/insight/src/routes/sessions_.$dbHash.$sessionId.tsx +0 -181
- package/insight/src/styles.css +0 -104
- package/insight/tsconfig.json +0 -29
- package/insight/vite.config.ts +0 -19
package/cli.bundle.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}function Ei(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),t.csharp&&e.push("csharp"),e}function Ld(t,e,r){switch(e){case"javascript":if(!t.javascript)throw new Error("No JavaScript runtime available. Install Node.js or Bun on PATH (the host process is not itself a JS runtime).");return Px.test(Dd(t.javascript))?[t.javascript,"run",r]:[t.javascript,r];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return Px.test(Dd(t.typescript))?[t.typescript,"run",r]:t.typescript==="tsx"?["tsx",r]:["ts-node",r];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,r];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let i=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${i}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-NoProfile","-ExecutionPolicy","Bypass","-File",r];let s=o.split(/[\\/]/).pop()??o;if(s==="cmd"||s==="cmd.exe")return[t.shell,"/d","/s","/c",r]}return[t.shell,r]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,r];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",r];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",r]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",r];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",r];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,r];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",r];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,r]}}var OC,Px,ki,zt,Xo=S(()=>{"use strict";Cr();OC=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,Px=/^bun(\.exe)?$/i;ki=process.platform==="win32";zt=null});function MC(t){let e=[];if(t&&typeof t=="object"){let r=t.command;typeof r=="string"&&e.push(r);let n=t.hooks;if(Array.isArray(n)){for(let o of n)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function jC(t){let e=gc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function _c(t,e){let r=new Set,n=t.generateHookConfig(e);for(let o of Object.values(n))if(Array.isArray(o))for(let s of o)for(let i of MC(s)){let a=jC(i);a&&r.add(a)}return[...r]}var zd=S(()=>{"use strict";Cr()});var Nx,Dx=S(()=>{"use strict";Nx={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code","kimi-code":"kimi",kimi:"kimi","Kimi Code":"kimi"}});var Ud={};we(Ud,{BunSQLiteAdapter:()=>xc,NodeSQLiteAdapter:()=>bc,SQLiteBase:()=>Ti,applyWALPragmas:()=>es,cleanOrphanedWALFiles:()=>ts,closeDB:()=>rs,defaultDBPath:()=>Hd,deleteDBFiles:()=>vc,hasModernSqlite:()=>Lx,isSQLiteCorruptionError:()=>Sc,loadDatabase:()=>rt,nodeSqliteHasFts5:()=>jx,renameCorruptDB:()=>zx,withRetry:()=>xn});import{createRequire as LC}from"node:module";import{existsSync as zC,unlinkSync as Mx,renameSync as FC}from"node:fs";import{tmpdir as HC}from"node:os";import{join as UC}from"node:path";function jx(t){let e=null;try{return e=new t(":memory:"),e.exec("CREATE VIRTUAL TABLE __fts5_probe USING fts5(x)"),!0}catch{return!1}finally{try{e?.close()}catch{}}}function Lx(t,e){let r=e!==void 0?e:globalThis.Bun;if(typeof r<"u"&&r!==null)return!0;let n=t??process.versions,[o,s]=(n.node??"0.0.0").split("."),i=Number(o),a=Number(s);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function rt(){if(!Qo){let t=LC(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;Qo=function(n,o){let s=new e(n,{readonly:o?.readonly,create:!0}),i=new xc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(Lx()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&jx(e)?Qo=function(n,o){let s=new e(n,{readOnly:o?.readonly??!1}),i=new bc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:Qo=t("better-sqlite3")}else Qo=t("better-sqlite3")}return Qo}function es(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function ts(t){if(!zC(t))for(let e of["-wal","-shm"])try{Mx(t+e)}catch{}}function vc(t){for(let e of["","-wal","-shm"])try{Mx(t+e)}catch{}}function rs(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function Hd(t="context-mode"){return UC(HC(),`${t}-${process.pid}.db`)}function xn(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(r=o instanceof Error?o:new Error(s),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function Sc(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function zx(t){let e=Date.now();for(let r of["","-wal","-shm"])try{FC(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var xc,bc,Qo,$i,Fd,Ti,bn=S(()=>{"use strict";xc=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){let r="",n=null;for(let s=0;s<e.length;s++){let i=e[s];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let o=r.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let o=r.get(...n);return o===null?void 0:o},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},bc=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},Qo=null;$i=Symbol.for("__context_mode_live_dbs_v3__"),Fd=(()=>{let t=globalThis;return t[$i]||(t[$i]=new Set,process.on("exit",()=>{for(let e of t[$i])rs(e);t[$i].clear()})),t[$i]})(),Ti=class{#e;#t;constructor(e){let r=rt();this.#e=e,ts(e);let n;try{n=new r(e,{timeout:3e4}),es(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(Sc(s)){zx(e),ts(e);try{n=new r(e,{timeout:3e4}),es(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=n,Fd.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){Fd.delete(this.#t),rs(this.#t)}withRetry(e){return xn(e)}cleanup(){Fd.delete(this.#t),rs(this.#t),vc(this.#e)}}});var Qx={};we(Qx,{SessionDB:()=>Gt,StorageDirectoryError:()=>Kt,_resetWorktreeSuffixCacheForTests:()=>sO,applyMissingSessionEventsColumns:()=>qd,clearStorageDirectoryCheckCacheForTests:()=>QC,describeStorageDirectorySource:()=>Ri,ensureSessionEventsSchema:()=>Vd,ensureWritableStorageDir:()=>Ir,formatStorageDirectoryError:()=>is,getWorktreeSuffix:()=>Ci,hashProjectDirCanonical:()=>nt,hashProjectDirLegacy:()=>Ar,normalizeWorktreePath:()=>as,resolveContentStorageDir:()=>Sn,resolveContentStorePath:()=>Zd,resolveDefaultSessionDir:()=>$c,resolveSessionDbPath:()=>cs,resolveSessionPath:()=>Yx,resolveSessionStorageDir:()=>Jr,resolveStatsStorageDir:()=>ss});import{createHash as Pi}from"node:crypto";import{execFileSync as BC}from"node:child_process";import{accessSync as ZC,constants as qC,existsSync as Ec,mkdirSync as VC,realpathSync as WC,renameSync as Bd}from"node:fs";import{homedir as qx}from"node:os";import{dirname as KC,isAbsolute as Vx,join as vn,resolve as os}from"node:path";function $c(t){let e=t.env??process.env,r=t.legacySessionDirEnv,n=r?e[r]?.trim():void 0;return n&&r?(t.onLegacySessionDir?.(r,n),n):vn(GC(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function GC(t,e,r){let n=e?r[e]:void 0;return n&&n.trim()!==""?Hx(n.trim()):Hx(t,qx())}function Hx(t,e){return t.startsWith("~")?os(qx(),t.replace(/^~[/\\]?/,"")):Vx(t)?os(t):e?os(e,t):os(t)}function JC(t,e,r){return new Kt(t,e,Or,void 0,[`Invalid ${Or} for context-mode ${t} directory: ${r}`,Jx()].join(`
|
|
4
|
-
`))}function
|
|
5
|
-
`)}function
|
|
2
|
+
var FC=Object.create;var Dd=Object.defineProperty;var HC=Object.getOwnPropertyDescriptor;var UC=Object.getOwnPropertyNames;var BC=Object.getPrototypeOf,ZC=Object.prototype.hasOwnProperty;var v=(t,e)=>()=>(t&&(e=t(t=0)),e);var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),_e=(t,e)=>{for(var n in e)Dd(t,n,{get:e[n],enumerable:!0})},qC=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of UC(e))!ZC.call(t,o)&&o!==n&&Dd(t,o,{get:()=>e[o],enumerable:!(r=HC(e,o))||r.enumerable});return t};var xi=(t,e,n)=>(n=t!=null?FC(BC(t)):{},qC(e||!t||!t.__esModule?Dd(n,"default",{value:t,enumerable:!0}):n,t));var Ud=L((V4,Hx)=>{"use strict";var Hd={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let n="";return t<0?n+=`\x1B[${-t}D`:t>0&&(n+=`\x1B[${t}C`),e<0?n+=`\x1B[${-e}A`:e>0&&(n+=`\x1B[${e}B`),n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},tO={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},nO={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?Hd.up():"");return t&&(e+=Hd.left),e}};Hx.exports={cursor:Hd,scroll:tO,erase:nO,beep:"\x07"}});var Kx=L((P9,Kd)=>{var bc=process||{},Vx=bc.argv||[],xc=bc.env||{},$O=!(xc.NO_COLOR||Vx.includes("--no-color"))&&(!!xc.FORCE_COLOR||Vx.includes("--color")||bc.platform==="win32"||(bc.stdout||{}).isTTY&&xc.TERM!=="dumb"||!!xc.CI),PO=(t,e,n=t)=>r=>{let o=""+r,s=o.indexOf(e,t.length);return~s?t+RO(o,e,n,s)+e:t+o+e},RO=(t,e,n,r)=>{let o="",s=0;do o+=t.substring(s,r)+n,s=r+e.length,r=t.indexOf(e,s);while(~r);return o+t.substring(s)},Wx=(t=$O)=>{let e=t?PO:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};Kd.exports=Wx();Kd.exports.createColors=Wx});function vi(t,e){let n=process.execPath.replace(/\\/g,"/");if(Jr(e?.platform)){let o=n.split("/").pop().replace(/\.exe$/i,"");Gd.has(o)||(n=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let r=t.replace(/\\/g,"/");return`"${n}" "${r}"`}function Ke(t,e){if(Jr(e?.platform))return vi(t,e);let r=Jd().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${r}" "${o}"`}function Sc(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}function Jr(t){return!!t&&CO.has(t)}var Gd,CO,Rn=v(()=>{"use strict";Yo();Gd=new Set(["node","bun","deno"]),CO=new Set(["opencode","kilo"])});var tb={};_e(tb,{buildCommand:()=>tp,detectRuntimes:()=>Xr,getAvailableLanguages:()=>Ei,getRuntimeSummary:()=>wi,hasBunRuntime:()=>hr,isAllowlistedShell:()=>Jx,resetHookRuntimeCache:()=>MO,resolveHookRuntime:()=>Jd,resolveJavascriptRuntime:()=>eb});import{execFileSync as Qd,execSync as Qo}from"node:child_process";import{existsSync as es}from"node:fs";function Yd(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function Jx(t){return OO.test(Yd(t))}function IO(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function AO(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\cmd\.exe$/.test(e)}function Ge(t){try{let e=ki?`where ${t}`:`command -v ${t}`;return Qo(e,{stdio:"pipe"}),!0}catch{return!1}}function Xd(t){if(ki)try{let n=Qo(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(n.length===0||n.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!Ge(t))return!1;try{return ki?Qo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):Qd(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function ep(){if(Ge("bun"))return!0;for(let t of Yx())if(es(t))return!0;return!1}function Xx(){for(let e of Yx())if(es(e))return e;if(Ge("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return ki?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Yx(){let t=process.env.HOME??process.env.USERPROFILE??"";if(ki){let e=process.env.LOCALAPPDATA??"",n=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...n?[`${n}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function Qx(){let t;try{t=Qo("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean)}catch{return null}for(let e of t){let n=e.toLowerCase();if(!(n.includes("system32")||n.includes("windowsapps"))){for(let r of NO)if(es(r))return r;return e}}return null}function DO(t=Qx()){return t??(Ge("sh")?"sh":Ge("pwsh")?"pwsh":Ge("powershell")?"powershell":"cmd.exe")}function Wt(t,e=["--version"]){try{if(process.platform==="win32"){let n=[t,...e].map(r=>/[\s"&|<>^()%!]/.test(r)?JSON.stringify(r):r).join(" ");return Qo(n,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return Qd(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function eb(t,e={}){if(t)return t;let n=e.execPath??process.execPath,r=e.commandExists??Ge,o=n.split(/[\\/]/).pop().replace(/\.exe$/i,"");return Gd.has(o)&&es(n)?n:r("node")?"node":null}function Xr(){let e=ep()?Xx():null,n=process.env.SHELL,r=process.platform==="win32",o=r?Qx():null,s=n&&es(n)&&Jx(n)&&!(r&&IO(n))&&!(r&&o&&AO(n))?n:null;return{javascript:eb(e),typescript:e||(Ge("tsx")?"tsx":Ge("ts-node")?"ts-node":null),python:Xd("python3")?"python3":Xd("python")?"python":Xd("py")?"py":null,shell:s??(r?DO(o):Ge("bash")?"bash":"sh"),ruby:Ge("ruby")?"ruby":null,go:Ge("go")?"go":null,rust:Ge("rustc")?"rustc":null,php:Ge("php")?"php":null,perl:Ge("perl")?"perl":null,r:Ge("Rscript")?"Rscript":Ge("r")?"r":null,elixir:Ge("elixir")?"elixir":null,csharp:Ge("dotnet-script")?"dotnet-script":null}}function hr(){return ep()}function MO(){Ft=null}function jO(t){let e=t.trim(),n=/^(\d+)\.(\d+)\.(\d+)/.exec(e);if(!n)return!1;let r=Number(n[1]);return Number.isFinite(r)&&r>=1}function LO(){return es(process.execPath)?{path:process.execPath,isBun:!1}:Ge("node")?{path:"node",isBun:!1}:{path:process.execPath,isBun:!1}}function Jd(){if(Ft)return Ft;let t=LO();try{if(!ep())return Ft=t,Ft;let e=Xx(),n;try{if(process.platform==="win32"){let r=Qo(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}else{let r=Qd(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}}catch{return Ft=t,Ft}return jO(n)?(Ft={path:e,isBun:!0},Ft):(Ft=t,Ft)}catch{return Ft=t,Ft}}function wi(t){let e=[],n=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${Wt(t.javascript)})${n?" \u26A1":""}`):e.push(" JavaScript: not available (install node or bun \u2014 host process is not a JS runtime)"),t.typescript?e.push(` TypeScript: ${t.typescript} (${Wt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Wt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Wt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Wt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Wt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Wt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Wt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Wt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Wt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Wt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Wt(t.csharp)})`),n||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
|
|
3
|
+
`)}function Ei(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),t.csharp&&e.push("csharp"),e}function tp(t,e,n){switch(e){case"javascript":if(!t.javascript)throw new Error("No JavaScript runtime available. Install Node.js or Bun on PATH (the host process is not itself a JS runtime).");return Gx.test(Yd(t.javascript))?[t.javascript,"run",n]:[t.javascript,n];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return Gx.test(Yd(t.typescript))?[t.typescript,"run",n]:t.typescript==="tsx"?["tsx",n]:["ts-node",n];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,n];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let i=n.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${i}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-NoProfile","-ExecutionPolicy","Bypass","-File",n];let s=o.split(/[\\/]/).pop()??o;if(s==="cmd"||s==="cmd.exe")return[t.shell,"/d","/s","/c",n]}return[t.shell,n]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,n];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",n];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",n]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",n];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",n];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,n];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",n];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,n]}}var OO,Gx,ki,NO,Ft,Yo=v(()=>{"use strict";Rn();OO=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,Gx=/^bun(\.exe)?$/i;ki=process.platform==="win32";NO=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];Ft=null});function zO(t){let e=[];if(t&&typeof t=="object"){let n=t.command;typeof n=="string"&&e.push(n);let r=t.hooks;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function FO(t){let e=Sc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function vc(t,e){let n=new Set,r=t.generateHookConfig(e);for(let o of Object.values(r))if(Array.isArray(o))for(let s of o)for(let i of zO(s)){let a=FO(i);a&&n.add(a)}return[...n]}var np=v(()=>{"use strict";Rn()});var nb,rb=v(()=>{"use strict";nb={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","antigravity-cli":"antigravity-cli",agy:"antigravity-cli","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","copilot-cli":"copilot-cli","GitHub Copilot CLI":"copilot-cli","github-copilot-cli":"copilot-cli","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code","kimi-code":"kimi",kimi:"kimi","Kimi Code":"kimi"}});var sp={};_e(sp,{BunSQLiteAdapter:()=>kc,NodeSQLiteAdapter:()=>wc,SQLiteBase:()=>$i,applyWALPragmas:()=>ns,cleanOrphanedWALFiles:()=>rs,closeDB:()=>os,defaultDBPath:()=>op,deleteDBFiles:()=>Ec,hasModernSqlite:()=>ib,isSQLiteCorruptionError:()=>Tc,loadDatabase:()=>nt,nodeSqliteHasFts5:()=>sb,renameCorruptDB:()=>ab,withRetry:()=>gr});import{createRequire as HO}from"node:module";import{existsSync as UO,unlinkSync as ob,renameSync as BO}from"node:fs";import{tmpdir as ZO}from"node:os";import{join as qO}from"node:path";function sb(t){let e=null;try{return e=new t(":memory:"),e.exec("CREATE VIRTUAL TABLE __fts5_probe USING fts5(x)"),!0}catch{return!1}finally{try{e?.close()}catch{}}}function ib(t,e){let n=e!==void 0?e:globalThis.Bun;if(typeof n<"u"&&n!==null)return!0;let r=t??process.versions,[o,s]=(r.node??"0.0.0").split("."),i=Number(o),a=Number(s);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function nt(){if(!ts){let t=HO(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;ts=function(r,o){let s=new e(r,{readonly:o?.readonly,create:!0}),i=new kc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(ib()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&sb(e)?ts=function(r,o){let s=new e(r,{readOnly:o?.readonly??!1}),i=new wc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:ts=t("better-sqlite3")}else ts=t("better-sqlite3")}return ts}function ns(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function rs(t){if(!UO(t))for(let e of["-wal","-shm"])try{ob(t+e)}catch{}}function Ec(t){for(let e of["","-wal","-shm"])try{ob(t+e)}catch{}}function os(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function op(t="context-mode"){return qO(ZO(),`${t}-${process.pid}.db`)}function gr(t,e=[100,500,2e3]){let n;for(let r=0;r<=e.length;r++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(n=o instanceof Error?o:new Error(s),r<e.length){let i=e[r],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${n?.message}`)}function Tc(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function ab(t){let e=Date.now();for(let n of["","-wal","-shm"])try{BO(t+n,`${t}${n}.corrupt-${e}`)}catch{}}var kc,wc,ts,Ti,rp,$i,yr=v(()=>{"use strict";kc=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){let n="",r=null;for(let s=0;s<e.length;s++){let i=e[s];if(r)n+=i,i===r&&(r=null);else if(i==="'"||i==='"')n+=i,r=i;else if(i===";"){let a=n.trim();a&&this.#e.prepare(a).run(),n=""}else n+=i}let o=n.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>{let o=n.get(...r);return o===null?void 0:o},all:(...r)=>n.all(...r),iterate:(...r)=>n.iterate(...r)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},wc=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){return this.#e.exec(e),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>n.get(...r),all:(...r)=>n.all(...r),iterate:(...r)=>typeof n.iterate=="function"?n.iterate(...r):n.all(...r)[Symbol.iterator]()}}transaction(e){return(...n)=>{this.#e.exec("BEGIN");try{let r=e(...n);return this.#e.exec("COMMIT"),r}catch(r){throw this.#e.exec("ROLLBACK"),r}}}close(){this.#e.close()}},ts=null;Ti=Symbol.for("__context_mode_live_dbs_v3__"),rp=(()=>{let t=globalThis;return t[Ti]||(t[Ti]=new Set,process.on("exit",()=>{for(let e of t[Ti])os(e);t[Ti].clear()})),t[Ti]})(),$i=class{#e;#t;constructor(e){let n=nt();this.#e=e,rs(e);let r;try{r=new n(e,{timeout:3e4}),ns(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(Tc(s)){ab(e),rs(e);try{r=new n(e,{timeout:3e4}),ns(r)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=r,rp.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){rp.delete(this.#t),os(this.#t)}withRetry(e){return gr(e)}cleanup(){rp.delete(this.#t),os(this.#t),Ec(this.#e)}}});var Sb={};_e(Sb,{SessionDB:()=>Gt,StorageDirectoryError:()=>Kt,_resetWorktreeSuffixCacheForTests:()=>cI,applyMissingSessionEventsColumns:()=>cp,clearStorageDirectoryCheckCacheForTests:()=>nI,describeStorageDirectorySource:()=>Ri,ensureSessionEventsSchema:()=>up,ensureWritableStorageDir:()=>Sr,formatStorageDirectoryError:()=>cs,getWorktreeSuffix:()=>Ci,hashProjectDirCanonical:()=>rt,hashProjectDirLegacy:()=>On,normalizeWorktreePath:()=>xr,resolveContentStorageDir:()=>Yr,resolveContentStorePath:()=>ap,resolveDefaultSessionDir:()=>Cc,resolveSessionDbPath:()=>us,resolveSessionPath:()=>bb,resolveSessionStorageDir:()=>br,resolveStatsStorageDir:()=>as});import{createHash as Pi}from"node:crypto";import{execFileSync as VO}from"node:child_process";import{accessSync as WO,constants as KO,existsSync as Rc,mkdirSync as GO,realpathSync as JO,renameSync as ip}from"node:fs";import{homedir as mb}from"node:os";import{dirname as XO,isAbsolute as fb,join as _r,resolve as is}from"node:path";function Cc(t){let e=t.env??process.env,n=t.legacySessionDirEnv,r=n?e[n]?.trim():void 0;return r&&n?(t.onLegacySessionDir?.(n,r),r):_r(YO(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function YO(t,e,n){let r=e?n[e]:void 0;return r&&r.trim()!==""?ub(r.trim()):ub(t,mb())}function ub(t,e){return t.startsWith("~")?is(mb(),t.replace(/^~[/\\]?/,"")):fb(t)?is(t):e?is(e,t):is(t)}function QO(t,e,n){return new Kt(t,e,Cn,void 0,[`Invalid ${Cn} for context-mode ${t} directory: ${n}`,_b()].join(`
|
|
4
|
+
`))}function gb(t){let e=process.env[Cn];if(e===void 0)return{kind:"unset"};let n=e.trim();if(!n)return{kind:"ignored-empty",ignoredEnvVar:Cn,ignoredReason:"empty"};if(!fb(n))throw QO(t,n,`${Cn} must be an absolute path.`);return{kind:"override",root:is(n)}}function eI(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function yb(t,e){let n=gb(t);return n.kind!=="override"?null:{kind:t,path:_r(n.root,e),envVar:Cn,source:"override"}}function tI(t,e,n){return{kind:t,path:is(e()),envVar:null,source:"default",...n}}function br(t){let e=gb("session");return e.kind==="override"?{kind:"session",path:_r(e.root,hb),envVar:Cn,source:"override"}:tI("session",t,eI(e))}function Yr(t){let e=yb("content",cb);if(e)return e;let n=br(t);return{kind:"content",path:_r(XO(n.path),cb),envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function as(t){let e=yb("stats",hb);if(e)return e;let n=br(t);return{kind:"stats",path:n.path,envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function cs(t){return t.message}function Ri(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function nI(){Pc.clear()}function Sr(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),n=Pc.get(e);if(n instanceof Kt)throw n;if(n===t.path)return n;try{return GO(t.path,{recursive:!0}),WO(t.path,KO.W_OK),Pc.set(e,t.path),t.path}catch(r){let o=new Kt(t.kind,sI(r)??t.path,Cn,r,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw Pc.set(e,o),o}}function rI(t,e,n={}){return[`context-mode ${t} directory is not writable: ${e}`,oI(n),_b()].filter(Boolean).join(`
|
|
5
|
+
`)}function oI(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function _b(){return`Set ${Cn} to a writable absolute path.`}function sI(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function xr(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function lb(t){let e=t;try{e=JO.native(t)}catch{}let n=xr(e);return process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n}function xb(t,e){return VO("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function iI(t){let e=xb(t,["rev-parse","--show-toplevel"]);return e.length>0?xr(e):null}function aI(t){let e=xb(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(n=>n.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?xr(e):null}function Ci(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(ss&&ss.projectDir===t&&ss.envSuffix===e)return ss.suffix;let n="";if(e!==void 0)n=e?`__${e}`:"";else try{let r=iI(t),o=aI(t);if(r&&o){let s=lb(r),i=lb(o);s!==i&&(n=`__${Pi("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return ss={projectDir:t,envSuffix:e,suffix:n},n}function cI(){ss=void 0}function On(t){return Pi("sha256").update(xr(t)).digest("hex").slice(0,16)}function rt(t){let e=xr(t),n=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Pi("sha256").update(n).digest("hex").slice(0,16)}function ap(t){let{projectDir:e,contentDir:n}=t,r=rt(e),o=_r(n,`${r}.db`);if(Rc(o))return o;let s=On(e);if(s===r)return o;let i=_r(n,`${s}.db`);if(Rc(i))try{ip(i,o);for(let a of["-wal","-shm"])try{ip(i+a,o+a)}catch{}}catch{}return o}function us(t){return bb({...t,ext:".db"})}function bb(t){let{projectDir:e,sessionsDir:n,ext:r}=t,o=t.suffix??Ci(e),s=rt(e),i=_r(n,`${s}${o}${r}`);if(Rc(i))return i;let a=On(e);if(a===s)return i;let c=_r(n,`${a}${o}${r}`);if(Rc(c))try{ip(c,i)}catch{}return i}function $c(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function cp(t){let e=t.pragma("table_xinfo(session_events)"),n=new Set(e.map(o=>o.name)),r=!1;for(let[o,s]of uI)n.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),r=!0);return r&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),r}function up(t,e){let n=null;try{n=new e(t),cp(n)}catch{}finally{try{n?.close()}catch{}}}var Cn,hb,cb,Kt,Pc,ss,db,pb,U,uI,Gt,Jt=v(()=>{"use strict";yr();Cn="CONTEXT_MODE_DIR",hb="sessions",cb="content",Kt=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,n,r=Cn,o,s,i={}){super(s??rI(e,n,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=n,this.overrideEnvVar=r,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},Pc=new Map;db=1e3,pb=5;U={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",getSessionRollup:"getSessionRollup",getMaxFileEdits:"getMaxFileEdits",getLatestCommitMessage:"getLatestCommitMessage",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",claimLatestUnconsumedResume:"claimLatestUnconsumedResume",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions",searchEvents:"searchEvents",incrementToolCall:"incrementToolCall",getToolCallTotals:"getToolCallTotals",getToolCallByTool:"getToolCallByTool",getEventBytesSummary:"getEventBytesSummary"},uI=[["project_dir","TEXT NOT NULL DEFAULT ''"],["attribution_source","TEXT NOT NULL DEFAULT 'unknown'"],["attribution_confidence","REAL NOT NULL DEFAULT 0"],["bytes_avoided","INTEGER NOT NULL DEFAULT 0"],["bytes_returned","INTEGER NOT NULL DEFAULT 0"]];Gt=class extends $i{constructor(e){super(e?.dbPath??op("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let n=this.db.pragma("table_xinfo(session_events)").find(r=>r.name==="data_hash");n&&n.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
|
|
6
6
|
CREATE TABLE IF NOT EXISTS session_events (
|
|
7
7
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
8
8
|
session_id TEXT NOT NULL,
|
|
@@ -52,7 +52,7 @@ var FR=Object.create;var _d=Object.defineProperty;var HR=Object.getOwnPropertyDe
|
|
|
52
52
|
);
|
|
53
53
|
|
|
54
54
|
CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
|
|
55
|
-
`);try{
|
|
55
|
+
`);try{cp(this.db)}catch{}}prepareStatements(){this.stmts=new Map;let e=(n,r)=>{this.stmts.set(n,this.db.prepare(r))};e(U.insertEvent,`INSERT INTO session_events (
|
|
56
56
|
session_id, type, category, priority, data,
|
|
57
57
|
project_dir, attribution_source, attribution_confidence,
|
|
58
58
|
bytes_avoided, bytes_returned,
|
|
@@ -141,46 +141,51 @@ var FR=Object.create;var _d=Object.defineProperty;var HR=Object.getOwnPropertyDe
|
|
|
141
141
|
FROM tool_calls WHERE session_id = ?`),e(U.getToolCallByTool,`SELECT tool, calls, bytes_returned
|
|
142
142
|
FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(U.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
143
143
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
144
|
-
FROM session_events WHERE session_id = ?`)}insertEvent(e,r
|
|
144
|
+
FROM session_events WHERE session_id = ?`)}insertEvent(e,n,r="PostToolUse",o,s){let i=Pi("sha256").update(n.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??n.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??n.attribution_source??"unknown"),u=Number(o?.confidence??n.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=$c(s?.bytesAvoided),p=$c(s?.bytesReturned),h=this.db.transaction(()=>{if(this.stmt(U.checkDuplicate).get(e,pb,n.type,i))return;this.stmt(U.getEventCount).get(e).cnt>=db&&this.stmt(U.evictLowestPriority).run(e),this.stmt(U.insertEvent).run(e,n.type,n.category,n.priority,n.data,a,c,l,d,p,r,i),this.stmt(U.updateMetaLastEvent).run(e)});this.withRetry(()=>h())}bulkInsertEvents(e,n,r="PostToolUse",o,s){if(!n||n.length===0)return;if(n.length===1){this.insertEvent(e,n[0],r,o?.[0],s?.[0]);return}let i=n.map((c,u)=>{let l=Pi("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),d=o?.[u],p=String(d?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),h=p===""?"":xr(p),m=String(d?.source??c.attribution_source??"unknown"),f=Number(d?.confidence??c.attribution_confidence??0),g=Number.isFinite(f)?Math.max(0,Math.min(1,f)):0,y=s?.[u],_=$c(y?.bytesAvoided),x=$c(y?.bytesReturned);return{event:c,dataHash:l,projectDir:h,attributionSource:m,attributionConfidence:g,bytesAvoided:_,bytesReturned:x}}),a=this.db.transaction(()=>{let c=this.stmt(U.getEventCount).get(e).cnt;for(let u of i)this.stmt(U.checkDuplicate).get(e,pb,u.event.type,u.dataHash)||(c>=db?this.stmt(U.evictLowestPriority).run(e):c++,this.stmt(U.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,r,u.dataHash));this.stmt(U.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,n){let r=n?.limit??1e3,o=n?.type,s=n?.minPriority;return o&&s!==void 0?this.stmt(U.getEventsByTypeAndPriority).all(e,o,s,r):o?this.stmt(U.getEventsByType).all(e,o,r):s!==void 0?this.stmt(U.getEventsByPriority).all(e,s,r):this.stmt(U.getEvents).all(e,r)}getEventCount(e){return this.stmt(U.getEventCount).get(e).cnt}getEventBytesSummary(e){let n=this.stmt(U.getEventBytesSummary).get(e);return{bytesAvoided:Number(n?.bytes_avoided??0),bytesReturned:Number(n?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(U.getLatestAttributedProject).get(e)?.project_dir||null}_getSessionProjectDir(e){try{return this.db.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(e)?.project_dir||""}catch{return""}}searchEvents(e,n,r,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(U.searchEvents).all(r,s,s,i,i,n)}catch{return[]}}getSessionIdsForProject(e){try{let n=xr(e);return this.db.prepare(`SELECT DISTINCT session_id
|
|
145
145
|
FROM session_events
|
|
146
|
-
WHERE project_dir = ?`).all(
|
|
147
|
-
`,"utf-8")}validateHooks(e){let
|
|
148
|
-
`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let
|
|
149
|
-
`,"utf-8")}validateHooks(e){let
|
|
150
|
-
`,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
`)
|
|
146
|
+
WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(n).map(o=>o.session_id)}catch{return[]}}ensureSession(e,n){this.stmt(U.ensureSession).run(e,n)}getSessionStats(e){return this.stmt(U.getSessionStats).get(e)??null}getSessionRollup(e){let n=this.stmt(U.getSessionRollup).get(e),r=this.stmt(U.getMaxFileEdits).get(e),o=this.stmt(U.getLatestCommitMessage).get(e),s=this.getSessionStats(e),i=(n?.tool_calls??0)>0?n?.unique_files??0:0,a=n?.errors??0,c=Math.min(i,a);return{tool_calls:n?.tool_calls??0,errors:n?.errors??0,unique_tools:n?.unique_tools??0,unique_files:n?.unique_files??0,max_file_edits:r?.max_file_edits??0,has_commit:n?.has_commit??0,commit_message:o?.data??"",edit_test_cycles:c,duration_min:n?.duration_min??0,compact_count:s?.compact_count??0,sources_indexed:n?.sources_indexed??0,total_chunks:n?.total_chunks??0,search_queries:n?.search_queries??0}}incrementCompactCount(e){this.stmt(U.incrementCompactCount).run(e)}upsertResume(e,n,r){this.stmt(U.upsertResume).run(e,n,r??0)}getResume(e){return this.stmt(U.getResume).get(e)??null}markResumeConsumed(e){this.stmt(U.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let n=this.stmt(U.claimLatestUnconsumedResume).get(e);return n?{sessionId:n.session_id,snapshot:n.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,n,r=0){let o=Number.isFinite(r)&&r>0?Math.round(r):0;try{this.stmt(U.incrementToolCall).run(e,n,o)}catch{}}getToolCallStats(e){try{let n=this.stmt(U.getToolCallTotals).get(e),r=this.stmt(U.getToolCallByTool).all(e),o={};for(let s of r)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:n?.calls??0,totalBytesReturned:n?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(U.deleteEvents).run(e),this.stmt(U.deleteResume).run(e),this.stmt(U.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let n=`-${e}`,r=this.stmt(U.getOldSessions).all(n);for(let{session_id:o}of r)this.deleteSession(o);return r.length}pruneOrphanedEvents(){let e=this.db.prepare("DELETE FROM session_events WHERE session_id NOT IN (SELECT session_id FROM session_meta)").run();return Number(e.changes??0)}}});import{join as ls,resolve as vb}from"node:path";import{accessSync as lI,copyFileSync as dI,constants as pI,mkdirSync as mI}from"node:fs";import{homedir as lp}from"node:os";function ht(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?vb(lp(),e.replace(/^~[/\\]?/,"")):vb(e)}var be,it=v(()=>{"use strict";Jt();be=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=ht(),n=e?ls(e,"context-mode","sessions"):ls(lp(),...this.sessionDirSegments,"context-mode","sessions");return mI(n,{recursive:!0}),n}getConfigDir(e){return ls(lp(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let n=ht(),r=n?ls(n,"context-mode","memory"):ls(this.getConfigDir(),"memory");return e?ls(r,rt(e)):r}backupSettings(){let e=this.getSettingsPath();try{lI(e,pI.R_OK);let n=e+".bak";return dI(e,n),n}catch{return null}}}});var ds,dp=v(()=>{"use strict";it();ds=class extends be{parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),e.updatedOutput&&(n.updatedMCPToolOutput=e.updatedOutput),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});import{existsSync as pp}from"node:fs";import{join as mp}from"node:path";async function fI(){if(ps)return ps;if(ms)return null;try{let t=[new URL("../../scripts/plugin-cache-integrity.mjs",import.meta.url),new URL("./scripts/plugin-cache-integrity.mjs",import.meta.url)],e=null;for(let n of t)try{let r=await import(n.href);if(typeof r?.assertPluginCacheIntegrity=="function")return ps=r,ps}catch(r){e=r}return ms=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return ms=t instanceof Error?t.message:String(t),null}}function hI(t){let e=[];return pp(mp(t,"start.mjs"))||e.push("start.mjs"),!pp(mp(t,"server.bundle.mjs"))&&!pp(mp(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function kb(t){if(ps){let e=ps.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(ms){let e=hI(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${ms}); the MCP server cannot start. Reinstall: npm install -g context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${ms}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var ps,ms,wb=v(()=>{"use strict";ps=null,ms=null;fI()});function Oi(t,e){let n=Qr[e],r=hp(e);return t.hooks?.some(o=>o.command?.includes(n)||o.command?.includes(r))??!1}function hp(t,e){if(e){let n=Qr[t];return Ke(`${e}/hooks/${n}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function gp(t){let e=Sc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function $b(t){let e=Object.values(Qr);return t.hooks?.some(n=>n.command!=null&&(e.some(r=>n.command.includes(r))||n.command.includes("context-mode hook")))??!1}var Xt,gI,fp,Eb,yI,oV,Qr,Tb,sV,Pb=v(()=>{"use strict";Rn();Xt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit",STOP:"Stop"},gI="mcp__",fp=["Bash","WebFetch","Read","Grep","Agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",gI],Eb=fp.join("|"),yI=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],oV=yI.join("|"),Qr={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs",Stop:"stop.mjs"},Tb=[Xt.PRE_TOOL_USE,Xt.SESSION_START],sV=[Xt.POST_TOOL_USE,Xt.PRE_COMPACT,Xt.USER_PROMPT_SUBMIT,Xt.STOP]});var _p={};_e(_p,{ClaudeCodeAdapter:()=>yp});import{readFileSync as Oc,writeFileSync as Rb,existsSync as Cb,readdirSync as _I,chmodSync as xI,accessSync as bI,mkdirSync as SI,constants as vI}from"node:fs";import{resolve as Ic,join as vr}from"node:path";import{homedir as Ob}from"node:os";var yp,xp=v(()=>{"use strict";dp();it();kr();wb();Rn();Pb();yp=class extends ds{constructor(){super([".claude"])}name="Claude Code";paradigm="json-stdio";projectDirEnvVar="CLAUDE_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getConfigDir(e){return Be()}getSessionDir(){let e=ht(),n=e?vr(e,"context-mode","sessions"):vr(this.getConfigDir(),"context-mode","sessions");return SI(n,{recursive:!0}),n}getSettingsPath(){return vr(this.getConfigDir(),"settings.json")}generateHookConfig(e){let n=Ke(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...fp].map(o=>({matcher:o,hooks:[{type:"command",command:n}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:Ke(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Ke(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Ke(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Ke(`${e}/hooks/sessionstart.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Ke(`${e}/hooks/stop.mjs`)}]}]}}readSettings(){try{let e=Oc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){Rb(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
147
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),n;let o=r.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,Xt.PRE_TOOL_USE);n.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(o,s,Xt.SESSION_START);return n.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),n}getHealthChecks(e){let n=Object.entries(Qr).map(([o,s])=>{let i=vr(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>Cb(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),r={name:"Plugin cache integrity",check:()=>kb(e)};return[...n,r]}readPluginHooks(e){let n=[vr(e,"hooks","hooks.json"),vr(e,".claude-plugin","hooks","hooks.json")];for(let r of n)try{let o=Oc(r,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,n,r){let o=e?.[r];if(o&&o.length>0&&o.some(i=>Oi(i,r)))return!0;let s=n?.[r];return!!(s&&s.length>0&&s.some(i=>Oi(i,r)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let n=e.enabledPlugins;if(!n)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let r=Object.keys(n).find(o=>o.startsWith("context-mode"));return r&&n[r]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${r}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let n=vr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Oc(n,"utf-8")).plugins??{};for(let[s,i]of Object.entries(o)){if(!s.toLowerCase().includes("context-mode"))continue;let a=i;if(a.length>0&&typeof a[0].version=="string")return a[0].version}}catch{}let e=Array.from(new Set([this.getConfigDir(),Be(),Ic(Ob(),".claude"),Ic(Ob(),".config","claude")]));for(let n of e){let r=Ic(n,"plugins","cache","context-mode","context-mode");try{let s=_I(r).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let l=0;l<3;l++)if((c[l]??0)!==(u[l]??0))return(c[l]??0)-(u[l]??0);return 0});if(s.length>0)return s[s.length-1]}catch{}}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[];for(let u of Object.keys(r)){let l=r[u];if(!Array.isArray(l))continue;let d=l.filter(h=>{let m=h;if(!$b(m))return!0;let f=m.hooks??[];return f.every(y=>!y.command||!gp(y.command))?!0:f.every(y=>{let _=y.command?gp(y.command):null;return _?Cb(_):!0})}),p=l.length-d.length;p>0&&(r[u]=d,o.push(`Removed ${p} stale ${u} hook(s)`))}let a=this.checkPluginRegistration().status==="pass"?this.readPluginHooks(e):void 0;if(a&&Tb.every(l=>this.checkHookType(void 0,a,l))){let l=Object.values(Qr),d=p=>p!=null&&(l.some(h=>p.includes(h))||p.includes("context-mode hook"));for(let p of Object.keys(r)){let h=r[p];if(!Array.isArray(h))continue;let m=0;for(let g of h){let y=g,_=y.hooks??[],x=_.length;y.hooks=_.filter(S=>!d(S.command)),m+=x-y.hooks.length}let f=h.filter(g=>{let y=g.hooks;return Array.isArray(y)&&y.length>0});(m>0||f.length!==h.length)&&(r[p]=f,m>0&&o.push(`Removed ${m} duplicate ${p} hook(s) \u2014 covered by plugin hooks.json`))}return n.hooks=r,this.writeSettings(n),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let c=[Xt.PRE_TOOL_USE,Xt.SESSION_START];for(let u of c){let l=hp(u,e);if(u===Xt.PRE_TOOL_USE){let d={matcher:Eb,hooks:[{type:"command",command:l}]},p=r.PreToolUse;if(p&&Array.isArray(p)){let h=p.findIndex(m=>Oi(m,u));h>=0?(p[h]=d,o.push(`Updated existing ${u} hook entry`)):(p.push(d),o.push(`Added ${u} hook entry`)),r.PreToolUse=p}else r.PreToolUse=[d],o.push(`Created ${u} hooks section`)}else{let d={matcher:"",hooks:[{type:"command",command:l}]},p=r[u];if(p&&Array.isArray(p)){let h=p.findIndex(m=>Oi(m,u));h>=0?(p[h]=d,o.push(`Updated existing ${u} hook entry`)):(p.push(d),o.push(`Added ${u} hook entry`)),r[u]=p}else r[u]=[d],o.push(`Created ${u} hooks section`)}}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[];for(let[,r]of Object.entries(Qr)){let o=Ic(e,"hooks",r);try{bI(o,vI.R_OK),xI(o,493),n.push(o)}catch{}}return n}updatePluginRegistry(e,n){try{let r=vr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Oc(r,"utf-8"));for(let[s,i]of Object.entries(o.plugins||{}))if(s.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=n,a.lastUpdated=new Date().toISOString();Rb(r,JSON.stringify(o,null,2)+`
|
|
148
|
+
`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function eo(t,e){let n=Ac[t];return e&&n?Ke(`${e}/hooks/gemini-cli/${n}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var Re,Ib,Ac,yV,_V,Ab=v(()=>{"use strict";Rn();Re={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},Ib="mcp__(?!.*context-mode)",Ac={[Re.BEFORE_AGENT]:"beforeagent.mjs",[Re.BEFORE_TOOL]:"beforetool.mjs",[Re.AFTER_TOOL]:"aftertool.mjs",[Re.PRE_COMPRESS]:"precompress.mjs",[Re.SESSION_START]:"sessionstart.mjs"},yV=[Re.BEFORE_TOOL,Re.SESSION_START],_V=[Re.AFTER_TOOL,Re.PRE_COMPRESS]});var Mb={};_e(Mb,{GeminiCLIAdapter:()=>Sp});import{readFileSync as bp,writeFileSync as Nb,mkdirSync as kI,accessSync as wI,chmodSync as EI,existsSync as TI,constants as $I}from"node:fs";import{resolve as Ii,join as Db}from"node:path";import{homedir as Nc}from"node:os";var Sp,jb=v(()=>{"use strict";it();Ab();Sp=class extends be{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Ii(Nc(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[Re.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:eo(Re.BEFORE_AGENT,e)}]}],[Re.BEFORE_TOOL]:[{matcher:`run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|${Ib}`,hooks:[{type:"command",command:eo(Re.BEFORE_TOOL,e)}]}],[Re.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:eo(Re.AFTER_TOOL,e)}]}],[Re.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:eo(Re.PRE_COMPRESS,e)}]}],[Re.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:eo(Re.SESSION_START,e)}]}]}}readSettings(){try{let e=bp(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=Ii(Nc(),".gemini");kI(n,{recursive:!0}),Nb(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
149
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),n;let o=r.hooks,s=o?.[Re.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else n.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[Re.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else n.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return n}getHealthChecks(e){return Object.entries(Ac).map(([n,r])=>{let o=Db(e,"hooks","gemini-cli",r);return{name:`Hook script: ${n} (${r})`,check:()=>TI(o)?{status:"OK",detail:o}:{status:"FAIL",detail:`not found at ${o}`}}})}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let n=e.extensions;return n&&(Array.isArray(n)?n.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(n).some(o=>o.includes("context-mode")))?{check:"Plugin registration",status:"pass",message:"context-mode found in extensions"}:{check:"Plugin registration",status:"warn",message:"context-mode not found in extensions (might be using standalone MCP mode)"}}getInstalledVersion(){try{let e=Ii(Nc(),".gemini","extensions","context-mode","package.json"),n=JSON.parse(bp(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[],s=[{name:Re.BEFORE_AGENT},{name:Re.BEFORE_TOOL},{name:Re.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:eo(i.name,e)}]},u=r[i.name];if(u&&Array.isArray(u)){let l=u.findIndex(d=>d.hooks?.some(h=>h.command?.includes("context-mode")));l>=0?(u[l]=c,o.push(`Updated existing ${i.name} hook entry`)):(u.push(c),o.push(`Added ${i.name} hook entry`)),r[i.name]=u}else r[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[],r=Db(e,"hooks","gemini-cli");for(let o of Object.values(Ac)){let s=Ii(r,o);try{wI(s,$I.R_OK),EI(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){try{let r=Ii(Nc(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(bp(r,"utf-8"));o.version=n,o.installPath=e,o.lastUpdated=new Date().toISOString(),Nb(r,JSON.stringify(o,null,2)+`
|
|
150
|
+
`,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});function Ai(t){let e="",n=!1,r=!1,o=!1;for(let c=0;c<t.length;c++){let u=t[c],l=t[c+1];if(o){u==="*"&&l==="/"&&(o=!1,c++);continue}if(r){e+=u,r=!1;continue}if(u==="\\"){e+=u,r=n;continue}if(u==='"'){n=!n,e+=u;continue}if(!n&&u==="/"&&l==="/"){for(;c<t.length&&t[c]!==`
|
|
151
|
+
`;)c++;c<t.length&&(e+=`
|
|
152
|
+
`);continue}if(!n&&u==="/"&&l==="*"){o=!0,c++;continue}e+=u}let s="",i=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];if(a){s+=u,a=!1;continue}if(u==="\\"){s+=u,a=i;continue}if(u==='"'){i=!i,s+=u;continue}if(!i&&u===","){let l=c+1;for(;l<e.length&&(e[l]===" "||e[l]===" "||e[l]==="\r"||e[l]===`
|
|
153
|
+
`);)l++;if(e[l]==="}"||e[l]==="]")continue}s+=u}return s}function Kn(t){for(let e of[t,Ai(t)])try{return JSON.parse(e)}catch{}}var Ni=v(()=>{"use strict"});var to,TV,$V,Lb=v(()=>{"use strict";to={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},TV=[to.BEFORE,to.AFTER],$V=[to.COMPACTING]});var Fb={};_e(Fb,{OpenCodeAdapter:()=>vp});import{readFileSync as zb,writeFileSync as PI,mkdirSync as RI,copyFileSync as CI,accessSync as OI,existsSync as II,constants as AI}from"node:fs";import{resolve as Ht,join as Gn}from"node:path";import{homedir as wr}from"node:os";var vp,Hb=v(()=>{"use strict";it();Ni();Lb();vp=class extends be{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},toolOutput:n.output,isError:void 0,sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let n={};return e.updatedOutput&&(n.output=e.updatedOutput),e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){if(this.settingsPath)return this.settingsPath;let e=Ht(`${this.platform}.jsonc`);return II(e)?e:Ht(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Ht("kilo.jsonc"),Ht("kilo.json"),Ht(".kilo","kilo.jsonc"),Ht(".kilo","kilo.json"),Ht(".kilocode","kilo.jsonc"),Ht(".kilocode","kilo.json"),Gn(wr(),".config","kilo","kilo.jsonc"),Gn(wr(),".config","kilo","kilo.json")]:[Ht("opencode.jsonc"),Ht("opencode.json"),Ht(".opencode","opencode.jsonc"),Ht(".opencode","opencode.json"),Gn(wr(),".config","opencode","opencode.jsonc"),Gn(wr(),".config","opencode","opencode.json")]}getSessionDir(){let e=ht(),n=e?Gn(e,"context-mode","sessions"):Gn(this.getConfigDir(),"context-mode","sessions");return RI(n,{recursive:!0}),n}getConfigDir(e){let n;return process.platform==="win32"?n=process.env.APPDATA||Gn(wr(),"AppData","Roaming"):n=process.env.XDG_CONFIG_HOME||Gn(wr(),".config"),Gn(n,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[to.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[to.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[to.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),n=new Set(e.filter(s=>s.includes(wr()))),r=null,o;for(let s of e)try{let i=zb(s,"utf-8"),a=s.endsWith(".jsonc")?Ai(i):i,c=JSON.parse(a);r||(r=c,o=s);let u=n.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return r?(this.settingsPath=o,r):null}writeSettings(e){PI(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
154
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),n;let o=this.hasContextModePlugin(r);return Array.isArray(r.plugin)?n.push({check:"Plugin registration",status:o?"pass":"fail",message:o?"context-mode found in plugin array":"context-mode not found in plugin array",fix:o?void 0:"context-mode upgrade"}):n.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),this.hasLegacyContextModeMcp(r)&&n.push({check:"Legacy MCP registration",status:"warn",message:"mcp.context-mode is redundant: ctx_* tools are now provided by the plugin",fix:"context-mode upgrade (removes only mcp.context-mode; preserves other MCP servers)"}),n.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),n}checkPluginRegistration(){let e=this.readSettings();return e?this.hasContextModePlugin(e)?{check:"Plugin registration",status:"pass",message:"context-mode found in plugin array"}:{check:"Plugin registration",status:"fail",message:`context-mode not found in ${this.platform}.json plugin array`,fix:"context-mode upgrade"}:{check:"Plugin registration",status:"warn",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`}}getInstalledVersion(){try{let e=Ht(wr(),".cache",this.platform,"node_modules","context-mode","package.json"),n=JSON.parse(zb(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[],o=n.plugin??[];o.some(i=>i.includes("context-mode"))?r.push("context-mode already in plugin array"):(o.push("context-mode"),r.push("Added context-mode to plugin array")),n.plugin=o;let s=n.mcp;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s;Object.prototype.hasOwnProperty.call(i,"context-mode")&&(delete i["context-mode"],r.push("Removed legacy context-mode MCP block (plugin-native tools)")),Object.keys(i).length===0&&delete n.mcp}return this.writeSettings(n),r}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{OI(this.settingsPath,AI.R_OK);let n=this.settingsPath+".bak";return CI(this.settingsPath,n),n}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}hasContextModePlugin(e){let n=e.plugin;return Array.isArray(n)&&n.some(r=>typeof r=="string"&&r.includes("context-mode"))}hasLegacyContextModeMcp(e){let n=e.mcp;return!!(n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var no,DV,MV,Ub=v(()=>{"use strict";no={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},DV=[no.TOOL_CALL_BEFORE,no.TOOL_CALL_AFTER],MV=[no.COMMAND_NEW]});var Bb={};_e(Bb,{OpenClawAdapter:()=>Tp});import{readFileSync as kp,writeFileSync as NI,copyFileSync as DI,accessSync as MI,constants as jI}from"node:fs";import{resolve as Jn,join as wp}from"node:path";import{homedir as Ep}from"node:os";var Tp,Zb=v(()=>{"use strict";it();Ub();Tp=class extends be{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},toolOutput:n.output??n.tool_output,isError:n.isError??n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Jn("openclaw.json")}getConfigDir(e){return Jn(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return wp(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[no.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[no.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[no.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Jn("openclaw.json"),Jn(".openclaw","openclaw.json"),wp(Ep(),".openclaw","openclaw.json")];for(let n of e)try{let r=kp(n,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let n=Jn("openclaw.json");NI(n,JSON.stringify(e,null,2)+`
|
|
155
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),n;let o=r.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(n.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=s["context-mode"]?.enabled!==!1;n.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else n.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?n.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):n.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),n}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let r=e.plugins?.entries;return r&&Object.keys(r).some(s=>s.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in plugins.entries"}:{check:"Plugin registration",status:"fail",message:"context-mode not found in openclaw.json plugins.entries",fix:"context-mode upgrade"}}getInstalledVersion(){try{let e=Jn(Ep(),".openclaw","extensions","context-mode","package.json"),n=JSON.parse(kp(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}try{let e=Jn("node_modules","context-mode","package.json"),n=JSON.parse(kp(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[];n.plugins||(n.plugins={});let o=n.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},r.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,r.push("Enabled context-mode plugin")):r.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&r.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",r.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(n),r}backupSettings(){let e=[Jn("openclaw.json"),Jn(".openclaw","openclaw.json"),wp(Ep(),".openclaw","openclaw.json")];for(let n of e)try{MI(n,jI.R_OK);let r=n+".bak";return DI(n,r),r}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getProjectDir(e){return e.cwd??process.env.OPENCLAW_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.sessionId?e.sessionId:`pid-${process.ppid}`}}});import{homedir as qb}from"node:os";import{resolve as $p}from"node:path";function Vb(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?$p(qb(),t.replace(/^~[/\\]?/,"")):$p(t):$p(qb(),".codex")}var Wb=v(()=>{"use strict"});var tS={};_e(tS,{CodexAdapter:()=>Cp,parseCodexContextModePluginRoot:()=>Mc,probeCodexCliVersion:()=>Qb});import{execFileSync as Yb}from"node:child_process";import{existsSync as LI,readFileSync as fs,writeFileSync as Kb,accessSync as zI,copyFileSync as FI,constants as HI,mkdirSync as Pp}from"node:fs";import{resolve as Dc,dirname as Rp,join as Xn}from"node:path";import{fileURLToPath as UI}from"node:url";function Qb(t=Yb){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","codex --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("codex",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function Mc(t){for(let e of t.split(/\r?\n/)){let n=e.match(/^\s*context-mode@context-mode\s+installed,\s+enabled\s+\S+\s+(.+?)\s*$/);if(n?.[1])return n[1].trim()}return null}function jc(t,e){let n=t.split(/\r?\n/),r=!1,o=[];for(let s of n){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(r)break;r=i[1]?.trim()===e;continue}r&&o.push(s)}return r?o.join(`
|
|
156
|
+
`):null}function eS(t){let e=jc(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function qI(t){let e=jc(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function Gb(t){let e=jc(t,'plugins."context-mode@context-mode"');return e!==null&&/^\s*enabled\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function Jb(t){return jc(t,"mcp_servers.context-mode")!==null}function VI(t){if(eS(t))return{text:t,changed:!1};let e=t.includes(`\r
|
|
154
157
|
`)?`\r
|
|
155
158
|
`:`
|
|
156
|
-
`,
|
|
157
|
-
`)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=
|
|
159
|
+
`,n=t.split(/\r?\n/),r=n.findIndex(s=>/^\s*\[features\]\s*(?:#.*)?$/.test(s));if(r===-1){let s=t.length>0&&!t.endsWith(`
|
|
160
|
+
`)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=n.length;for(let s=r+1;s<n.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(n[s]??"")){o=s;break}for(let s=r+1;s<o;s++)if(/^\s*hooks\s*=/.test(n[s]??""))return n[s]="hooks = true",{text:n.join(e),changed:!0};return n.splice(r+1,0,"hooks = true"),{text:n.join(e),changed:!0}}function Xb(t,e){let n=t.includes(`\r
|
|
158
161
|
`)?`\r
|
|
159
162
|
`:`
|
|
160
|
-
`,n=t.split(/\r?\n/),o=[],s=[],i=!1;for(let a of n){let c=a.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(c){let u=c[1]?.trim()??"";i=e(u),i&&s.push(u)}i||o.push(a)}return{text:o.join(r),removed:s}}function VO(t){let e=t.trim();if(!e.startsWith('"')||!e.endsWith('"'))return null;try{let r=JSON.parse(e);return typeof r=="string"?r:null}catch{let r="",n=!1;for(let o of e.slice(1,-1))n?(r+=o==='"'||o==="\\"?o:`\\${o}`,n=!1):o==="\\"?n=!0:r+=o;return n&&(r+="\\"),r}}var UO,oo,BO,fp,Ib=S(()=>{"use strict";pt();Jt();Eb();UO="local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",oo={PreToolUse:"context-mode hook codex pretooluse",PostToolUse:"context-mode hook codex posttooluse",SessionStart:"context-mode hook codex sessionstart",PreCompact:"context-mode hook codex precompact",UserPromptSubmit:"context-mode hook codex userpromptsubmit",Stop:"context-mode hook codex stop"},BO={PreToolUse:["hooks/pretooluse.mjs","hooks/codex/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/codex/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/codex/sessionstart.mjs"],PreCompact:["hooks/precompact.mjs","hooks/codex/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/codex/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/codex/stop.mjs"]};fp=class extends xe{constructor(){super([".codex"])}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return wb()}getSettingsPath(){return Qr(this.getConfigDir(),"config.toml")}getSessionDir(){let e=Pt(),r=e?Qr(e,"context-mode","sessions"):Qr(this.getConfigDir(),"context-mode","sessions");return dp(r,{recursive:!0}),r}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let r=Pt(),n=r?Qr(r,"context-mode","memories"):Qr(this.getConfigDir(),"memories");return e?Qr(n,nt(e)):n}generateHookConfig(e){return{PreToolUse:[{matcher:UO,hooks:[{type:"command",command:oo.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:oo.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:oo.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:oo.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:oo.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:oo.Stop}]}]}}readSettings(){try{return{_raw_toml:ms(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[],n=Rb(),o="",s=!1;r.push({check:"Codex CLI binary",status:n?"pass":"warn",message:n?`codex --version resolved to ${n}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...n?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{o=ms(this.getSettingsPath(),"utf-8"),s=!0;let p=Cb(o),h=!p&&ZO(o);r.push({check:"Codex hooks feature flag",status:p?"pass":"fail",message:p?`[features].hooks enabled in ${this.getSettingsPath()}`:h?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...p?{}:{fix:"context-mode upgrade"}})}catch{r.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let i=this.generateHookConfig(""),a=s&&mp(o),c=a&&this.hasCodexPluginHookManifest(e);a&&!c&&r.push({check:"Codex plugin hooks",status:"fail",message:`context-mode Codex plugin is enabled, but ${Qr(e,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"}),a&&Tb(o)&&r.push({check:"Standalone MCP duplicate",status:"warn",message:"[mcp_servers.context-mode] is still registered while context-mode@context-mode is enabled; Codex may start both plugin and standalone MCP surfaces",fix:"context-mode upgrade (removes the standalone Codex MCP registration when the plugin owns context-mode)"});let u=this.readHooksConfig();if(!u.ok){if(u.reason==="missing"&&c){let p=Object.keys(i).map(h=>({check:`${h} hook`,status:"pass",message:`${h} hook provided by context-mode@context-mode plugin`}));return r.concat(p)}return u.reason==="missing"?r.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):u.reason==="invalid_json"?r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${u.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):r.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${u.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}])}if(!u.config.hooks&&!c)return r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let l=c?Object.keys(i).map(p=>({check:`${p} hook`,status:"pass",message:`${p} hook provided by context-mode@context-mode plugin`})):Object.entries(i).map(([p,h])=>{let m=u.config.hooks?.[p],f=h[0],g=Array.isArray(m)&&m.some(_=>this.isExpectedHookEntry(p,_,f)),y=p==="PreCompact"?"warn":"fail";return{check:`${p} hook`,status:g?"pass":y,message:g?`${p} hook configured in ${this.getHooksPath()}`:p==="PreCompact"?`${p} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${p} hook missing or not pointing to context-mode`,fix:g?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),d=[];for(let p of Object.keys(i)){let h=u.config.hooks?.[p];if(!Array.isArray(h))continue;let m=h.filter(f=>this.isManagedContextModeEntry(p,f)).length;m>1?d.push({check:`${p} duplicates`,status:"warn",message:`${m} context-mode entries found for ${p} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"}):c&&m===1&&d.push({check:`${p} plugin duplicate`,status:"warn",message:`${p} is configured in both ${this.getHooksPath()} and the context-mode Codex plugin; Codex will fire both hooks`,fix:"context-mode upgrade (removes user config context-mode hooks; preserves unrelated hooks)"})}return r.concat(l,d)}checkPluginRegistration(){try{let e=ms(this.getSettingsPath(),"utf-8"),r=mp(e),n=Tb(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return r&&n?{check:"MCP registration",status:"warn",message:"context-mode@context-mode plugin is enabled, but standalone [mcp_servers.context-mode] is also configured",fix:"context-mode upgrade"}:r?{check:"MCP registration",status:"pass",message:"context-mode@context-mode plugin enabled"}:n?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:o?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let r=this.readHooksConfig(),n=[],o=this.getSettingsPath(),s="";try{s=ms(o,"utf-8")}catch{s=""}let i=mp(s)&&this.hasCodexPluginHookManifest(e),a;if(r.ok)a=r.config;else if(r.reason==="missing")a={hooks:{}};else if(r.reason==="invalid_json"){let h=this.backupFile(this.getHooksPath(),".broken");n.push(`Backed up malformed Codex hooks to ${h}`),a={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${r.error}`);let c=a.hooks&&typeof a.hooks=="object"&&!Array.isArray(a.hooks)?a.hooks:{},u=this.generateHookConfig(e),l=n.length;if(i)for(let h of Object.keys(u))this.removeManagedHookEntries(c,h,n);else for(let[h,m]of Object.entries(u))this.upsertManagedHookEntry(c,h,m[0],n);n.length>l&&(a.hooks=c,this.writeHooksConfig(a),n.push(i?`Removed duplicate context-mode user hooks from ${this.getHooksPath()}`:`Wrote native Codex hooks to ${this.getHooksPath()}`));let d=qO(s).text,p=d!==s;if(i){let h=Pb(d,f=>f==="mcp_servers.context-mode"||f.startsWith("mcp_servers.context-mode.tools."));h.removed.length>0&&(d=h.text,n.push("Removed standalone Codex context-mode MCP registration"));let m=this.pruneStaleUserHookTrustState(d,c);m.removed.length>0&&(d=m.text,n.push(`Removed ${m.removed.length} stale Codex hook trust entr${m.removed.length===1?"y":"ies"}`))}if(d!==s){let h=d.includes(`\r
|
|
163
|
+
`,r=t.split(/\r?\n/),o=[],s=[],i=!1;for(let a of r){let c=a.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(c){let u=c[1]?.trim()??"";i=e(u),i&&s.push(u)}i||o.push(a)}return{text:o.join(n),removed:s}}function WI(t){let e=t.trim();if(!e.startsWith('"')||!e.endsWith('"'))return null;try{let n=JSON.parse(e);return typeof n=="string"?n:null}catch{let n="",r=!1;for(let o of e.slice(1,-1))r?(n+=o==='"'||o==="\\"?o:`\\${o}`,r=!1):o==="\\"?r=!0:n+=o;return r&&(n+="\\"),n}}var BI,ro,ZI,Cp,Op=v(()=>{"use strict";it();Jt();Wb();BI="local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",ro={PreToolUse:"context-mode hook codex pretooluse",PostToolUse:"context-mode hook codex posttooluse",SessionStart:"context-mode hook codex sessionstart",PreCompact:"context-mode hook codex precompact",UserPromptSubmit:"context-mode hook codex userpromptsubmit",Stop:"context-mode hook codex stop"},ZI={PreToolUse:["hooks/pretooluse.mjs","hooks/codex/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/codex/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/codex/sessionstart.mjs"],PreCompact:["hooks/precompact.mjs","hooks/codex/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/codex/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/codex/stop.mjs"]};Cp=class extends be{codexPluginListRunner;constructor(e={}){super([".codex"]),this.codexPluginListRunner=e.codexPluginListRunner??Yb}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return Vb()}getSettingsPath(){return Xn(this.getConfigDir(),"config.toml")}getSessionDir(){let e=ht(),n=e?Xn(e,"context-mode","sessions"):Xn(this.getConfigDir(),"context-mode","sessions");return Pp(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=ht(),r=n?Xn(n,"context-mode","memories"):Xn(this.getConfigDir(),"memories");return e?Xn(r,rt(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:BI,hooks:[{type:"command",command:ro.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:ro.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:ro.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:ro.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:ro.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:ro.Stop}]}]}}readSettings(){try{return{_raw_toml:fs(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=Qb(),o="",s=!1;n.push({check:"Codex CLI binary",status:r?"pass":"warn",message:r?`codex --version resolved to ${r}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...r?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{o=fs(this.getSettingsPath(),"utf-8"),s=!0;let h=eS(o),m=!h&&qI(o);n.push({check:"Codex hooks feature flag",status:h?"pass":"fail",message:h?`[features].hooks enabled in ${this.getSettingsPath()}`:m?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...h?{}:{fix:"context-mode upgrade"}})}catch{n.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let i=this.generateHookConfig(""),a=this.getCodexPluginHookStatus(e,o,s),c=a.enabled,u=a.hooksAvailable;if(c&&a.runtimeRoot?n.push({check:"Codex plugin root",status:a.rootMismatch?"warn":"pass",message:a.rootMismatch?`context-mode doctor is running from ${a.configuredRoot}, but Codex plugin manager reports ${a.runtimeRoot}`:`Codex plugin manager reports ${a.runtimeRoot}`,...a.rootMismatch?{fix:"Restart Codex after upgrade; run context-mode upgrade to keep native user-hook fallback until the plugin root converges"}:{}}):c&&n.push({check:"Codex plugin root",status:"warn",message:"context-mode@context-mode is enabled, but `codex plugin list` did not report its runtime root",fix:"Restart Codex or verify `codex plugin list` shows context-mode@context-mode installed and enabled"}),c&&!u){let h=a.runtimeRoot??e;n.push({check:"Codex plugin hooks",status:"fail",message:`context-mode Codex plugin is enabled, but ${Xn(h,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"})}c&&Jb(o)&&n.push({check:"Standalone MCP duplicate",status:"warn",message:"[mcp_servers.context-mode] is still registered while context-mode@context-mode is enabled; Codex may start both plugin and standalone MCP surfaces",fix:"context-mode upgrade (removes the standalone Codex MCP registration when the plugin owns context-mode)"});let l=this.readHooksConfig();if(!l.ok){if(l.reason==="missing"&&u){let h=Object.keys(i).map(m=>({check:`${m} hook`,status:"pass",message:`${m} hook provided by context-mode@context-mode plugin`}));return n.concat(h)}return l.reason==="missing"?n.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):l.reason==="invalid_json"?n.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${l.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):n.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${l.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}])}if(!l.config.hooks&&!u)return n.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let d=u?Object.keys(i).map(h=>({check:`${h} hook`,status:"pass",message:`${h} hook provided by context-mode@context-mode plugin`})):Object.entries(i).map(([h,m])=>{let f=l.config.hooks?.[h],g=m[0],y=Array.isArray(f)&&f.some(x=>this.isExpectedHookEntry(h,x,g)),_=h==="PreCompact"?"warn":"fail";return{check:`${h} hook`,status:y?"pass":_,message:y?`${h} hook configured in ${this.getHooksPath()}`:h==="PreCompact"?`${h} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${h} hook missing or not pointing to context-mode`,fix:y?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),p=[];for(let h of Object.keys(i)){let m=l.config.hooks?.[h];if(!Array.isArray(m))continue;let f=m.filter(g=>this.isManagedContextModeEntry(h,g)).length;f>1?p.push({check:`${h} duplicates`,status:"warn",message:`${f} context-mode entries found for ${h} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"}):u&&f===1&&p.push({check:`${h} plugin duplicate`,status:"warn",message:`${h} is configured in both ${this.getHooksPath()} and the context-mode Codex plugin; Codex will fire both hooks`,fix:"context-mode upgrade (removes user config context-mode hooks; preserves unrelated hooks)"})}return n.concat(d,p)}checkPluginRegistration(){try{let e=fs(this.getSettingsPath(),"utf-8"),n=Gb(e),r=Jb(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return n&&r?{check:"MCP registration",status:"warn",message:"context-mode@context-mode plugin is enabled, but standalone [mcp_servers.context-mode] is also configured",fix:"context-mode upgrade"}:n?{check:"MCP registration",status:"pass",message:"context-mode@context-mode plugin enabled"}:r?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:o?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let n=this.readHooksConfig(),r=[],o=this.getSettingsPath(),s="";try{s=fs(o,"utf-8")}catch{s=""}let a=this.getCodexPluginHookStatus(e,s,s.length>0).ownsHooksForUpgrade,c;if(n.ok)c=n.config;else if(n.reason==="missing")c={hooks:{}};else if(n.reason==="invalid_json"){let m=this.backupFile(this.getHooksPath(),".broken");r.push(`Backed up malformed Codex hooks to ${m}`),c={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${n.error}`);let u=c.hooks&&typeof c.hooks=="object"&&!Array.isArray(c.hooks)?c.hooks:{},l=this.generateHookConfig(e),d=r.length;if(a)for(let m of Object.keys(l))this.removeManagedHookEntries(u,m,r);else for(let[m,f]of Object.entries(l))this.upsertManagedHookEntry(u,m,f[0],r);r.length>d&&(c.hooks=u,this.writeHooksConfig(c),r.push(a?`Removed duplicate context-mode user hooks from ${this.getHooksPath()}`:`Wrote native Codex hooks to ${this.getHooksPath()}`));let p=VI(s).text,h=p!==s;if(a){let m=Xb(p,g=>g==="mcp_servers.context-mode"||g.startsWith("mcp_servers.context-mode.tools."));m.removed.length>0&&(p=m.text,r.push("Removed standalone Codex context-mode MCP registration"));let f=this.pruneStaleUserHookTrustState(p,u);f.removed.length>0&&(p=f.text,r.push(`Removed ${f.removed.length} stale Codex hook trust entr${f.removed.length===1?"y":"ies"}`))}if(p!==s){let m=p.includes(`\r
|
|
161
164
|
`)?`\r
|
|
162
165
|
`:`
|
|
163
|
-
`,
|
|
164
|
-
`)?
|
|
166
|
+
`,f=p.endsWith(`
|
|
167
|
+
`)?p:`${p}${m}`;Pp(Rp(o),{recursive:!0}),Kb(o,f,"utf-8"),h&&r.push("Enabled Codex hooks feature flag")}return r}backupSettings(){let e=null;for(let n of[this.getHooksPath(),this.getSettingsPath()])try{zI(n,HI.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=Dc(Rp(UI(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return fs(e,"utf-8")}catch{return`# context-mode
|
|
165
168
|
|
|
166
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.CODEX_PROJECT_DIR??process.cwd()}getHooksPath(){return
|
|
167
|
-
`,"utf-8")}upsertManagedHookEntry(e,r,
|
|
168
|
-
`,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},o=n.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=o,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=YO(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Ic(n,o);try{GO(s,XO.R_OK),JO(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}}});function Nb(t,e){if(!gp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Yt,gp,C9,O9,Db=S(()=>{"use strict";Yt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},gp={[Yt.PRE_TOOL_USE]:"pretooluse.mjs",[Yt.POST_TOOL_USE]:"posttooluse.mjs",[Yt.PRE_COMPACT]:"precompact.mjs",[Yt.SESSION_START]:"sessionstart.mjs"},C9=[Yt.PRE_TOOL_USE,Yt.SESSION_START],O9=[Yt.POST_TOOL_USE,Yt.PRE_COMPACT]});var jb={};we(jb,{VSCodeCopilotAdapter:()=>xp});import{readFileSync as yp,mkdirSync as Mb,accessSync as QO,existsSync as eI,constants as tI}from"node:fs";import{resolve as hs,join as Ai}from"node:path";import{homedir as _p}from"node:os";var xp,Lb=S(()=>{"use strict";hp();pt();Db();xp=class extends fs{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Yt,HOOK_SCRIPTS:gp,buildHookCommand:Nb};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.env.VSCODE_CWD||process.cwd()}getSessionDir(){let e=Pt();if(e){let s=Ai(e,"context-mode","sessions");return Mb(s,{recursive:!0}),s}let r=hs(".github","context-mode","sessions"),n=Ai(_p(),".vscode","context-mode","sessions"),o=eI(hs(".github"))?r:n;return Mb(o,{recursive:!0}),o}getConfigDir(e){return hs(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=hs(".github","hooks");try{QO(n,tI.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let o=hs(n,"context-mode.json");try{let s=yp(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Yt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Yt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),r.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),r}checkPluginRegistration(){try{let e=hs(".vscode","mcp.json"),r=yp(e,"utf-8"),o=JSON.parse(r).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[Ai(_p(),".vscode","extensions"),Ai(_p(),".vscode-insiders","extensions")];for(let r of e)try{let n=yp(Ai(r,"extensions.json"),"utf-8"),s=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function zb(t,e){if(!bp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Qt,bp,z9,F9,Fb=S(()=>{"use strict";Qt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},bp={[Qt.PRE_TOOL_USE]:"pretooluse.mjs",[Qt.POST_TOOL_USE]:"posttooluse.mjs",[Qt.PRE_COMPACT]:"precompact.mjs",[Qt.SESSION_START]:"sessionstart.mjs"},z9=[Qt.PRE_TOOL_USE,Qt.SESSION_START],F9=[Qt.POST_TOOL_USE,Qt.PRE_COMPACT]});var Hb={};we(Hb,{JetBrainsCopilotAdapter:()=>vp});import{readFileSync as rI}from"node:fs";import{resolve as nI}from"node:path";var vp,Ub=S(()=>{"use strict";hp();Fb();vp=class extends fs{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Qt,HOOK_SCRIPTS:bp,buildHookCommand:zb};hookSubdir="jetbrains-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.JETBRAINS_CLIENT_ID?`jetbrains-${process.env.JETBRAINS_CLIENT_ID}`:process.env.IDEA_HOME?`idea-${process.pid}`:`pid-${process.ppid}`}getProjectDir(){return process.env.IDEA_INITIAL_DIRECTORY||process.env.CLAUDE_PROJECT_DIR||process.cwd()}getConfigDir(e){return nI(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=rI(this.getSettingsPath(),"utf-8"),s=JSON.parse(n).hooks;s?.[Qt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Qt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),r}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let r=this.readSettings()?.hooks;return r&&Object.keys(r).length>0?"configured":"unknown"}}});function Ni(t,e){let r=Sp[e],n=er(e);if("command"in t){let s=t.command??"";return r!=null&&s.includes(r)||s.includes(n)}return t.hooks?.some(s=>{let i=s.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function er(t){return`context-mode hook cursor ${t.toLowerCase()}`}var be,Sp,oI,sI,kp,Bb,Zb,qb=S(()=>{"use strict";be={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Sp={[be.PRE_TOOL_USE]:"pretooluse.mjs",[be.POST_TOOL_USE]:"posttooluse.mjs",[be.SESSION_START]:"sessionstart.mjs",[be.STOP]:"stop.mjs",[be.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},oI="MCP:(?!ctx_)",sI=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",oI],kp=sI.join("|"),Bb=[be.PRE_TOOL_USE],Zb=[be.POST_TOOL_USE]});var Jb={};we(Jb,{CursorAdapter:()=>wp});import{readFileSync as Ac,writeFileSync as iI,mkdirSync as aI,accessSync as Vb,chmodSync as cI,constants as Wb,existsSync as Kb,readdirSync as uI}from"node:fs";import{execSync as lI}from"node:child_process";import{resolve as so,join as io}from"node:path";import{homedir as Nc}from"node:os";var Gb,wp,Xb=S(()=>{"use strict";pt();wn();qb();Gb="/Library/Application Support/Cursor/hooks.json",wp=class extends xe{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return so(".cursor","hooks.json")}getConfigDir(e){return so(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[be.PRE_TOOL_USE]:[{type:"command",command:er(be.PRE_TOOL_USE),matcher:kp,loop_limit:null,failClosed:!1}],[be.POST_TOOL_USE]:[{type:"command",command:er(be.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[be.SESSION_START]:[{type:"command",command:er(be.SESSION_START),loop_limit:null,failClosed:!1}],[be.STOP]:[{type:"command",command:er(be.STOP),loop_limit:null,failClosed:!1}],[be.AFTER_AGENT_RESPONSE]:[{type:"command",command:er(be.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=Ac(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();aI(so(".cursor"),{recursive:!0}),iI(r,JSON.stringify(e,null,2)+`
|
|
169
|
-
`,"utf-8")}
|
|
169
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.CODEX_PROJECT_DIR??process.cwd()}getHooksPath(){return Xn(this.getConfigDir(),"hooks.json")}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return FI(e,r),r}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(fs(e,"utf-8"))}}catch(n){let r=n instanceof Error?n.message:String(n);return(typeof n=="object"&&n!==null&&"code"in n?String(n.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:n instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:r}:{ok:!1,reason:"read_error",error:r}}}writeHooksConfig(e){let n=this.getHooksPath();Pp(Rp(n),{recursive:!0}),Kb(n,JSON.stringify(e,null,2)+`
|
|
170
|
+
`,"utf-8")}upsertManagedHookEntry(e,n,r,o){let s=Array.isArray(e[n])?[...e[n]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(n,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(r),e[n]=s,o.push(`Added ${n} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(r)&&(s[a]=r,o.push(`Updated ${n} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${n} context-mode hook`);e[n]=s}removeManagedHookEntries(e,n,r){let o=Array.isArray(e[n])?[...e[n]]:[],s=o.filter(a=>!this.isManagedContextModeEntry(n,a)),i=o.length-s.length;i!==0&&(s.length>0?e[n]=s:delete e[n],r.push(`Removed ${i} ${n} context-mode user hook${i===1?"":"s"}`))}hasCodexPluginHookManifest(e){return LI(Xn(e,".codex-plugin","hooks.json"))}getCodexPluginHookStatus(e,n,r){let o=r&&Gb(n),s=Dc(e),i=this.hasCodexPluginHookManifest(s),a=o?this.probeCodexContextModePluginRoot():null,c=a?this.hasCodexPluginHookManifest(a):!1,u=a?!this.samePath(s,a):!1;return{enabled:o,configuredRoot:s,configuredManifestAvailable:i,runtimeRoot:a,runtimeManifestAvailable:c,rootMismatch:u,hooksAvailable:o&&(c||!a&&i),ownsHooksForUpgrade:o&&a!==null&&c&&!u}}probeCodexContextModePluginRoot(){try{let e=process.platform==="win32"?this.codexPluginListRunner("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):this.codexPluginListRunner("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});return Mc(String(e))}catch{return null}}samePath(e,n){return this.normalizeCommand(Dc(e))===this.normalizeCommand(Dc(n))}pruneStaleUserHookTrustState(e,n){let r=this.normalizeCommand(this.getHooksPath()),o={post_compact:"PostCompact",post_tool_use:"PostToolUse",pre_compact:"PreCompact",pre_tool_use:"PreToolUse",session_start:"SessionStart",stop:"Stop",user_prompt_submit:"UserPromptSubmit"};return Xb(e,s=>{let i="hooks.state.";if(!s.startsWith(i))return!1;let a=WI(s.slice(i.length));if(a===null)return!1;let u=this.normalizeCommand(a).split(":"),l=Number(u.pop()),d=Number(u.pop()),p=o[u.pop()??""];if(u.join(":")!==r||!p||!Number.isInteger(d)||!Number.isInteger(l))return!1;let m=n[p]?.[d];return!m||!Array.isArray(m.hooks)||!m.hooks[l]})}isExpectedHookEntry(e,n,r){return!n||typeof n!="object"||e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}isManagedContextModeEntry(e,n){return!n||typeof n!="object"?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(Array.isArray(n.hooks)?n.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(ro[e]??""),s=ZI[e]??[];return r.some(i=>i.includes(o)||s.some(a=>i.includes(a)))}normalizeCommand(e){return(e??"").replace(/\\/g,"/")}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});import{readFileSync as nS,writeFileSync as KI,mkdirSync as GI,accessSync as JI,chmodSync as XI,constants as YI}from"node:fs";import{resolve as Lc,join as QI}from"node:path";var Er,zc=v(()=>{"use strict";it();Er=class extends be{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,updatedInput:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,additionalContext:e.additionalContext}};if(e.decision==="ask")return{permissionDecision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,decision:"block",reason:e.updatedOutput}};if(e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(e){return Lc(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule;return{[n.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_TOOL_USE,e)}]}],[n.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.POST_TOOL_USE,e)}]}],[n.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_COMPACT,e)}]}],[n.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:r(n.SESSION_START,e)}]}]}}readSettings(){try{let e=nS(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=nS(Lc(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();GI(Lc(".github","hooks"),{recursive:!0}),KI(n,JSON.stringify(e,null,2)+`
|
|
171
|
+
`,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],n.push(`Configured ${u} hook`));return r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`),n}setHookPermissions(e){let n=[],r=QI(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Lc(r,o);try{JI(s,YI.R_OK),XI(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function rS(t,e){if(!Ip[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Yt,Ip,r3,o3,oS=v(()=>{"use strict";Yt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Ip={[Yt.PRE_TOOL_USE]:"pretooluse.mjs",[Yt.POST_TOOL_USE]:"posttooluse.mjs",[Yt.PRE_COMPACT]:"precompact.mjs",[Yt.SESSION_START]:"sessionstart.mjs"},r3=[Yt.PRE_TOOL_USE,Yt.SESSION_START],o3=[Yt.POST_TOOL_USE,Yt.PRE_COMPACT]});var iS={};_e(iS,{VSCodeCopilotAdapter:()=>Dp});import{readFileSync as Ap,mkdirSync as sS,accessSync as eA,existsSync as tA,constants as nA}from"node:fs";import{resolve as hs,join as Di}from"node:path";import{homedir as Np}from"node:os";var Dp,aS=v(()=>{"use strict";zc();it();oS();Dp=class extends Er{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Yt,HOOK_SCRIPTS:Ip,buildHookCommand:rS};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.env.VSCODE_CWD||process.cwd()}getSessionDir(){let e=ht();if(e){let s=Di(e,"context-mode","sessions");return sS(s,{recursive:!0}),s}let n=hs(".github","context-mode","sessions"),r=Di(Np(),".vscode","context-mode","sessions"),o=tA(hs(".github"))?n:r;return sS(o,{recursive:!0}),o}getConfigDir(e){return hs(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=hs(".github","hooks");try{eA(r,nA.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=hs(r,"context-mode.json");try{let s=Ap(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Yt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Yt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),n.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),n}checkPluginRegistration(){try{let e=hs(".vscode","mcp.json"),n=Ap(e,"utf-8"),o=JSON.parse(n).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[Di(Np(),".vscode","extensions"),Di(Np(),".vscode-insiders","extensions")];for(let n of e)try{let r=Ap(Di(n,"extensions.json"),"utf-8"),s=JSON.parse(r).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function cS(t,e){if(!Mp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Qt,Mp,p3,m3,uS=v(()=>{"use strict";Qt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Mp={[Qt.PRE_TOOL_USE]:"pretooluse.mjs",[Qt.POST_TOOL_USE]:"posttooluse.mjs",[Qt.PRE_COMPACT]:"precompact.mjs",[Qt.SESSION_START]:"sessionstart.mjs"},p3=[Qt.PRE_TOOL_USE,Qt.SESSION_START],m3=[Qt.POST_TOOL_USE,Qt.PRE_COMPACT]});var lS={};_e(lS,{JetBrainsCopilotAdapter:()=>jp});import{readFileSync as rA}from"node:fs";import{resolve as oA}from"node:path";var jp,dS=v(()=>{"use strict";zc();uS();jp=class extends Er{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Qt,HOOK_SCRIPTS:Mp,buildHookCommand:cS};hookSubdir="jetbrains-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.JETBRAINS_CLIENT_ID?`jetbrains-${process.env.JETBRAINS_CLIENT_ID}`:process.env.IDEA_HOME?`idea-${process.pid}`:`pid-${process.ppid}`}getProjectDir(){return process.env.IDEA_INITIAL_DIRECTORY||process.env.CLAUDE_PROJECT_DIR||process.cwd()}getConfigDir(e){return oA(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=rA(this.getSettingsPath(),"utf-8"),s=JSON.parse(r).hooks;s?.[Qt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Qt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),n}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let n=this.readSettings()?.hooks;return n&&Object.keys(n).length>0?"configured":"unknown"}}});function pS(t,e){let n=Lp[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var St,Lp,b3,S3,mS=v(()=>{"use strict";St={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},Lp={[St.PRE_TOOL_USE]:"pretooluse.mjs",[St.POST_TOOL_USE]:"posttooluse.mjs",[St.PRE_COMPACT]:"precompact.mjs",[St.SESSION_START]:"sessionstart.mjs",[St.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[St.STOP]:"stop.mjs"},b3=[St.PRE_TOOL_USE,St.SESSION_START],S3=[St.POST_TOOL_USE,St.PRE_COMPACT,St.USER_PROMPT_SUBMIT,St.STOP]});var xS={};_e(xS,{CopilotCliAdapter:()=>Fp,copilotCliHome:()=>Hc,copilotCliMcpConfigPath:()=>Fc});import{existsSync as fS,mkdirSync as hS,readFileSync as zp,writeFileSync as sA}from"node:fs";import{homedir as gS}from"node:os";import{dirname as iA,join as gs,resolve as _S}from"node:path";function yS(){return process.env[aA]==="1"}function cA(t){return _S(t,"configs","copilot-cli","hooks.json")}function uA(t){return Kn(zp(t,"utf-8"))??{}}function lA(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function Hc(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?gs(gS(),t.replace(/^~[/\\]?/,"")):_S(t):gs(gS(),".copilot")}function Fc(){return gs(Hc(),"mcp-config.json")}var aA,Fp,bS=v(()=>{"use strict";zc();it();Ni();mS();aA="CONTEXT_MODE_COPILOT_PLUGIN";Fp=class extends Er{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:St,HOOK_SCRIPTS:Lp,buildHookCommand:pS};hookSubdir="copilot-cli";extractSessionId(e){let n=e;if(n.transcript_path){let r=n.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return n.conversation_id?n.conversation_id:n.session_id?n.session_id:e.sessionId?e.sessionId:`pid-${process.ppid}`}getProjectDir(){return process.cwd()}parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_result?.text_result_for_llm??n.toolResult?.textResultForLlm??(typeof n.tool_response=="string"?n.tool_response:void 0)??n.tool_output;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},toolOutput:r,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}getSettingsPath(e){return gs(Hc(),"hooks","context-mode.json")}getConfigDir(e){return Hc()}getSessionDir(){let e=ht(),n=e?gs(e,"context-mode","sessions"):gs(this.getConfigDir(),"context-mode","sessions");return hS(n,{recursive:!0}),n}getInstructionFiles(){return[".github/copilot-instructions.md","AGENTS.md"]}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule,o=i=>[{type:"command",command:r(i,e)}],s={};for(let i of Object.values(n))s[i]=o(i);return s}writeSettings(e){let n=this.getSettingsPath();hS(iA(n),{recursive:!0}),sA(n,JSON.stringify(e,null,2)+`
|
|
172
|
+
`,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule;for(let c of Object.values(s)){if(!i[c])continue;let u=[{type:"command",command:a(c,e)}];JSON.stringify(o[c])!==JSON.stringify(u)&&(o[c]=u,n.push(`Configured ${c} hook`))}return r.version!==1&&n.push("Set hooks schema version to 1"),n.length>0&&(r.version=1,r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`)),n}readSettings(){try{let e=zp(this.getSettingsPath(),"utf-8");return Kn(e)??null}catch{return null}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="ask")return{permissionDecision:"ask",permissionDecisionReason:e.reason??"Action requires user confirmation"};if(e.decision==="modify"&&e.updatedInput)return{modifiedArgs:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext}}formatPostToolUseResponse(e){if(e.updatedOutput)return{modifiedResult:{resultType:"success",textResultForLlm:e.updatedOutput}};if(e.additionalContext)return{additionalContext:e.additionalContext}}formatPreCompactResponse(e){}formatSessionStartResponse(e){return e.context?{additionalContext:e.context}:void 0}validateHooks(e){let n=[],r=yS(),o=r?cA(e):this.getSettingsPath(),s=r?`Copilot CLI plugin bundle hooks.json (${o})`:o,i=r?"copilot plugin install mksglu/context-mode:configs/copilot-cli":"context-mode upgrade";try{let a=uA(o),c=a.hooks;n.push({check:"Hooks schema version",status:a.version===1?"pass":"fail",message:a.version===1?`${s} declares the required "version": 1`:`${s} is missing top-level "version": 1`,...a.version===1?{}:{fix:i}});for(let u of Object.values(St)){let l=lA(c,u);n.push({check:`${u} hook`,status:l?"pass":"fail",message:l?`${u} hook configured in ${s}`:`${u} not found in ${s}`,...l?{}:{fix:i}})}}catch{n.push({check:"Hook configuration",status:"fail",message:`Could not read ${s}`,fix:i})}return n}checkPluginRegistration(){if(yS())return{check:"MCP registration",status:"pass",message:"context-mode loaded from the Copilot CLI plugin bundle"};try{let e=zp(Fc(),"utf-8");return"context-mode"in((Kn(e)??{})?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in Copilot CLI mcp-config.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in Copilot CLI mcpServers",fix:"copilot mcp add context-mode -- context-mode"}}catch{return{check:"MCP registration",status:"fail",message:`Could not read ${Fc()}`,fix:"copilot mcp add context-mode -- context-mode"}}}getInstalledVersion(){return fS(Fc())||fS(this.getSettingsPath())?"standalone":"not installed"}}});function Mi(t,e){let n=Hp[e],r=en(e);if("command"in t){let s=t.command??"";return n!=null&&s.includes(n)||s.includes(r)}return t.hooks?.some(s=>{let i=s.command??"";return n!=null&&i.includes(n)||i.includes(r)})??!1}function en(t){return`context-mode hook cursor ${t.toLowerCase()}`}var Se,Hp,dA,pA,Up,SS,vS,kS=v(()=>{"use strict";Se={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Hp={[Se.PRE_TOOL_USE]:"pretooluse.mjs",[Se.POST_TOOL_USE]:"posttooluse.mjs",[Se.SESSION_START]:"sessionstart.mjs",[Se.STOP]:"stop.mjs",[Se.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},dA="MCP:(?!ctx_)",pA=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",dA],Up=pA.join("|"),SS=[Se.PRE_TOOL_USE],vS=[Se.POST_TOOL_USE]});var PS={};_e(PS,{CursorAdapter:()=>Bp});import{readFileSync as Uc,writeFileSync as mA,mkdirSync as fA,accessSync as wS,chmodSync as hA,constants as ES,existsSync as TS,readdirSync as gA}from"node:fs";import{execSync as yA}from"node:child_process";import{resolve as oo,join as so}from"node:path";import{homedir as Bc}from"node:os";var $S,Bp,RS=v(()=>{"use strict";it();kr();kS();$S="/Library/Application Support/Cursor/hooks.json",Bp=class extends be{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output??n.error_message,isError:!!n.error_message,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??n.trigger??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let n=e;return{sessionId:n.conversation_id??`pid-${process.ppid}`,status:n.status??"completed",loopCount:n.loop_count??0,generationId:n.generation_id,transcriptPath:n.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return oo(".cursor","hooks.json")}getConfigDir(e){return oo(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[Se.PRE_TOOL_USE]:[{type:"command",command:en(Se.PRE_TOOL_USE),matcher:Up,loop_limit:null,failClosed:!1}],[Se.POST_TOOL_USE]:[{type:"command",command:en(Se.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[Se.SESSION_START]:[{type:"command",command:en(Se.SESSION_START),loop_limit:null,failClosed:!1}],[Se.STOP]:[{type:"command",command:en(Se.STOP),loop_limit:null,failClosed:!1}],[Se.AFTER_AGENT_RESPONSE]:[{type:"command",command:en(Se.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let n=Uc(e,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let n=this.getSettingsPath();fA(oo(".cursor"),{recursive:!0}),mA(n,JSON.stringify(e,null,2)+`
|
|
173
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.loadNativeHookConfig();if(!r)n.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let s=r.config.hooks??{};n.push({check:"Native hook config",status:"pass",message:`Loaded ${r.path}`});for(let i of SS){let a=s[i],c=Array.isArray(a)&&a.some(u=>Mi(u,i));n.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${r.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of vS){let a=s[i],c=Array.isArray(a)&&a.some(u=>Mi(u,i));n.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}TS($S)&&n.push({check:"Enterprise hook config",status:"warn",message:"Enterprise Cursor hook config detected at /Library/Application Support/Cursor/hooks.json (read-only informational layer)"}),this.hasClaudeCompatibilityHooks()&&n.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let o=this.detectPluginInstalls();return o.length>0&&((r?Object.entries(r.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>Mi(c,i))):!1)&&r?n.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${r.path} \u2014 each event will fire twice. Remove one configuration to avoid duplicate routing.`,fix:"Remove the native .cursor/hooks.json entries OR uninstall the plugin"}):n.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),n}detectPluginInstalls(){let e=[so(Bc(),".cursor","plugins","local"),so(Bc(),".cursor","plugins","cache")],n=[];for(let r of e){try{wS(r,ES.F_OK)}catch{continue}let o=[];try{o=gA(r)}catch{continue}for(let s of o){let i=so(r,s,".cursor-plugin","plugin.json");try{let a=Uc(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&n.push(i)}catch{continue}}}return n}checkPluginRegistration(){let e=[oo(".cursor","mcp.json"),so(Bc(),".cursor","mcp.json")];for(let r of e)try{let o=Uc(r,"utf-8"),s=JSON.parse(o),i=s.mcpServers??s.servers;if(!i)continue;if(Object.entries(i).some(([c,u])=>c.includes("context-mode")?!0:!u||typeof u!="object"?!1:u.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${r}`}}catch{continue}let n=this.detectPluginInstalls();return n.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${n[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return yA("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=this.readSettings()??{version:1,hooks:{}},r=n.hooks??{},o=[];return this.upsertHookEntry(r,Se.PRE_TOOL_USE,{type:"command",command:en(Se.PRE_TOOL_USE),matcher:Up,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,Se.POST_TOOL_USE,{type:"command",command:en(Se.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,Se.SESSION_START,{type:"command",command:en(Se.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,Se.STOP,{type:"command",command:en(Se.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,Se.AFTER_AGENT_RESPONSE,{type:"command",command:en(Se.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),n.version=1,n.hooks=r,this.writeSettings(n),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let n=[],r=so(e,"hooks","cursor");for(let o of Object.values(Hp)){let s=oo(r,o);try{wS(s,ES.R_OK),hA(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),so(Bc(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push($S),e}getProjectDir(e){return e.cwd||e.workspace_roots?.[0]||process.env.CURSOR_CWD||process.cwd()}extractSessionId(e){return e.conversation_id?e.conversation_id:e.session_id?e.session_id:process.env.CURSOR_SESSION_ID?process.env.CURSOR_SESSION_ID:process.env.CURSOR_TRACE_ID?process.env.CURSOR_TRACE_ID:`pid-${process.ppid}`}loadNativeHookConfig(){for(let e of this.getCandidateHookConfigPaths())try{let n=Uc(e,"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object")return{path:e,config:r}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[oo(".claude","settings.json"),oo(".claude","settings.local.json"),so(Be(),"settings.json")].some(n=>TS(n))}upsertHookEntry(e,n,r,o){let s=e[n],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>Mi(c,n));a>=0?(i[a]=r,o.push(`Updated existing ${n} hook entry`)):(i.push(r),o.push(`Added ${n} hook entry`)),e[n]=i}}});var OS={};_e(OS,{AntigravityAdapter:()=>ji});import{readFileSync as Zc,writeFileSync as _A,mkdirSync as xA}from"node:fs";import{resolve as qc,dirname as CS}from"node:path";import{fileURLToPath as bA}from"node:url";import{homedir as Zp}from"node:os";var ji,qp=v(()=>{"use strict";it();ji=class extends be{constructor(){super([".gemini"])}name="Antigravity";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePostToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePreCompactInput(e){throw new Error("Antigravity does not support hooks")}parseSessionStartInput(e){throw new Error("Antigravity does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return qc(Zp(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return qc(Zp(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Zc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();xA(CS(n),{recursive:!0}),_A(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Antigravity does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Zc(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.gemini/antigravity/mcp_config.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.gemini/antigravity/mcp_config.json"}}}getInstalledVersion(){try{let e=qc(Zp(),".gemini","extensions","context-mode","package.json");return JSON.parse(Zc(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=qc(CS(bA(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Zc(e,"utf-8")}catch{return`# context-mode
|
|
170
174
|
|
|
171
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});
|
|
175
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});var FS={};_e(FS,{AntigravityCliAdapter:()=>Xp,antigravityCliConfigDir:()=>LS,antigravityCliHooksPath:()=>Wp,antigravityCliMcpConfigPath:()=>jS,antigravityCliPluginDir:()=>Kc});import{mkdirSync as SA,readFileSync as Vc,writeFileSync as vA}from"node:fs";import{dirname as kA,resolve as io}from"node:path";import{homedir as Wc}from"node:os";function jS(){return io(Wc(),".gemini","config","mcp_config.json")}function LS(){return io(Wc(),".gemini","antigravity-cli")}function Wp(){return io(Wc(),".gemini","config","hooks.json")}function Kc(){return io(Wc(),".gemini","config","plugins","context-mode")}function wA(){return io(Kc(),"mcp_config.json")}function EA(){return io(Kc(),"hooks.json")}function IS(t){for(let e of t)try{if("context-mode"in((Kn(Vc(e,"utf-8"))??{})?.mcpServers??{}))return{ok:!0,where:e}}catch{}return{ok:!1}}function In(t){return t&&typeof t=="object"?t:{}}function AS(t){let e=In(t.workspace);if(typeof e.current_dir=="string"&&e.current_dir)return e.current_dir;let n=t.workspacePaths;return Array.isArray(n)&&n.length>0?String(n[0]):void 0}function NS(t){return typeof t.conversationId=="string"&&t.conversationId?t.conversationId:`pid-${process.ppid}`}function zS(t,e){let n=In(t);return(Array.isArray(n.hooks)?n.hooks:[]).some(o=>In(o).command===e)}function DS(t,e){return JSON.stringify(t).includes(e)}function TA(t){return typeof t!="string"?!1:["run_command","view_file","grep_search","web_fetch","read_url_content"].every(e=>t.includes(e))}function MS(t,e){return Array.isArray(t)&&t.some(n=>zS(n,e))}function $A(t){return Array.isArray(t)&&t.some(e=>{let n=In(e);return TA(n.matcher)&&zS(e,Kp)})}function PA(t){let e={preOk:!1,postOk:!1,stopOk:!1,where:void 0};for(let n of t)try{let o=(Kn(Vc(n,"utf-8"))??{}).hooks??{},s=$A(o.PreToolUse),i=MS(o.PostToolUse,Gp),a=MS(o.Stop,Jp);(s||i||a)&&!e.where&&(e.where=n),e.preOk||=s,e.postOk||=i,e.stopOk||=a}catch{}return{...e,ok:e.preOk&&e.postOk}}function CA(t){let e=String(t??"").replace(/<\/?context_guidance>/g," ").replace(/<\/?tip>/g," ").replace(/\s+/g," ").trim();return e?`context-mode: use the context-mode MCP tools instead of this native tool. ${e}`:"context-mode: use the context-mode MCP tools instead of this native tool so raw bytes stay out of the conversation."}function Vp(t,e,n,r){let o=Array.isArray(t[e])?t[e]:[],s=JSON.stringify(n);return o.some(a=>JSON.stringify(a)===s)&&o.every(a=>!DS(a,r)||JSON.stringify(a)===s)?!1:(t[e]=[...o.filter(a=>!DS(a,r)),n],!0)}var Kp,RA,Gp,Jp,Xp,HS=v(()=>{"use strict";qp();Ni();Kp="context-mode hook antigravity-cli pretooluse",RA="run_command|view_file|grep_search|web_fetch|read_url_content",Gp="context-mode hook antigravity-cli posttooluse",Jp="context-mode hook antigravity-cli stop";Xp=class extends ji{name="Antigravity CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};getSettingsPath(){return jS()}getConfigDir(e){return LS()}parsePreToolUseInput(e){let n=In(e),r=In(n.toolCall);return{toolName:typeof r.name=="string"?r.name:"",toolInput:In(r.args),sessionId:NS(n),projectDir:AS(n),raw:e}}parsePostToolUseInput(e){let n=In(e),r=In(n.toolCall),o=typeof n.error=="string"?n.error:"";return{toolName:typeof r.name=="string"?r.name:"",toolInput:In(r.args),toolOutput:o,isError:o.length>0,sessionId:NS(n),projectDir:AS(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{decision:"deny",reason:e.reason??"Denied by context-mode"}:e.decision==="ask"?{decision:"ask",reason:e.reason??"Action requires user confirmation"}:e.decision==="context"&&e.additionalContext?{decision:"deny",reason:CA(e.additionalContext)}:null}formatPostToolUseResponse(e){}checkPluginRegistration(){let{ok:e,where:n}=IS([wA(),this.getSettingsPath()]);return e?{check:"MCP registration",status:"pass",message:`context-mode found in Antigravity CLI mcpServers (${n})`}:{check:"MCP registration",status:"fail",message:"context-mode not found in Antigravity CLI mcpServers",fix:"npm run install:agy"}}getInstalledVersion(){try{let e=Kn(Vc(io(Kc(),"plugin.json"),"utf-8"));if(e&&typeof e.version=="string"&&e.version)return e.version}catch{}return IS([this.getSettingsPath()]).ok?"standalone":"not installed"}configureAllHooks(e){let n=[],r=Wp(),o={};try{o=Kn(Vc(r,"utf-8"))??{}}catch{}let s=o.hooks??{},i={matcher:RA,hooks:[{type:"command",command:Kp}]},a={matcher:"",hooks:[{type:"command",command:Gp}]},c={matcher:"",hooks:[{type:"command",command:Jp}]},u=Vp(s,"PreToolUse",i,Kp),l=Vp(s,"PostToolUse",a,Gp),d=Vp(s,"Stop",c,Jp);return(u||l||d)&&(o.hooks=s,SA(kA(r),{recursive:!0}),vA(r,JSON.stringify(o,null,2)+`
|
|
176
|
+
`,"utf-8"),n.push(`Configured Antigravity CLI PreToolUse/PostToolUse hooks and best-effort Stop hook in ${r}`)),n}validateHooks(e){let{ok:n,where:r,preOk:o,postOk:s,stopOk:i}=PA([EA(),Wp()]),a=[o?null:"PreToolUse",s?null:"PostToolUse"].filter(Boolean).join(", ");return[{check:"Antigravity CLI hooks",status:n?"pass":"warn",message:n?`PreToolUse guard and PostToolUse capture configured in ${r}${i?"; best-effort Stop hook also configured":""}`:`Antigravity CLI hooks incomplete (${a||"none found"} missing) \u2014 MCP tools still work, but bounded routing enforcement and session capture are degraded. Run \`npm run install:agy\` (agy plugin) or \`context-mode upgrade\` to repair hooks.`,...n?{}:{fix:"npm run install:agy"}}]}}});function Gc(t,e){let n=US[e];return n&&(t.command?.includes(n)||t.command?.includes("context-mode hook kiro"))||!1}function ys(t,e){let n=US[t];return e&&n?Ke(`${e}/hooks/kiro/${n}`):`context-mode hook kiro ${t.toLowerCase()}`}var ze,US,OA,IA,Yp,G3,J3,BS=v(()=>{"use strict";Rn();ze={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},US={[ze.PRE_TOOL_USE]:"pretooluse.mjs",[ze.POST_TOOL_USE]:"posttooluse.mjs",[ze.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[ze.AGENT_SPAWN]:"agentspawn.mjs"},OA="@(?!context-mode/)",IA=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",OA],Yp=IA.join("|"),G3=[ze.PRE_TOOL_USE,ze.AGENT_SPAWN],J3=[ze.POST_TOOL_USE,ze.USER_PROMPT_SUBMIT]});var WS={};_e(WS,{KiroAdapter:()=>Qp});import{readFileSync as _s,writeFileSync as ZS,mkdirSync as qS}from"node:fs";import{resolve as ao,dirname as VS}from"node:path";import{fileURLToPath as AA}from"node:url";import{homedir as Jc}from"node:os";var Qp,KS=v(()=>{"use strict";it();BS();Qp=class extends be{constructor(){super([".kiro"])}name="Kiro";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_response;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:typeof r=="string"?r:JSON.stringify(r??""),sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let n=e??{};return{source:n.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}formatPreToolUseResponse(e){switch(e.decision){case"deny":return{exitCode:2,stderr:e.reason??"Blocked by context-mode"};case"context":return{exitCode:0,stdout:e.additionalContext??""};default:return}}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){if(e?.context)return{hookSpecificOutput:{hookEventName:"agentSpawn",additionalContext:e.context}}}getSettingsPath(){return ao(Jc(),".kiro","settings","mcp.json")}getConfigDir(e){return ao(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[ze.PRE_TOOL_USE]:[{matcher:Yp,hooks:[{type:"command",command:ys(ze.PRE_TOOL_USE,e)}]}],[ze.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:ys(ze.POST_TOOL_USE,e)}]}],[ze.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:ys(ze.AGENT_SPAWN,e)}]}],[ze.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:ys(ze.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=_s(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();qS(VS(n),{recursive:!0}),ZS(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let n=[],r=ao(Jc(),".kiro","agents","default.json");try{let s=JSON.parse(_s(r,"utf-8")).hooks??{};for(let i of[ze.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>Gc(u,i));n.push({check:`Hook: ${i}`,status:c?"pass":"fail",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured`,...c?{}:{fix:"Run: context-mode upgrade"}})}for(let i of[ze.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>Gc(u,i));n.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{n.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return n}checkPluginRegistration(){try{let e=_s(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.kiro/settings/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.kiro/settings/mcp.json"}}}getInstalledVersion(){try{let e=ao(Jc(),".kiro","extensions","context-mode","package.json");return JSON.parse(_s(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=[],r=ao(Jc(),".kiro","agents"),o=ao(r,"default.json");try{qS(r,{recursive:!0});let s={};try{s=JSON.parse(_s(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[ze.PRE_TOOL_USE,Yp],[ze.POST_TOOL_USE,"*"],[ze.AGENT_SPAWN,"*"],[ze.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>Gc(d,c))||(l.push({matcher:u,command:ys(c,e)}),i[c]=l,n.push(`Added ${c} hook to ${o}`))}s.hooks=i,ZS(o,JSON.stringify(s,null,2),"utf-8")}catch(s){n.push(`Failed to configure hooks: ${s.message}`)}return n}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=ao(VS(AA(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return _s(e,"utf-8")}catch{return`# context-mode
|
|
172
177
|
|
|
173
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});var
|
|
178
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});var XS={};_e(XS,{ZedAdapter:()=>tm});import{readFileSync as em,writeFileSync as NA,mkdirSync as DA}from"node:fs";import{resolve as GS,dirname as JS}from"node:path";import{fileURLToPath as MA}from"node:url";import{homedir as jA}from"node:os";var tm,YS=v(()=>{"use strict";it();tm=class extends be{constructor(){super([".config","zed"])}name="Zed";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Zed does not support hooks")}parsePostToolUseInput(e){throw new Error("Zed does not support hooks")}parsePreCompactInput(e){throw new Error("Zed does not support hooks")}parseSessionStartInput(e){throw new Error("Zed does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return GS(jA(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=em(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();DA(JS(n),{recursive:!0}),NA(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Zed does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=em(this.getSettingsPath(),"utf-8"),r=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:r?{check:"MCP registration",status:"fail",message:"context_servers section exists but context-mode not found",fix:"Add context-mode to context_servers in ~/.config/zed/settings.json"}:{check:"MCP registration",status:"fail",message:"No context_servers section in settings.json",fix:"Add context_servers.context-mode to ~/.config/zed/settings.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.config/zed/settings.json"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=GS(JS(MA(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return em(e,"utf-8")}catch{return`# context-mode
|
|
174
179
|
|
|
175
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var
|
|
180
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var nm,QS=v(()=>{"use strict";nm="mcp__(?!.*context-mode)"});var nv={};_e(nv,{QwenCodeAdapter:()=>rm});import{readFileSync as LA,writeFileSync as zA,existsSync as FA}from"node:fs";import{resolve as ev,join as HA}from"node:path";import{homedir as tv}from"node:os";var rm,rv=v(()=>{"use strict";dp();QS();Rn();rm=class extends ds{constructor(){super([".qwen"])}name="Qwen Code";paradigm="json-stdio";projectDirEnvVar="QWEN_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getSettingsPath(){return ev(tv(),".qwen","settings.json")}getInstructionFiles(){return["QWEN.md"]}generateHookConfig(e){return{PreToolUse:[{matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",nm].join("|"),hooks:[{type:"command",command:Ke(`${e}/hooks/pretooluse.mjs`)}]}],PostToolUse:[{matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__",hooks:[{type:"command",command:Ke(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Ke(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Ke(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Ke(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=LA(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){zA(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let n=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit"]){let i=Array.isArray(o[s])&&o[s].length>0;n.push({check:`${s} hook`,status:i?"pass":"fail",message:i?`${s} hook configured in ~/.qwen/settings.json`:`${s} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${s} hook to ~/.qwen/settings.json`}})}return n}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let n=e.mcpServers;return Object.keys(n).some(r=>r.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in mcpServers"}:{check:"Plugin registration",status:"fail",message:"mcpServers exists but context-mode not found",fix:"Add context-mode to mcpServers in ~/.qwen/settings.json"}}return{check:"Plugin registration",status:"warn",message:"No mcpServers in ~/.qwen/settings.json"}}catch{return{check:"Plugin registration",status:"warn",message:"Could not read ~/.qwen/settings.json"}}}getInstalledVersion(){let e=this.readSettings();if(!e)return"not installed";let n=e.hooks;if(!n)return"not installed";let r=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(n))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&r.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[];for(let i of Object.keys(r)){let a=r[i];if(!Array.isArray(a))continue;let c=a.filter(l=>{let p=l.hooks??[];return p.some(m=>m.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(m.command))?p.every(m=>{if(!m.command)return!0;let f=m.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=m.command.match(/node\s+"?([^"]+\.mjs)"?/),y=f||g;return y?FA(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(r[i]=c,o.push(`Removed ${u} stale ${i} hook(s)`))}let s=[{name:"PreToolUse",script:"pretooluse.mjs",matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",nm].join("|")},{name:"PostToolUse",script:"posttooluse.mjs",matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__"},{name:"SessionStart",script:"sessionstart.mjs",matcher:""},{name:"PreCompact",script:"precompact.mjs",matcher:""},{name:"UserPromptSubmit",script:"userpromptsubmit.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:Ke(`${e}/hooks/${a}`)}]},l=r[i];if(l&&Array.isArray(l)){let d=l.findIndex(p=>p.hooks?.some(m=>m.command?.includes(a))??!1);d>=0?(l[d]=u,o.push(`Updated ${i} hook`)):(l.push(u),o.push(`Added ${i} hook`)),r[i]=l}else r[i]=[u],o.push(`Created ${i} hooks`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructionsConfig(){return{instructionsPath:ev(HA(tv(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var ov={};_e(ov,{OMPAdapter:()=>im});import{readFileSync as om,writeFileSync as UA,mkdirSync as BA}from"node:fs";import{resolve as sm,dirname as ZA}from"node:path";import{homedir as qA}from"node:os";var im,sv=v(()=>{"use strict";it();im=class extends be{constructor(){super([".omp"])}name="OMP";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePostToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePreCompactInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parseSessionStartInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getAgentDir(){return process.env.PI_CODING_AGENT_DIR??sm(qA(),".omp","agent")}getSettingsPath(){return sm(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=om(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();BA(ZA(n),{recursive:!0}),UA(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"context-mode delivers via MCP for OMP. Native OMP pre/post tool-call hooks are not yet wired by this adapter."}]}checkPluginRegistration(){try{let e=om(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:`Add context-mode to mcpServers in ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){try{let e=sm(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(om(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
|
|
176
181
|
|
|
177
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}});var
|
|
182
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}});var iv={};_e(iv,{PiAdapter:()=>lm});import{readFileSync as am,writeFileSync as VA,mkdirSync as WA}from"node:fs";import{resolve as cm,dirname as KA}from"node:path";import{homedir as um}from"node:os";var lm,av=v(()=>{"use strict";it();lm=class extends be{constructor(){super([".pi"])}name="Pi";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePostToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePreCompactInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parseSessionStartInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return cm(um(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=am(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();WA(KA(n),{recursive:!0}),VA(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"pass",message:"Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/), not via JSON-stdio."}]}checkPluginRegistration(){let e=cm(um(),".pi","extensions","context-mode","package.json");try{return JSON.parse(am(e,"utf-8"))?.name==="context-mode"?{check:"Pi extension registration",status:"pass",message:`context-mode extension installed at ${e}`}:{check:"Pi extension registration",status:"warn",message:`Unexpected package at ${e}`}}catch{return{check:"Pi extension registration",status:"fail",message:`context-mode not found at ${e}`,fix:"Run: context-mode upgrade"}}}getInstalledVersion(){try{let e=cm(um(),".pi","extensions","context-mode","package.json");return JSON.parse(am(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
|
|
178
183
|
|
|
179
|
-
Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});import{homedir as
|
|
180
|
-
`)}function
|
|
184
|
+
Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});import{homedir as cv}from"node:os";import{resolve as dm}from"node:path";function uv(){let t=process.env.KIMI_CODE_HOME;return t?t.startsWith("~")?dm(cv(),t.replace(/^~[/\\]?/,"")):dm(t):dm(cv(),".kimi-code")}var lv=v(()=>{"use strict"});var hv={};_e(hv,{KimiAdapter:()=>mm,probeKimiCliVersion:()=>fv});import{execFileSync as GA}from"node:child_process";import{readFileSync as Li,writeFileSync as JA,accessSync as XA,copyFileSync as YA,constants as QA,mkdirSync as dv}from"node:fs";import{resolve as eN,dirname as pv,join as co}from"node:path";import{fileURLToPath as tN}from"node:url";function fv(t=GA){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","kimi --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("kimi",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function mv(t){let e=[],n=t.split(/\r?\n/),r=null;for(let o of n){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(o)){r&&r.event&&r.command&&e.push(r),r={};continue}if(!r)continue;let s=o.match(/^\s*(\w+)\s*=\s*(?:"([^"]*)"|(\d+))\s*(?:#.*)?$/);if(s){let i=s[1],a=s[2],c=s[3];a!==void 0?r[i]=a:c!==void 0&&(r[i]=Number(c))}}return r&&r.event&&r.command&&e.push(r),e}function oN(t){let e=["[[hooks]]"];return e.push(`event = "${t.event}"`),t.matcher&&e.push(`matcher = "${t.matcher}"`),e.push(`command = "${t.command}"`),t.timeout!==void 0&&e.push(`timeout = ${t.timeout}`),e.join(`
|
|
185
|
+
`)}function pm(t){return t.command.includes("context-mode hook kimi")}function sN(t,e){let n=(e.hooks?.[0]?.command??"").trim();return n?{event:t,matcher:e.matcher||void 0,command:n,timeout:30}:null}var nN,Tr,rN,mm,gv=v(()=>{"use strict";it();Jt();lv();nN="Bash|Shell|Read|Edit|Write|WebFetch|Agent|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",Tr={PreToolUse:"context-mode hook kimi pretooluse",PostToolUse:"context-mode hook kimi posttooluse",SessionStart:"context-mode hook kimi sessionstart",SessionEnd:"context-mode hook kimi sessionend",PreCompact:"context-mode hook kimi precompact",UserPromptSubmit:"context-mode hook kimi userpromptsubmit",Stop:"context-mode hook kimi stop"},rN={PreToolUse:["hooks/pretooluse.mjs","hooks/kimi/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/kimi/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/kimi/sessionstart.mjs"],SessionEnd:["hooks/sessionend.mjs","hooks/kimi/sessionend.mjs"],PreCompact:["hooks/precompact.mjs","hooks/kimi/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/kimi/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/kimi/stop.mjs"]};mm=class extends be{constructor(){super([".kimi-code"])}name="Kimi Code CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,o=(n.source??"startup")==="resume"?"resume":"startup";return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return uv()}getSettingsPath(){return co(this.getConfigDir(),"config.toml")}getMcpPath(){return co(this.getConfigDir(),"mcp.json")}getSessionDir(){let e=ht(),n=e?co(e,"context-mode","sessions"):co(this.getConfigDir(),"context-mode","sessions");return dv(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=ht(),r=n?co(n,"context-mode","memory"):co(this.getConfigDir(),"memory");return e?co(r,rt(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:nN,hooks:[{type:"command",command:Tr.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:Tr.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Tr.SessionStart}]}],SessionEnd:[{matcher:"",hooks:[{type:"command",command:Tr.SessionEnd}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Tr.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Tr.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Tr.Stop}]}]}}readSettings(){try{return{_raw_toml:Li(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=fv();n.push({check:"Kimi Code CLI binary",status:r?"pass":"warn",message:r?`kimi --version resolved to ${r}`:"Could not run kimi --version; hooks need the Kimi Code CLI available on PATH",...r?{}:{fix:"Install Kimi Code CLI or make kimi available on PATH"}});let o="";try{o=Li(this.getSettingsPath(),"utf-8")}catch{return n.push({check:"Hooks config",status:"fail",message:`No readable ${this.getSettingsPath()} found`,fix:"Run context-mode upgrade to generate the initial config.toml"}),n}let s=mv(o),i=this.generateHookConfig("");for(let[a,c]of Object.entries(i)){let u=c[0],l=s.some(p=>p.event===a&&this.isExpectedHookEntry(a,p,u)),d=a==="PreCompact"?"warn":"fail";n.push({check:`${a} hook`,status:l?"pass":d,message:l?`${a} hook configured in ${this.getSettingsPath()}`:a==="PreCompact"?`${a} hook missing or not pointing to context-mode; compaction snapshots require a Kimi build that emits PreCompact`:`${a} hook missing or not pointing to context-mode`,fix:l?void 0:`Update ${this.getSettingsPath()} to include the managed ${a} [[hooks]] entry`})}for(let a of Object.keys(i)){let c=s.filter(u=>u.event===a&&pm(u)).length;c>1&&n.push({check:`${a} duplicates`,status:"warn",message:`${c} context-mode entries found for ${a} in ${this.getSettingsPath()}; Kimi will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"})}return n}checkPluginRegistration(){try{let e=Li(this.getMcpPath(),"utf-8"),n=JSON.parse(e),r=e.includes("context-mode"),o=n.mcpServers!==void 0||n.mcp_servers!==void 0;return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in mcp.json"}:o?{check:"MCP registration",status:"fail",message:"mcpServers section exists but context-mode not found",fix:`Add context-mode to mcpServers in ${this.getMcpPath()}`}:{check:"MCP registration",status:"fail",message:"No mcpServers section in mcp.json",fix:`Add mcpServers.context-mode to ${this.getMcpPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getMcpPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let n=[],r=this.generateHookConfig(""),o="";try{o=Li(this.getSettingsPath(),"utf-8")}catch{o=""}let s=mv(o),i=s.filter(l=>!pm(l)),a=[];for(let[l,d]of Object.entries(r)){let p=sN(l,d[0]);p&&a.push(p)}let c=s.some(pm),u=this.rebuildToml(o,i,a);return u!==o&&(dv(pv(this.getSettingsPath()),{recursive:!0}),JA(this.getSettingsPath(),u,"utf-8"),c?n.push(`Updated managed Kimi hooks in ${this.getSettingsPath()}`):n.push(`Wrote managed Kimi hooks to ${this.getSettingsPath()}`)),n}backupSettings(){let e=null;for(let n of[this.getSettingsPath(),this.getMcpPath()])try{XA(n,QA.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=eN(pv(tN(import.meta.url)),"..","..","..","configs","kimi","AGENTS.md");try{return Li(e,"utf-8")}catch{return`# context-mode
|
|
181
186
|
|
|
182
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.KIMI_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}backupFile(e,
|
|
183
|
-
`)}}});var zc={};we(zc,{PLATFORM_ENV_VARS:()=>_s,__resetClaudeCodePluginCacheForTests:()=>qI,__seedClaudeCodePluginCacheMissForTests:()=>VI,detectPlatform:()=>vt,foreignIdentificationEnv:()=>JI,foreignWorkspaceEnv:()=>GI,getAdapter:()=>xs,getEnvVarNames:()=>KI,getSessionDirSegments:()=>Mi,workspaceEnvVarsFor:()=>Bp});import{existsSync as Rt,readFileSync as BI}from"node:fs";import{resolve as bt}from"node:path";import{homedir as Cv}from"node:os";function ZI(){if(uo!==null)return uo!=="miss"&&uo.hasCM;try{let t=bt(Cv(),".claude","plugins","installed_plugins.json"),e=BI(t,"utf-8"),r=JSON.parse(e),o=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(s=>s.includes("context-mode"));return uo={hasCM:o},o}catch{return uo="miss",!1}}function qI(){uo=null}function VI(){uo="miss"}function KI(t){return(_s.get(t)??[]).map(e=>e.name)}function Bp(t){return(_s.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function GI(t){let e=new Set;for(let[r,n]of _s)if(r!==t)for(let o of n)o.role==="workspace"&&e.add(o.name);return e}function JI(t){let e=new Set;for(let[r,n]of _s)if(r!==t)for(let o of n)o.role==="identification"&&e.add(o.name);return e}function Mi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kimi":return[".kimi-code"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function vt(t){if(t?.name){let n=Nx[t.name];if(n)return{platform:n,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","cursor","antigravity","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,o]of _s)if(o.some(s=>s.detect!==!1&&process.env[s.name]))return n==="vscode-copilot"&&ZI()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:n,confidence:"high",reason:`${o.filter(s=>s.detect!==!1).map(s=>s.name).join(" or ")} env var set`};let r=Cv();return Rt(bt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Rt(bt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Rt(bt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Rt(bt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Rt(bt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Rt(bt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Rt(bt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Rt(bt(r,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:Rt(bt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Rt(bt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Rt(bt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Rt(bt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Rt(bt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Rt(bt(r,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function xs(t){let e=t??vt().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(rp(),tp));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(hb(),fb));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(xb(),_b));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(Sb(),vb));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(Ib(),Ob));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(Lb(),jb));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(Ub(),Hb));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(Xb(),Jb));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(ev(),Qb));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(av(),iv));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(dv(),lv));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(gv(),hv));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(_v(),yv));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(bv(),xv));return new r}case"kimi":{let{KimiAdapter:r}=await Promise.resolve().then(()=>(Rv(),Pv));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(rp(),tp));return new r}}}var uo,WI,_s,Tn=S(()=>{"use strict";Dx();uo=null;WI=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"}]]],_s=new Map(WI)});import{resolve as ji}from"node:path";import{homedir as Zp}from"node:os";function qe(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?ji(Zp(),e.replace(/^~[/\\]?/,"")):ji(e):ji(Zp(),".claude")}function XI(t=process.env){return ji(qe(t),"settings.json")}function qp(t=process.env){let e=[],r=vt();if(r.platform!=="claude-code"){let o=Mi(r.platform);o&&o.length>0&&e.push(ji(Zp(),...o,"settings.json"))}let n=XI(t);return e.includes(n)||e.push(n),e}var wn=S(()=>{"use strict";Tn()});import{readdirSync as YI,statSync as QI,lstatSync as eA,realpathSync as Ov,existsSync as tA,readFileSync as rA}from"node:fs";import{join as Av,extname as nA,relative as Nv,sep as oA,resolve as sA}from"node:path";function lA(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];n==="*"?t[r+1]==="*"?(e+=".*",r++):e+="[^/]*":n==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(n)?e+="\\"+n:e+=n}return new RegExp(`^${e}$`)}function Iv(t,e){if(e.length===0)return!1;let r=t.split("/").pop()??t;for(let n of e){if(!n.includes("/")&&!n.includes("*")){if(r===n||t.split("/").includes(n))return!0;continue}let o=lA(n);if(o.test(t)||o.test(r))return!0}return!1}function dA(t){let e=Av(t,".gitignore");if(!tA(e))return[];try{return rA(e,"utf-8").split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function pA(t,e){return Nv(t,e).split(oA).join("/")}function Dv(t,e={}){let{include:r,exclude:n,maxDepth:o=cA,maxFiles:s=uA,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=Ov(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:aA).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...iA,...n??[],...a?dA(u):[]],p=r??[],h=[],m=new Set([u]),f=0,g=!1;function y(_,x){if(g||x>o)return;let v;try{v=YI(_,{withFileTypes:!0})}catch{return}for(let E of v){if(g)return;let C=Av(_,E.name),b=pA(u,C);if(Iv(b,d))continue;let k=E.isDirectory(),P=E.isFile(),N=!1;try{N=eA(C).isSymbolicLink()}catch{continue}if(N){if(!c)continue;let O;try{O=Ov(C)}catch{continue}let F=Nv(u,O);if((F.startsWith("..")||sA(F)===O)&&F.startsWith("..")||m.has(O))continue;m.add(O);try{let K=QI(O);k=K.isDirectory(),P=K.isFile()}catch{continue}}if(k){y(C,x+1);continue}if(!P)continue;let R=nA(C).toLowerCase();if(l.includes(R)&&!(p.length>0&&!Iv(b,p))){if(f++,h.length>=s){g=!0;return}h.push(C)}}}return y(u,0),{files:h,capped:g,totalSeen:f}}var iA,aA,cA,uA,Mv=S(()=>{"use strict";iA=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],aA=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],cA=5,uA=200});import{readFileSync as jv,readdirSync as Bv,unlinkSync as Wp,existsSync as Vp,statSync as Fc,openSync as Lv,fstatSync as zv,closeSync as Fv}from"node:fs";import{createHash as Hv}from"node:crypto";import{tmpdir as Zv}from"node:os";import{join as Kp}from"node:path";function qv(t){let e=new Set,r=[];for(let n of t){let o=n.toLowerCase();e.has(o)||(e.add(o),r.push(n))}return r}function mA(t,e="AND"){let r=qv(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(r.length===0)return'""';let n=r.filter(s=>!bs.has(s.toLowerCase()));return(n.length>0?n:r).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function fA(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=qv(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let o=n.filter(i=>!bs.has(i.toLowerCase()));return(o.length>0?o:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function hA(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function gA(t){return t<=4?1:t<=12?2:3}function Gp(){let t=Zv(),e=0;try{let r=Bv(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=Kp(t,n);for(let a of["","-wal","-shm"])try{Wp(i+a)}catch{}e++}}}catch{}return e}function Jp(t,e){let r=0;try{if(!Vp(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=Bv(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=Kp(t,s),c=Fc(i).mtimeMs<n;if(!c){let u=i+"-wal";if(Vp(u))try{let l=Fc(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Wp(i+u)}catch{}r++}}catch{}}catch{}return r}function yA(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function _A(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,o=Math.min(t.length,e.length)-1;for(let s=0;s<o;s++){let i=t[s],a=t[s+1],c=e[s].length,u=0;for(let l of i){let d=l+c,p=d+r;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=p&&(n++,u++)}}return n}function xA(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t,r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var bs,Uv,vs,Xp=S(()=>{"use strict";bn();Mv();bs=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);Uv=4096;vs=class t{#e;#t;#n;#s;#o;#a;#c;#i;#u;#l;#m;#f;#h;#g;#y;#_;#x;#b;#v;#S;#k;#w;#E;#$;#T;#P;#R;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=rt();this.#t=e??Kp(Zv(),`context-mode-${process.pid}.db`),ts(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),es(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(Sc(s)){vc(this.#t),ts(this.#t);try{n=new r(this.#t,{timeout:3e4}),es(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#U(),this.#B()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{Wp(this.#t+e)}catch{}}#U(){this.#e.exec(`
|
|
187
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.KIMI_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return YA(e,r),r}isExpectedHookEntry(e,n,r){return e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(n.command??"").replace(/\\/g,"/"),o=(Tr[e]??"").replace(/\\/g,"/"),s=rN[e]??[];return r.includes(o)||s.some(i=>r.includes(i))}rebuildToml(e,n,r){let o=e.split(/\r?\n/),s=[],i=!1;for(let c of o){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(c)){i=!0;continue}if(i){/^\s*\[/.test(c)&&(i=!1,s.push(c));continue}s.push(c)}for(;s.length>0&&s[s.length-1]==="";)s.pop();s.length>0&&s.push("");let a=[...n,...r];if(a.length>0)for(let c of a)s.push(oN(c)),s.push("");return s.join(`
|
|
188
|
+
`)}}});var hm={};_e(hm,{PLATFORM_ENV_VARS:()=>xs,__resetClaudeCodePluginCacheForTests:()=>cN,__seedClaudeCodePluginCacheMissForTests:()=>uN,detectPlatform:()=>Qe,foreignIdentificationEnv:()=>mN,foreignWorkspaceEnv:()=>pN,getAdapter:()=>Fi,getEnvVarNames:()=>dN,getSessionDirSegments:()=>zi,workspaceEnvVarsFor:()=>fm});import{existsSync as Ye,readFileSync as iN}from"node:fs";import{resolve as Fe}from"node:path";import{homedir as yv}from"node:os";function aN(){if(uo!==null)return uo!=="miss"&&uo.hasCM;try{let t=Fe(yv(),".claude","plugins","installed_plugins.json"),e=iN(t,"utf-8"),n=JSON.parse(e),o=[...Object.keys(n.plugins??{}),...Object.keys(n.enabledPlugins??{})].some(s=>s.includes("context-mode"));return uo={hasCM:o},o}catch{return uo="miss",!1}}function cN(){uo=null}function uN(){uo="miss"}function dN(t){return(xs.get(t)??[]).map(e=>e.name)}function fm(t){return(xs.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function pN(t){let e=new Set;for(let[n,r]of xs)if(n!==t)for(let o of r)o.role==="workspace"&&e.add(o.name);return e}function mN(t){let e=new Set;for(let[n,r]of xs)if(n!==t)for(let o of r)o.role==="identification"&&e.add(o.name);return e}function zi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"antigravity-cli":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"copilot-cli":return[".copilot"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kimi":return[".kimi-code"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function Qe(t){if(t?.name){let s=nb[t.name];if(s)return{platform:s,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","copilot-cli","cursor","antigravity","antigravity-cli","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[s,i]of xs)if(i.some(a=>a.detect!==!1&&process.env[a.name]))return s==="vscode-copilot"&&aN()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:s,confidence:"high",reason:`${i.filter(a=>a.detect!==!1).map(a=>a.name).join(" or ")} env var set`};let n=yv(),r=(()=>{let s=process.env.COPILOT_HOME;return s&&s.trim()!==""?s.startsWith("~")?Fe(n,s.replace(/^~[/\\]?/,"")):Fe(s):Fe(n,".copilot")})(),o=Ye(Fe(r,"mcp-config.json"))||Ye(Fe(r,"hooks","context-mode.json"));return process.env.COPILOT_HOME?.trim()&&o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in explicit COPILOT_HOME exists (mcp-config.json or hooks/context-mode.json)"}:Ye(Fe(n,".local","bin","agy"))||Ye(Fe(n,".gemini","antigravity-cli"))||Ye(Fe(n,".gemini","config","mcp_config.json"))?{platform:"antigravity-cli",confidence:"medium",reason:"Antigravity CLI marker exists (~/.local/bin/agy, ~/.gemini/antigravity-cli, or ~/.gemini/config/mcp_config.json)"}:o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in Copilot CLI home exists (mcp-config.json or hooks/context-mode.json; honors COPILOT_HOME)"}:Ye(Fe(n,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Ye(Fe(n,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Ye(Fe(n,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Ye(Fe(n,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Ye(Fe(n,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Ye(Fe(n,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Ye(Fe(n,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Ye(Fe(n,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:Ye(Fe(n,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Ye(Fe(n,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Ye(Fe(n,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Ye(Fe(n,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Ye(Fe(n,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Ye(Fe(n,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function Fi(t){let e=t??Qe().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(xp(),_p));return new n}case"gemini-cli":{let{GeminiCLIAdapter:n}=await Promise.resolve().then(()=>(jb(),Mb));return new n}case"kilo":case"opencode":{let{OpenCodeAdapter:n}=await Promise.resolve().then(()=>(Hb(),Fb));return new n(e)}case"openclaw":{let{OpenClawAdapter:n}=await Promise.resolve().then(()=>(Zb(),Bb));return new n}case"codex":{let{CodexAdapter:n}=await Promise.resolve().then(()=>(Op(),tS));return new n}case"vscode-copilot":{let{VSCodeCopilotAdapter:n}=await Promise.resolve().then(()=>(aS(),iS));return new n}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:n}=await Promise.resolve().then(()=>(dS(),lS));return new n}case"copilot-cli":{let{CopilotCliAdapter:n}=await Promise.resolve().then(()=>(bS(),xS));return new n}case"cursor":{let{CursorAdapter:n}=await Promise.resolve().then(()=>(RS(),PS));return new n}case"antigravity":{let{AntigravityAdapter:n}=await Promise.resolve().then(()=>(qp(),OS));return new n}case"antigravity-cli":{let{AntigravityCliAdapter:n}=await Promise.resolve().then(()=>(HS(),FS));return new n}case"kiro":{let{KiroAdapter:n}=await Promise.resolve().then(()=>(KS(),WS));return new n}case"zed":{let{ZedAdapter:n}=await Promise.resolve().then(()=>(YS(),XS));return new n}case"qwen-code":{let{QwenCodeAdapter:n}=await Promise.resolve().then(()=>(rv(),nv));return new n}case"omp":{let{OMPAdapter:n}=await Promise.resolve().then(()=>(sv(),ov));return new n}case"pi":{let{PiAdapter:n}=await Promise.resolve().then(()=>(av(),iv));return new n}case"kimi":{let{KimiAdapter:n}=await Promise.resolve().then(()=>(gv(),hv));return new n}default:{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(xp(),_p));return new n}}}var uo,lN,xs,lo=v(()=>{"use strict";rb();uo=null;lN=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"},{name:"PI_CODING_AGENT",role:"identification"}]]],xs=new Map(lN)});import{resolve as Hi}from"node:path";import{homedir as gm}from"node:os";function Be(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Hi(gm(),e.replace(/^~[/\\]?/,"")):Hi(e):Hi(gm(),".claude")}function fN(t=process.env){return Hi(Be(t),"settings.json")}function ym(t=process.env){let e=[],n=Qe();if(n.platform!=="claude-code"){let o=zi(n.platform);o&&o.length>0&&e.push(Hi(gm(),...o,"settings.json"))}let r=fN(t);return e.includes(r)||e.push(r),e}var kr=v(()=>{"use strict";lo()});import{readdirSync as hN,statSync as gN,lstatSync as yN,realpathSync as _v,existsSync as _N,readFileSync as xN}from"node:fs";import{join as bv,extname as bN,relative as Sv,sep as SN,resolve as vN}from"node:path";function $N(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];r==="*"?t[n+1]==="*"?(e+=".*",n++):e+="[^/]*":r==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(r)?e+="\\"+r:e+=r}return new RegExp(`^${e}$`)}function xv(t,e){if(e.length===0)return!1;let n=t.split("/").pop()??t;for(let r of e){if(!r.includes("/")&&!r.includes("*")){if(n===r||t.split("/").includes(r))return!0;continue}let o=$N(r);if(o.test(t)||o.test(n))return!0}return!1}function PN(t){let e=bv(t,".gitignore");if(!_N(e))return[];try{return xN(e,"utf-8").split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#")&&!r.startsWith("!")).map(r=>r.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function RN(t,e){return Sv(t,e).split(SN).join("/")}function vv(t,e={}){let{include:n,exclude:r,maxDepth:o=EN,maxFiles:s=TN,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=_v(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:wN).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...kN,...r??[],...a?PN(u):[]],p=n??[],h=[],m=new Set([u]),f=0,g=!1;function y(_,x){if(g||x>o)return;let S;try{S=hN(_,{withFileTypes:!0})}catch{return}for(let E of S){if(g)return;let A=bv(_,E.name),b=RN(u,A);if(xv(b,d))continue;let T=E.isDirectory(),P=E.isFile(),N=!1;try{N=yN(A).isSymbolicLink()}catch{continue}if(N){if(!c)continue;let C;try{C=_v(A)}catch{continue}let F=Sv(u,C);if((F.startsWith("..")||vN(F)===C)&&F.startsWith("..")||m.has(C))continue;m.add(C);try{let W=gN(C);T=W.isDirectory(),P=W.isFile()}catch{continue}}if(T){y(A,x+1);continue}if(!P)continue;let R=bN(A).toLowerCase();if(l.includes(R)&&!(p.length>0&&!xv(b,p))){if(f++,h.length>=s){g=!0;return}h.push(A)}}}return y(u,0),{files:h,capped:g,totalSeen:f}}var kN,wN,EN,TN,kv=v(()=>{"use strict";kN=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],wN=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],EN=5,TN=200});import{readFileSync as wv,readdirSync as Cv,unlinkSync as xm,existsSync as _m,statSync as Yc,openSync as Ev,fstatSync as Tv,closeSync as $v}from"node:fs";import{createHash as Pv}from"node:crypto";import{tmpdir as Ov}from"node:os";import{join as bm}from"node:path";function Iv(t){let e=new Set,n=[];for(let r of t){let o=r.toLowerCase();e.has(o)||(e.add(o),n.push(r))}return n}function CN(t,e="AND"){let n=Iv(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(n.length===0)return'""';let r=n.filter(s=>!bs.has(s.toLowerCase()));return(r.length>0?r:n).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function ON(t,e="AND"){let n=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(n.length<3)return"";let r=Iv(n.split(/\s+/).filter(i=>i.length>=3));if(r.length===0)return"";let o=r.filter(i=>!bs.has(i.toLowerCase()));return(o.length>0?o:r).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function IN(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let n=Array.from({length:e.length+1},(r,o)=>o);for(let r=1;r<=t.length;r++){let o=[r];for(let s=1;s<=e.length;s++)o[s]=t[r-1]===e[s-1]?n[s-1]:1+Math.min(n[s],o[s-1],n[s-1]);n=o}return n[e.length]}function AN(t){return t<=4?1:t<=12?2:3}function Sm(){let t=Ov(),e=0;try{let n=Cv(t);for(let r of n){let o=r.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=bm(t,r);for(let a of["","-wal","-shm"])try{xm(i+a)}catch{}e++}}}catch{}return e}function vm(t,e){let n=0;try{if(!_m(t))return 0;let r=Date.now()-e*24*60*60*1e3,o=Cv(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=bm(t,s),c=Yc(i).mtimeMs<r;if(!c){let u=i+"-wal";if(_m(u))try{let l=Yc(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{xm(i+u)}catch{}n++}}catch{}}catch{}return n}function LN(t,e){let n=[],r=t.indexOf(e);for(;r!==-1;)n.push(r),r=t.indexOf(e,r+1);return n}function zN(t,e,n=30){if(t.length<2||e.length<2)return 0;let r=0,o=Math.min(t.length,e.length)-1;for(let s=0;s<o;s++){let i=t[s],a=t[s+1],c=e[s].length,u=0;for(let l of i){let d=l+c,p=d+n;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=p&&(r++,u++)}}return r}function FN(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t,n=new Array(e.length).fill(0),r=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][n[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<r&&(r=a),n[i]++,n[i]>=e[i].length)break}return r}var bs,Xc,NN,DN,MN,Rv,jN,Ss,km=v(()=>{"use strict";yr();kv();bs=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);Xc=4096,NN=3,DN=200,MN=5e3,Rv=80,jN=.5;Ss=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#f;#h;#g;#y;#_;#x;#b;#S;#v;#k;#w;#E;#T;#$;#P;#R;#C;#O;#I;#A;#N;#D;#M;#j=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let n=nt();this.#t=e??bm(Ov(),`context-mode-${process.pid}.db`),rs(this.#t);let r;try{r=new n(this.#t,{timeout:3e4}),ns(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(Tc(s)){Ec(this.#t),rs(this.#t);try{r=new n(this.#t,{timeout:3e4}),ns(r)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=r,this.#B(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{xm(this.#t+e)}catch{}}#B(){this.#e.exec(`
|
|
184
189
|
CREATE TABLE IF NOT EXISTS sources (
|
|
185
190
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
186
191
|
label TEXT NOT NULL,
|
|
@@ -220,7 +225,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
220
225
|
);
|
|
221
226
|
|
|
222
227
|
CREATE INDEX IF NOT EXISTS idx_sources_label ON sources(label);
|
|
223
|
-
`);try{let e=this.#e.prepare("SELECT name FROM pragma_table_xinfo('chunks')").all(),
|
|
228
|
+
`);try{let e=this.#e.prepare("SELECT name FROM pragma_table_xinfo('chunks')").all(),n=new Set(e.map(r=>r.name));e.length>0&&!n.has("source_category")&&(this.#e.exec("DROP TABLE IF EXISTS chunks"),this.#e.exec("DROP TABLE IF EXISTS chunks_trigram"),this.#e.exec(`
|
|
224
229
|
CREATE VIRTUAL TABLE chunks USING fts5(
|
|
225
230
|
title,
|
|
226
231
|
content,
|
|
@@ -243,7 +248,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
243
248
|
timestamp UNINDEXED,
|
|
244
249
|
tokenize='trigram'
|
|
245
250
|
);
|
|
246
|
-
`))}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN file_path TEXT")}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN content_hash TEXT")}catch{}}#
|
|
251
|
+
`))}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN file_path TEXT")}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN content_hash TEXT")}catch{}}#Z(){this.#o=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, 0, 0, ?, ?)"),this.#s=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, ?, ?, ?, ?)"),this.#a=this.#e.prepare("INSERT INTO chunks (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#c=this.#e.prepare("INSERT INTO chunks_trigram (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#i=this.#e.prepare("INSERT OR IGNORE INTO vocabulary (word) VALUES (?)"),this.#u=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#l=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#f=this.#e.prepare("DELETE FROM sources WHERE label = ?"),this.#h=this.#e.prepare(`
|
|
247
252
|
SELECT
|
|
248
253
|
chunks.title,
|
|
249
254
|
chunks.content,
|
|
@@ -258,7 +263,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
258
263
|
WHERE chunks MATCH ?
|
|
259
264
|
ORDER BY rank
|
|
260
265
|
LIMIT ?
|
|
261
|
-
`),this.#
|
|
266
|
+
`),this.#g=this.#e.prepare(`
|
|
262
267
|
SELECT
|
|
263
268
|
chunks.title,
|
|
264
269
|
chunks.content,
|
|
@@ -273,7 +278,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
273
278
|
WHERE chunks MATCH ? AND sources.label LIKE ? ESCAPE '\\'
|
|
274
279
|
ORDER BY rank
|
|
275
280
|
LIMIT ?
|
|
276
|
-
`),this.#
|
|
281
|
+
`),this.#y=this.#e.prepare(`
|
|
277
282
|
SELECT
|
|
278
283
|
chunks.title,
|
|
279
284
|
chunks.content,
|
|
@@ -288,7 +293,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
288
293
|
WHERE chunks MATCH ? AND sources.label = ?
|
|
289
294
|
ORDER BY rank
|
|
290
295
|
LIMIT ?
|
|
291
|
-
`),this.#
|
|
296
|
+
`),this.#_=this.#e.prepare(`
|
|
292
297
|
SELECT
|
|
293
298
|
chunks_trigram.title,
|
|
294
299
|
chunks_trigram.content,
|
|
@@ -303,7 +308,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
303
308
|
WHERE chunks_trigram MATCH ?
|
|
304
309
|
ORDER BY rank
|
|
305
310
|
LIMIT ?
|
|
306
|
-
`),this.#
|
|
311
|
+
`),this.#x=this.#e.prepare(`
|
|
307
312
|
SELECT
|
|
308
313
|
chunks_trigram.title,
|
|
309
314
|
chunks_trigram.content,
|
|
@@ -318,7 +323,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
318
323
|
WHERE chunks_trigram MATCH ? AND sources.label LIKE ? ESCAPE '\\'
|
|
319
324
|
ORDER BY rank
|
|
320
325
|
LIMIT ?
|
|
321
|
-
`),this.#
|
|
326
|
+
`),this.#b=this.#e.prepare(`
|
|
322
327
|
SELECT
|
|
323
328
|
chunks_trigram.title,
|
|
324
329
|
chunks_trigram.content,
|
|
@@ -348,7 +353,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
348
353
|
WHERE chunks MATCH ? AND chunks.content_type = ?
|
|
349
354
|
ORDER BY rank
|
|
350
355
|
LIMIT ?
|
|
351
|
-
`),this.#
|
|
356
|
+
`),this.#k=this.#e.prepare(`
|
|
352
357
|
SELECT
|
|
353
358
|
chunks.title,
|
|
354
359
|
chunks.content,
|
|
@@ -363,7 +368,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
363
368
|
WHERE chunks MATCH ? AND sources.label LIKE ? ESCAPE '\\' AND chunks.content_type = ?
|
|
364
369
|
ORDER BY rank
|
|
365
370
|
LIMIT ?
|
|
366
|
-
`),this.#
|
|
371
|
+
`),this.#w=this.#e.prepare(`
|
|
367
372
|
SELECT
|
|
368
373
|
chunks.title,
|
|
369
374
|
chunks.content,
|
|
@@ -378,7 +383,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
378
383
|
WHERE chunks MATCH ? AND sources.label = ? AND chunks.content_type = ?
|
|
379
384
|
ORDER BY rank
|
|
380
385
|
LIMIT ?
|
|
381
|
-
`),this.#
|
|
386
|
+
`),this.#E=this.#e.prepare(`
|
|
382
387
|
SELECT
|
|
383
388
|
chunks_trigram.title,
|
|
384
389
|
chunks_trigram.content,
|
|
@@ -393,7 +398,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
393
398
|
WHERE chunks_trigram MATCH ? AND chunks_trigram.content_type = ?
|
|
394
399
|
ORDER BY rank
|
|
395
400
|
LIMIT ?
|
|
396
|
-
`),this.#
|
|
401
|
+
`),this.#T=this.#e.prepare(`
|
|
397
402
|
SELECT
|
|
398
403
|
chunks_trigram.title,
|
|
399
404
|
chunks_trigram.content,
|
|
@@ -423,96 +428,105 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
423
428
|
WHERE chunks_trigram MATCH ? AND sources.label = ? AND chunks_trigram.content_type = ?
|
|
424
429
|
ORDER BY rank
|
|
425
430
|
LIMIT ?
|
|
426
|
-
`),this.#
|
|
431
|
+
`),this.#S=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#P=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#R=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label
|
|
427
432
|
FROM chunks c
|
|
428
433
|
JOIN sources s ON s.id = c.source_id
|
|
429
434
|
WHERE c.source_id = ?
|
|
430
|
-
ORDER BY c.rowid`),this.#
|
|
435
|
+
ORDER BY c.rowid`),this.#C=this.#e.prepare("SELECT chunk_count FROM sources WHERE id = ?"),this.#O=this.#e.prepare("SELECT content FROM chunks WHERE source_id = ?"),this.#A=this.#e.prepare("SELECT label, chunk_count, code_chunk_count, indexed_at, file_path, content_hash FROM sources WHERE label = ?"),this.#I=this.#e.prepare(`
|
|
431
436
|
SELECT
|
|
432
437
|
(SELECT COUNT(*) FROM sources) AS sources,
|
|
433
438
|
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
434
439
|
(SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
|
|
435
|
-
`),this.#
|
|
440
|
+
`),this.#N=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#M=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:n,path:r,source:o,attribution:s}=e,i=typeof n=="string"&&n.length>0;if(!i&&!r)throw new Error("Either content or path must be provided");let a;if(i)a=n;else{let p=Ev(r,"r");try{if(!Tv(p).isFile())throw new Error(`refusing to index ${r}: not a regular file`);a=wv(p,"utf-8")}finally{$v(p)}}let c=o??r??"untitled",u=this.#K(a),l=r??void 0,d=l?Pv("sha256").update(a).digest("hex"):void 0;return gr(()=>this.#d(u,c,a,l,d,s))}indexDirectory(e){let{path:n,source:r,attribution:o,perFileDeny:s,...i}=e,a=vv(n,i),c=0,u=0,l=0,d=0;for(let p of a.files){if(s&&s(p)){l++;continue}try{let h=r?`${r}:${p}`:p,m=this.index({path:p,source:h,attribution:o});c++,u+=m.totalChunks}catch{d++}}return{filesIndexed:c,totalChunks:u,capped:a.capped,totalSeen:a.totalSeen,denied:l,failed:d,label:r??n}}indexPlainText(e,n,r=20,o,s=Xc){if(!e||e.trim().length===0)return this.#d([],n,"",void 0,void 0,o);let i=this.#J(e,r,s);return gr(()=>this.#d(i.map(a=>({...a,hasCode:!1})),n,e,void 0,void 0,o))}indexJSON(e,n,r=Xc,o){if(!e||e.trim().length===0)return this.indexPlainText("",n,void 0,o,r);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,n,void 0,o,r)}let i=[];return this.#U(s,[],i,r),i.length===0?this.indexPlainText(e,n,void 0,o,r):gr(()=>this.#d(i,n,e,void 0,void 0,o))}#d(e,n,r,o,s,i){let a=e.filter(p=>p.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",d=this.#e.transaction(()=>{if(this.#u.run(n),this.#l.run(n),this.#f.run(n),e.length===0){let f=this.#o.run(n,o??null,s??null);return Number(f.lastInsertRowid)}let p=this.#s.run(n,e.length,a,o??null,s??null),h=Number(p.lastInsertRowid),m=new Date().toISOString();for(let f of e){let g=f.hasCode?"code":"prose";this.#a.run(f.title,f.content,h,g,null,c,u,m),this.#c.run(f.title,f.content,h,g,null,c,u,m)}return h})();return r&&this.#W(r),this.#j++,this.#j%t.OPTIMIZE_EVERY===0&&this.#H(),{sourceId:d,label:n,totalChunks:e.length,codeChunks:a}}#L(e){return e.map(n=>({title:n.title,content:n.content,source:n.label,rank:n.rank,contentType:n.content_type,highlighted:n.highlighted,timestamp:n.timestamp??void 0,sessionId:n.session_id??""}))}#p(e,n){return n==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,n=3,r,o="AND",s,i="like"){let a=CN(e,o),c,u;return r&&s?(c=i==="exact"?this.#w:this.#k,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#y:this.#g,u=[a,this.#p(r,i),n]):s?(c=this.#v,u=[a,s,n]):(c=this.#h,u=[a,n]),gr(()=>this.#L(c.all(...u)))}searchTrigram(e,n=3,r,o="AND",s,i="like"){let a=ON(e,o);if(!a)return[];let c,u;return r&&s?(c=i==="exact"?this.#$:this.#T,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#b:this.#x,u=[a,this.#p(r,i),n]):s?(c=this.#E,u=[a,s,n]):(c=this.#_,u=[a,n]),gr(()=>this.#L(c.all(...u)))}fuzzyCorrect(e){let n=e.toLowerCase().trim();if(n.length<3)return null;if(this.#r.has(n)){let u=this.#r.get(n)??null;return this.#r.delete(n),this.#r.set(n,u),u}let r=AN(n.length),o=this.#S.all(n.length-r,n.length+r),s=null,i=r+1,a=!1;for(let{word:u}of o){if(u===n){a=!0;break}let l=IN(n,u);l<i&&(i=l,s=u)}let c=a?null:i<=r?s:null;if(this.#r.size>=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(n,c),c}#z(e,n,r,o,s="like"){let a=Math.max(n*2,10),c=this.search(e,a,r,"OR",o,s),u=this.searchTrigram(e,a,r,"OR",o,s),l=new Map,d=p=>`${p.source}::${p.title}`;for(let[p,h]of c.entries()){let m=d(h),f=l.get(m);f?f.score+=1/(60+p+1):l.set(m,{result:h,score:1/(60+p+1)})}for(let[p,h]of u.entries()){let m=d(h),f=l.get(m);f?f.score+=1/(60+p+1):l.set(m,{result:h,score:1/(60+p+1)})}return Array.from(l.values()).sort((p,h)=>h.score-p.score).slice(0,n).map(({result:p,score:h})=>({...p,rank:-h}))}#F(e,n){let r=n.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=r.filter(i=>!bs.has(i)),s=o.length>0?o:r;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(h=>a.includes(h)).length,u=i.contentType==="code"?.6:.3,l=c>0?u*(c/s.length):0,d=0,p=0;if(s.length>=2){let h=i.content.toLowerCase(),m=s.map(f=>LN(h,f));if(!m.some(f=>f.length===0)){d=1/(1+FN(m)/Math.max(h.length,1));let g=zN(m,s);p=.5*Math.min(1,g/4)}}return{result:i,boost:l+d+p}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,n=3,r,o,s="like",i){this.#V();let a=i?Math.max(n*8,40):n,c=this.#q(i),u=this.#z(e,a,r,o,s),l=c?u.filter(c):u;if(l.length>0)return this.#F(l.slice(0,n),e).map(g=>({...g,matchLayer:"rrf"}));let d=e.toLowerCase().trim().split(/\s+/).filter(f=>f.length>=3&&!bs.has(f)),p=d.join(" "),m=d.map(f=>this.fuzzyCorrect(f)??f).join(" ");if(m!==p){let f=this.#z(m,a,r,o,s),g=c?f.filter(c):f;if(g.length>0)return this.#F(g.slice(0,n),m).map(_=>({..._,matchLayer:"rrf-fuzzy"}))}return[]}#q(e){return e?n=>{let r=n.sessionId??"";return r===""||e.has(r)}:null}lastRefreshCount=0;#V(){this.lastRefreshCount=0;let e=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let n of e)try{if(!_m(n.file_path)||this.#n&&this.#n(n.file_path))continue;let r=Yc(n.file_path).mtime,o=new Date(n.indexed_at+"Z");if(r<=o)continue;let s=Ev(n.file_path,"r"),i;try{if(!Tv(s).isFile())continue;i=wv(s,"utf-8")}finally{$v(s)}if(Pv("sha256").update(i).digest("hex")===n.content_hash)continue;this.index({content:i,path:n.file_path,source:n.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let n=this.#A.get(e);return n?{label:n.label,chunkCount:n.chunk_count,codeChunkCount:n.code_chunk_count,indexedAt:n.indexed_at,filePath:n.file_path??null,contentHash:n.content_hash??null}:null}listSources(){return this.#P.all()}getIndexState(){let e=this.#e.prepare("SELECT COALESCE(SUM(chunk_count), 0) AS total_chunks, COUNT(*) AS total_sources, MAX(indexed_at) AS last_indexed_at FROM sources").get();return{totalChunks:e.total_chunks??0,totalSources:e.total_sources??0,lastIndexedAt:e.last_indexed_at??void 0}}getChunksBySource(e){return this.#R.all(e).map(r=>({title:r.title,content:r.content,source:r.label,rank:0,contentType:r.content_type}))}getDistinctiveTerms(e,n=40){let r=this.#C.get(e);if(!r||r.chunk_count<3)return[];let o=r.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#O.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(p=>p.length>=3&&!bs.has(p)));for(let p of d)a.set(p,(a.get(p)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let p=Math.log(o/d),h=Math.min(l.length/20,.5),m=/[_]/.test(l),f=l.length>=12,g=m?1.5:f?.8:0;return{word:l,score:p+h+g}}).sort((l,d)=>d.score-l.score).slice(0,n).map(l=>l.word)}getStats(){let e=this.#I.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#N.run(o),this.#D.run(o),this.#M.run(o)))(e).changes}getDBSizeBytes(){try{return Yc(this.#t).size}catch{return 0}}#H(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#H(),os(this.#e)}#W(e){let n=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!bs.has(s)),r=[...new Set(n)],o=0;this.#e.transaction(()=>{for(let s of r){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#K(e,n=Xc){let r=[],o=e.split(`
|
|
436
441
|
`),s=[],i=[],a="",c=()=>{let l=i.join(`
|
|
437
|
-
`).trim();if(l.length===0)return;let d=this.#
|
|
438
|
-
|
|
439
|
-
`).trim();if(y.length===0)return;let _=h.length>1?`${d} (${f})`:d;f++,
|
|
440
|
-
|
|
441
|
-
`);Buffer.byteLength(_)>
|
|
442
|
-
`)
|
|
443
|
-
`)
|
|
444
|
-
`)
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
`,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:d}}function BA({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:r}){if(!t||!en(t))return{healed:[],skipped:"no-claude-json"};let n;try{n=Ss(t,"utf-8")}catch(l){return{healed:[],error:`read-failed: ${l&&l.message||l}`}}let o;try{o=JSON.parse(n)}catch(l){return{healed:[],error:`parse-failed: ${l&&l.message||l}`}}let s=o&&o.mcpServers;if(!s||typeof s!="object")return{healed:[],skipped:"no-mcp-servers"};let i=e.replace(/\\/g,"/"),a=St(r),c=a+mo,u=!1;for(let l of Object.values(s))if(!(!l||typeof l!="object"||!Array.isArray(l.args)))for(let d=0;d<l.args.length;d++){let p=l.args[d];if(typeof p!="string")continue;let h=p.replace(/\\/g,"/");if(!h.startsWith(i+"/"))continue;let m=h.slice(i.length+1),f=m.indexOf("/");if(f<0)continue;let g=m.slice(f+1),y=St(r,g);y!==a&&!(y+mo).startsWith(c)||y!==p&&(l.args[d]=y,u=!0)}if(!u)return{healed:[]};try{Fi(t,JSON.stringify(o,null,2),"utf-8")}catch(l){return{healed:[],error:`write-failed: ${l&&l.message||l}`}}return{healed:["claude-json-mcp-args"]}}function Uc({pluginCacheRoot:t,pluginKey:e}){let r=[];if(!t||!e)return{removed:r,skipped:"missing-args"};let n=St(t);if(!en(n))return{removed:r,skipped:"no-cache-root"};let[o,s]=e.split("@");if(!o||!s)return{removed:r,skipped:"bad-plugin-key"};let i=St(n,o,s),a=n+mo;if(!i.startsWith(a))return{removed:r,skipped:"outside-cache-root"};if(!en(i))return{removed:r,skipped:"no-plugin-dir"};let c=[];try{c=jA(i)}catch{return{removed:r,skipped:"readdir-failed"}}for(let u of c){let l=St(i,u);if(!l.startsWith(i+mo))continue;try{if(!zA(l).isDirectory())continue}catch{continue}let d=St(l,".mcp.json");if(en(d))try{LA(d),r.push(d)}catch{}}return{removed:r}}var zi,rm=S(()=>{"use strict";zi="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ce,nm,z,Nr,Hi=S(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ce||(ce={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(nm||(nm={}));z=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Nr=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}}});var A,VA,Ct,Bc=S(()=>{Hi();A=ce.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"]),VA=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ct=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ce.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ct.create=t=>new Ct(t)});var WA,tn,om=S(()=>{Bc();Hi();WA=(t,e)=>{let r;switch(t.code){case A.invalid_type:t.received===z.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case A.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:r=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case A.invalid_union:r="Invalid input";break;case A.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case A.invalid_enum_value:r=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case A.invalid_arguments:r="Invalid function arguments";break;case A.invalid_return_type:r="Invalid function return type";break;case A.invalid_date:r="Invalid date";break;case A.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ce.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case A.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case A.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case A.custom:r="Invalid input";break;case A.invalid_intersection_types:r="Intersection results could not be merged";break;case A.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case A.not_finite:r="Number must be finite";break;default:r=e.defaultError,ce.assertNever(t)}return{message:r}},tn=WA});function KA(t){eS=t}function ks(){return eS}var eS,Zc=S(()=>{om();eS=tn});function j(t,e){let r=ks(),n=Ui({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===tn?void 0:tn].filter(o=>!!o)});t.common.issues.push(n)}var Ui,GA,st,J,fo,mt,qc,Vc,Pn,ws,sm=S(()=>{Zc();om();Ui=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},GA=[];st=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return J;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return J;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},J=Object.freeze({status:"aborted"}),fo=t=>({status:"dirty",value:t}),mt=t=>({status:"valid",value:t}),qc=t=>t.status==="aborted",Vc=t=>t.status==="dirty",Pn=t=>t.status==="valid",ws=t=>typeof Promise<"u"&&t instanceof Promise});var tS=S(()=>{});var B,rS=S(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(B||(B={}))});function te(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function iS(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function pN(t){return new RegExp(`^${iS(t)}$`)}function aS(t){let e=`${sS}T${iS(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function mN(t,e){return!!((e==="v4"||!e)&&sN.test(t)||(e==="v6"||!e)&&aN.test(t))}function fN(t,e){if(!tN.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function hN(t,e){return!!((e==="v4"||!e)&&iN.test(t)||(e==="v6"||!e)&&cN.test(t))}function gN(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Es(t){if(t instanceof It){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ot.create(Es(n))}return new It({...t._def,shape:()=>e})}else return t instanceof on?new on({...t._def,type:Es(t.element)}):t instanceof Ot?Ot.create(Es(t.unwrap())):t instanceof Mr?Mr.create(Es(t.unwrap())):t instanceof Dr?Dr.create(t.items.map(e=>Es(e))):t}function am(t,e){let r=Nr(t),n=Nr(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let o=ce.objectKeys(e),s=ce.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=am(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===z.array&&n===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=am(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===z.date&&n===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function cS(t,e){return new Eo({values:t,typeName:D.ZodEnum,...te(e)})}function oS(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function uS(t,e={},r){return t?Cn.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=oS(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=oS(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Cn.create()}var tr,nS,ne,JA,XA,YA,QA,eN,tN,rN,nN,oN,im,sN,iN,aN,cN,uN,lN,sS,dN,Rn,ho,go,yo,_o,$s,xo,bo,Cn,nn,hr,Ts,on,It,vo,rn,Wc,So,Dr,Kc,Ps,Rs,Gc,ko,wo,Eo,$o,On,rr,Ot,Mr,To,Po,Cs,yN,Bi,Zi,Ro,_N,D,xN,lS,dS,bN,vN,pS,SN,kN,wN,EN,$N,TN,PN,RN,CN,cm,ON,IN,AN,NN,DN,MN,jN,LN,zN,FN,HN,UN,BN,ZN,qN,VN,WN,KN,GN,JN,XN,YN,QN,eD,mS=S(()=>{Bc();Zc();rS();sm();Hi();tr=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},nS=(t,e)=>{if(Pn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ct(t.common.issues);return this._error=r,this._error}}};ne=class{get description(){return this._def.description}_getType(e){return Nr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Nr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new st,ctx:{common:e.parent.common,data:e.data,parsedType:Nr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ws(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Nr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return nS(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Nr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Pn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Pn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Nr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ws(o)?o:Promise.resolve(o));return nS(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:A.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new rr({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:r=>this["~validate"](r)}}optional(){return Ot.create(this,this._def)}nullable(){return Mr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return on.create(this)}promise(){return On.create(this,this._def)}or(e){return vo.create([this,e],this._def)}and(e){return So.create(this,e,this._def)}transform(e){return new rr({...te(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new To({...te(this._def),innerType:this,defaultValue:r,typeName:D.ZodDefault})}brand(){return new Bi({typeName:D.ZodBranded,type:this,...te(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Po({...te(this._def),innerType:this,catchValue:r,typeName:D.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Zi.create(this,e)}readonly(){return Ro.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},JA=/^c[^\s-]{8,}$/i,XA=/^[0-9a-z]+$/,YA=/^[0-9A-HJKMNP-TV-Z]{26}$/i,QA=/^[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,eN=/^[a-z0-9_-]{21}$/i,tN=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rN=/^[-+]?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)?)??$/,nN=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,oN="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",sN=/^(?:(?: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])$/,iN=/^(?:(?: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])$/,aN=/^(([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]))$/,cN=/^(([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])$/,uN=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,lN=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,sS="((\\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])))",dN=new RegExp(`^${sS}$`);Rn=class t extends ne{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_type,expected:z.string,received:s.parsedType}),J}let n=new st,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),j(o,{code:A.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),j(o,{code:A.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?j(o,{code:A.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&j(o,{code:A.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")nN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"email",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")im||(im=new RegExp(oN,"u")),im.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"emoji",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")QA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"uuid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")eN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"nanoid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")JA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"cuid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")XA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"cuid2",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")YA.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"ulid",code:A.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),j(o,{validation:"url",code:A.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"regex",code:A.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?aS(s).test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?dN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?pN(s).test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{code:A.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?rN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"duration",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?mN(e.data,s.version)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"ip",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?fN(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"jwt",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?hN(e.data,s.version)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"cidr",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?uN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"base64",code:A.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?lN.test(e.data)||(o=this._getOrReturnCtx(e,o),j(o,{validation:"base64url",code:A.invalid_string,message:s.message}),n.dirty()):ce.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:A.invalid_string,...B.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...B.errToObj(e)})}url(e){return this._addCheck({kind:"url",...B.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...B.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...B.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...B.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...B.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...B.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...B.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...B.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...B.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...B.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...B.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...B.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...B.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...B.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...B.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...B.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...B.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...B.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...B.errToObj(r)})}nonempty(e){return this.min(1,B.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Rn.create=t=>new Rn({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...te(t)});ho=class t extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_type,expected:z.number,received:s.parsedType}),J}let n,o=new st;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:A.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?gN(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:A.not_finite,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,B.toString(r))}gt(e,r){return this.setLimit("min",e,!1,B.toString(r))}lte(e,r){return this.setLimit("max",e,!0,B.toString(r))}lt(e,r){return this.setLimit("max",e,!1,B.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:B.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:B.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:B.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:B.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:B.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ce.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};ho.create=t=>new ho({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...te(t)});go=class t extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let n,o=new st;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return j(r,{code:A.invalid_type,expected:z.bigint,received:r.parsedType}),J}gte(e,r){return this.setLimit("min",e,!0,B.toString(r))}gt(e,r){return this.setLimit("min",e,!1,B.toString(r))}lte(e,r){return this.setLimit("max",e,!0,B.toString(r))}lt(e,r){return this.setLimit("max",e,!1,B.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:B.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};go.create=t=>new go({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...te(t)});yo=class extends ne{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.boolean,received:n.parsedType}),J}return mt(e.data)}};yo.create=t=>new yo({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...te(t)});_o=class t extends ne{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_type,expected:z.date,received:s.parsedType}),J}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return j(s,{code:A.invalid_date}),J}let n=new st,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),j(o,{code:A.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),j(o,{code:A.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ce.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:B.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:B.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};_o.create=t=>new _o({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...te(t)});$s=class extends ne{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.symbol,received:n.parsedType}),J}return mt(e.data)}};$s.create=t=>new $s({typeName:D.ZodSymbol,...te(t)});xo=class extends ne{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.undefined,received:n.parsedType}),J}return mt(e.data)}};xo.create=t=>new xo({typeName:D.ZodUndefined,...te(t)});bo=class extends ne{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.null,received:n.parsedType}),J}return mt(e.data)}};bo.create=t=>new bo({typeName:D.ZodNull,...te(t)});Cn=class extends ne{constructor(){super(...arguments),this._any=!0}_parse(e){return mt(e.data)}};Cn.create=t=>new Cn({typeName:D.ZodAny,...te(t)});nn=class extends ne{constructor(){super(...arguments),this._unknown=!0}_parse(e){return mt(e.data)}};nn.create=t=>new nn({typeName:D.ZodUnknown,...te(t)});hr=class extends ne{_parse(e){let r=this._getOrReturnCtx(e);return j(r,{code:A.invalid_type,expected:z.never,received:r.parsedType}),J}};hr.create=t=>new hr({typeName:D.ZodNever,...te(t)});Ts=class extends ne{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.void,received:n.parsedType}),J}return mt(e.data)}};Ts.create=t=>new Ts({typeName:D.ZodVoid,...te(t)});on=class t extends ne{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==z.array)return j(r,{code:A.invalid_type,expected:z.array,received:r.parsedType}),J;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(j(r,{code:i?A.too_big:A.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(j(r,{code:A.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(j(r,{code:A.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new tr(r,i,r.path,a)))).then(i=>st.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new tr(r,i,r.path,a)));return st.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:B.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:B.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:B.toString(r)}})}nonempty(e){return this.min(1,e)}};on.create=(t,e)=>new on({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...te(e)});It=class t extends ne{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ce.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return j(u,{code:A.invalid_type,expected:z.object,received:u.parsedType}),J}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof hr&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new tr(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof hr){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(j(o,{code:A.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new tr(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>st.mergeObjectSync(n,u)):st.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return B.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:B.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ce.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ce.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Es(this)}partial(e){let r={};for(let n of ce.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ce.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ot;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return cS(ce.objectKeys(this.shape))}};It.create=(t,e)=>new It({shape:()=>t,unknownKeys:"strip",catchall:hr.create(),typeName:D.ZodObject,...te(e)});It.strictCreate=(t,e)=>new It({shape:()=>t,unknownKeys:"strict",catchall:hr.create(),typeName:D.ZodObject,...te(e)});It.lazycreate=(t,e)=>new It({shape:t,unknownKeys:"strip",catchall:hr.create(),typeName:D.ZodObject,...te(e)});vo=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ct(a.ctx.common.issues));return j(r,{code:A.invalid_union,unionErrors:i}),J}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ct(c));return j(r,{code:A.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}};vo.create=(t,e)=>new vo({options:t,typeName:D.ZodUnion,...te(e)});rn=t=>t instanceof ko?rn(t.schema):t instanceof rr?rn(t.innerType()):t instanceof wo?[t.value]:t instanceof Eo?t.options:t instanceof $o?ce.objectValues(t.enum):t instanceof To?rn(t._def.innerType):t instanceof xo?[void 0]:t instanceof bo?[null]:t instanceof Ot?[void 0,...rn(t.unwrap())]:t instanceof Mr?[null,...rn(t.unwrap())]:t instanceof Bi||t instanceof Ro?rn(t.unwrap()):t instanceof Po?rn(t._def.innerType):[],Wc=class t extends ne{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return j(r,{code:A.invalid_type,expected:z.object,received:r.parsedType}),J;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(j(r,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),J)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=rn(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...te(n)})}};So=class extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(qc(s)||qc(i))return J;let a=am(s.value,i.value);return a.valid?((Vc(s)||Vc(i))&&r.dirty(),{status:r.value,value:a.data}):(j(n,{code:A.invalid_intersection_types}),J)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};So.create=(t,e,r)=>new So({left:t,right:e,typeName:D.ZodIntersection,...te(r)});Dr=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return j(n,{code:A.invalid_type,expected:z.array,received:n.parsedType}),J;if(n.data.length<this._def.items.length)return j(n,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&n.data.length>this._def.items.length&&(j(n,{code:A.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new tr(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>st.mergeArray(r,i)):st.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dr({items:t,typeName:D.ZodTuple,rest:null,...te(e)})};Kc=class t extends ne{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return j(n,{code:A.invalid_type,expected:z.object,received:n.parsedType}),J;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new tr(n,a,n.path,a)),value:i._parse(new tr(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?st.mergeObjectAsync(r,o):st.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ne?new t({keyType:e,valueType:r,typeName:D.ZodRecord,...te(n)}):new t({keyType:Rn.create(),valueType:e,typeName:D.ZodRecord,...te(r)})}},Ps=class extends ne{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.map)return j(n,{code:A.invalid_type,expected:z.map,received:n.parsedType}),J;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new tr(n,a,n.path,[u,"key"])),value:s._parse(new tr(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return J;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return J;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Ps.create=(t,e,r)=>new Ps({valueType:e,keyType:t,typeName:D.ZodMap,...te(r)});Rs=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return j(n,{code:A.invalid_type,expected:z.set,received:n.parsedType}),J;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(j(n,{code:A.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(j(n,{code:A.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return J;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new tr(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:B.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:B.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Rs.create=(t,e)=>new Rs({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...te(e)});Gc=class t extends ne{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return j(r,{code:A.invalid_type,expected:z.function,received:r.parsedType}),J;function n(a,c){return Ui({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ks(),tn].filter(u=>!!u),issueData:{code:A.invalid_arguments,argumentsError:c}})}function o(a,c){return Ui({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ks(),tn].filter(u=>!!u),issueData:{code:A.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof On){let a=this;return mt(async function(...c){let u=new Ct([]),l=await a._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(n(c,h)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw u.addIssue(o(d,h)),u})})}else{let a=this;return mt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ct([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ct([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Dr.create(e).rest(nn.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Dr.create([]).rest(nn.create()),returns:r||nn.create(),typeName:D.ZodFunction,...te(n)})}},ko=class extends ne{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ko.create=(t,e)=>new ko({getter:t,typeName:D.ZodLazy,...te(e)});wo=class extends ne{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return j(r,{received:r.data,code:A.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};wo.create=(t,e)=>new wo({value:t,typeName:D.ZodLiteral,...te(e)});Eo=class t extends ne{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return j(r,{expected:ce.joinValues(n),received:r.parsedType,code:A.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return j(r,{received:r.data,code:A.invalid_enum_value,options:n}),J}return mt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Eo.create=cS;$o=class extends ne{_parse(e){let r=ce.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let o=ce.objectValues(r);return j(n,{expected:ce.joinValues(o),received:n.parsedType,code:A.invalid_type}),J}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ce.objectValues(r);return j(n,{received:n.data,code:A.invalid_enum_value,options:o}),J}return mt(e.data)}get enum(){return this._def.values}};$o.create=(t,e)=>new $o({values:t,typeName:D.ZodNativeEnum,...te(e)});On=class extends ne{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return j(r,{code:A.invalid_type,expected:z.promise,received:r.parsedType}),J;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return mt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};On.create=(t,e)=>new On({type:t,typeName:D.ZodPromise,...te(e)});rr=class extends ne{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{j(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return J;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?J:c.status==="dirty"?fo(c.value):r.value==="dirty"?fo(c.value):c});{if(r.value==="aborted")return J;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?J:a.status==="dirty"?fo(a.value):r.value==="dirty"?fo(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?J:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Pn(i))return J;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Pn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):J);ce.assertNever(o)}};rr.create=(t,e,r)=>new rr({schema:t,typeName:D.ZodEffects,effect:e,...te(r)});rr.createWithPreprocess=(t,e,r)=>new rr({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...te(r)});Ot=class extends ne{_parse(e){return this._getType(e)===z.undefined?mt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ot.create=(t,e)=>new Ot({innerType:t,typeName:D.ZodOptional,...te(e)});Mr=class extends ne{_parse(e){return this._getType(e)===z.null?mt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mr.create=(t,e)=>new Mr({innerType:t,typeName:D.ZodNullable,...te(e)});To=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};To.create=(t,e)=>new To({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});Po=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ws(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ct(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ct(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Po.create=(t,e)=>new Po({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});Cs=class extends ne{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return j(n,{code:A.invalid_type,expected:z.nan,received:n.parsedType}),J}return{status:"valid",value:e.data}}};Cs.create=t=>new Cs({typeName:D.ZodNaN,...te(t)});yN=Symbol("zod_brand"),Bi=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Zi=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?J:s.status==="dirty"?(r.dirty(),fo(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?J:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:D.ZodPipeline})}},Ro=class extends ne{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Pn(o)&&(o.value=Object.freeze(o.value)),o);return ws(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Ro.create=(t,e)=>new Ro({innerType:t,typeName:D.ZodReadonly,...te(e)});_N={object:It.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(D||(D={}));xN=(t,e={message:`Input not instance of ${t.name}`})=>uS(r=>r instanceof t,e),lS=Rn.create,dS=ho.create,bN=Cs.create,vN=go.create,pS=yo.create,SN=_o.create,kN=$s.create,wN=xo.create,EN=bo.create,$N=Cn.create,TN=nn.create,PN=hr.create,RN=Ts.create,CN=on.create,cm=It.create,ON=It.strictCreate,IN=vo.create,AN=Wc.create,NN=So.create,DN=Dr.create,MN=Kc.create,jN=Ps.create,LN=Rs.create,zN=Gc.create,FN=ko.create,HN=wo.create,UN=Eo.create,BN=$o.create,ZN=On.create,qN=rr.create,VN=Ot.create,WN=Mr.create,KN=rr.createWithPreprocess,GN=Zi.create,JN=()=>lS().optional(),XN=()=>dS().optional(),YN=()=>pS().optional(),QN={string:(t=>Rn.create({...t,coerce:!0})),number:(t=>ho.create({...t,coerce:!0})),boolean:(t=>yo.create({...t,coerce:!0})),bigint:(t=>go.create({...t,coerce:!0})),date:(t=>_o.create({...t,coerce:!0}))},eD=J});var M={};we(M,{BRAND:()=>yN,DIRTY:()=>fo,EMPTY_PATH:()=>GA,INVALID:()=>J,NEVER:()=>eD,OK:()=>mt,ParseStatus:()=>st,Schema:()=>ne,ZodAny:()=>Cn,ZodArray:()=>on,ZodBigInt:()=>go,ZodBoolean:()=>yo,ZodBranded:()=>Bi,ZodCatch:()=>Po,ZodDate:()=>_o,ZodDefault:()=>To,ZodDiscriminatedUnion:()=>Wc,ZodEffects:()=>rr,ZodEnum:()=>Eo,ZodError:()=>Ct,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Gc,ZodIntersection:()=>So,ZodIssueCode:()=>A,ZodLazy:()=>ko,ZodLiteral:()=>wo,ZodMap:()=>Ps,ZodNaN:()=>Cs,ZodNativeEnum:()=>$o,ZodNever:()=>hr,ZodNull:()=>bo,ZodNullable:()=>Mr,ZodNumber:()=>ho,ZodObject:()=>It,ZodOptional:()=>Ot,ZodParsedType:()=>z,ZodPipeline:()=>Zi,ZodPromise:()=>On,ZodReadonly:()=>Ro,ZodRecord:()=>Kc,ZodSchema:()=>ne,ZodSet:()=>Rs,ZodString:()=>Rn,ZodSymbol:()=>$s,ZodTransformer:()=>rr,ZodTuple:()=>Dr,ZodType:()=>ne,ZodUndefined:()=>xo,ZodUnion:()=>vo,ZodUnknown:()=>nn,ZodVoid:()=>Ts,addIssueToContext:()=>j,any:()=>$N,array:()=>CN,bigint:()=>vN,boolean:()=>pS,coerce:()=>QN,custom:()=>uS,date:()=>SN,datetimeRegex:()=>aS,defaultErrorMap:()=>tn,discriminatedUnion:()=>AN,effect:()=>qN,enum:()=>UN,function:()=>zN,getErrorMap:()=>ks,getParsedType:()=>Nr,instanceof:()=>xN,intersection:()=>NN,isAborted:()=>qc,isAsync:()=>ws,isDirty:()=>Vc,isValid:()=>Pn,late:()=>_N,lazy:()=>FN,literal:()=>HN,makeIssue:()=>Ui,map:()=>jN,nan:()=>bN,nativeEnum:()=>BN,never:()=>PN,null:()=>EN,nullable:()=>WN,number:()=>dS,object:()=>cm,objectUtil:()=>nm,oboolean:()=>YN,onumber:()=>XN,optional:()=>VN,ostring:()=>JN,pipeline:()=>GN,preprocess:()=>KN,promise:()=>ZN,quotelessJson:()=>VA,record:()=>MN,set:()=>LN,setErrorMap:()=>KA,strictObject:()=>ON,string:()=>lS,symbol:()=>kN,transformer:()=>qN,tuple:()=>DN,undefined:()=>wN,union:()=>IN,unknown:()=>TN,util:()=>ce,void:()=>RN});var Jc=S(()=>{Zc();sm();tS();Hi();mS();Bc()});var qi=S(()=>{Jc()});function T(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Ft(t){return t&&Object.assign(Xc,t),Xc}var rD,sn,Xc,Os=S(()=>{rD=Object.freeze({status:"aborted"});sn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Xc={}});var ue={};we(ue,{BIGINT_FORMAT_RANGES:()=>hS,Class:()=>lm,NUMBER_FORMAT_RANGES:()=>ym,aborted:()=>Oo,allowsEval:()=>fm,assert:()=>aD,assertEqual:()=>nD,assertIs:()=>sD,assertNever:()=>iD,assertNotEqual:()=>oD,assignProp:()=>mm,cached:()=>Ki,captureStackTrace:()=>Qc,cleanEnum:()=>bD,cleanRegex:()=>Ji,clone:()=>Ht,createTransparentProxy:()=>mD,defineLazy:()=>Te,esc:()=>Co,escapeRegex:()=>In,extend:()=>gD,finalizeIssue:()=>gr,floatSafeRemainder:()=>pm,getElementAtPath:()=>cD,getEnumValues:()=>Wi,getLengthableOrigin:()=>Xi,getParsedType:()=>pD,getSizableOrigin:()=>gS,isObject:()=>Is,isPlainObject:()=>As,issue:()=>_m,joinValues:()=>Yc,jsonStringifyReplacer:()=>dm,merge:()=>yD,normalizeParams:()=>X,nullish:()=>Gi,numKeys:()=>dD,omit:()=>hD,optionalKeys:()=>gm,partial:()=>_D,pick:()=>fD,prefixIssues:()=>jr,primitiveTypes:()=>fS,promiseAllObject:()=>uD,propertyKeyTypes:()=>hm,randomString:()=>lD,required:()=>xD,stringifyPrimitive:()=>eu,unwrapMessage:()=>Vi});function nD(t){return t}function oD(t){return t}function sD(t){}function iD(t){throw new Error}function aD(t){}function Wi(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Yc(t,e="|"){return t.map(r=>eu(r)).join(e)}function dm(t,e){return typeof e=="bigint"?e.toString():e}function Ki(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Gi(t){return t==null}function Ji(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function pm(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Te(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function mm(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function cD(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function uD(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function lD(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Co(t){return JSON.stringify(t)}function Is(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function As(t){if(Is(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Is(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function dD(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function In(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ht(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function X(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function mD(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function eu(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function gm(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function fD(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Ht(t,{...t._zod.def,shape:r,checks:[]})}function hD(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Ht(t,{...t._zod.def,shape:r,checks:[]})}function gD(t,e){if(!As(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return mm(this,"shape",n),n},checks:[]};return Ht(t,r)}function yD(t,e){return Ht(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return mm(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function _D(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Ht(e,{...e._zod.def,shape:o,checks:[]})}function xD(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Ht(e,{...e._zod.def,shape:o,checks:[]})}function Oo(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function jr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Vi(t){return typeof t=="string"?t:t?.message}function gr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Vi(t.inst?._zod.def?.error?.(t))??Vi(e?.error?.(t))??Vi(r.customError?.(t))??Vi(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function gS(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Xi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _m(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function bD(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Qc,fm,pD,hm,fS,ym,hS,lm,Lr=S(()=>{Qc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};fm=Ki(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});pD=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},hm=new Set(["string","number","symbol"]),fS=new Set(["string","number","bigint","boolean","symbol","undefined"]);ym={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},hS={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};lm=class{constructor(...e){}}});function xm(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function bm(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var yS,tu,Yi,vm=S(()=>{Os();Lr();yS=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,dm,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},tu=T("$ZodError",yS),Yi=T("$ZodError",yS,{Parent:Error})});var Sm,km,wm,Em,$m,Io,Tm,Ao,Pm=S(()=>{Os();vm();Lr();Sm=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new sn;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gr(c,s,Ft())));throw Qc(a,o?.callee),a}return i.value},km=Sm(Yi),wm=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gr(c,s,Ft())));throw Qc(a,o?.callee),a}return i.value},Em=wm(Yi),$m=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new sn;return s.issues.length?{success:!1,error:new(t??tu)(s.issues.map(i=>gr(i,o,Ft())))}:{success:!0,data:s.value}},Io=$m(Yi),Tm=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>gr(i,o,Ft())))}:{success:!0,data:s.value}},Ao=Tm(Yi)});function TS(){return new RegExp(SD,"u")}function jS(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function LS(t){return new RegExp(`^${jS(t)}$`)}function zS(t){let e=jS({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${DS}T(?:${n})$`)}var _S,xS,bS,vS,SS,kS,wS,ES,Rm,$S,SD,PS,RS,CS,OS,IS,Cm,AS,NS,DS,MS,FS,HS,US,BS,ZS,qS,VS,nu=S(()=>{_S=/^[cC][^\s-]{8,}$/,xS=/^[0-9a-z]+$/,bS=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,vS=/^[0-9a-vA-V]{20}$/,SS=/^[A-Za-z0-9]{27}$/,kS=/^[a-zA-Z0-9_-]{21}$/,wS=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ES=/^([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})$/,Rm=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/,$S=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,SD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";PS=/^(?:(?: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])$/,RS=/^(([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})$/,CS=/^((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])$/,OS=/^(([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])$/,IS=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Cm=/^[A-Za-z0-9_-]*$/,AS=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,NS=/^\+(?:[0-9]){6,14}[0-9]$/,DS="(?:(?:\\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])))",MS=new RegExp(`^${DS}$`);FS=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},HS=/^\d+$/,US=/^-?\d+(?:\.\d+)?/i,BS=/true|false/i,ZS=/null/i,qS=/^[^A-Z]*$/,VS=/^[^a-z]*$/});var it,WS,Om,Im,KS,GS,JS,XS,YS,Qi,QS,ek,tk,rk,nk,ok,sk,ou=S(()=>{Os();nu();Lr();it=T("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),WS={number:"number",bigint:"bigint",object:"date"},Om=T("$ZodCheckLessThan",(t,e)=>{it.init(t,e);let r=WS[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Im=T("$ZodCheckGreaterThan",(t,e)=>{it.init(t,e);let r=WS[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),KS=T("$ZodCheckMultipleOf",(t,e)=>{it.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):pm(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),GS=T("$ZodCheckNumberFormat",(t,e)=>{it.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=ym[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=HS)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),JS=T("$ZodCheckMaxLength",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Gi(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Xi(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),XS=T("$ZodCheckMinLength",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Gi(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Xi(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),YS=T("$ZodCheckLengthEquals",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Gi(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Xi(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Qi=T("$ZodCheckStringFormat",(t,e)=>{var r,n;it.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),QS=T("$ZodCheckRegex",(t,e)=>{Qi.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),ek=T("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=qS),Qi.init(t,e)}),tk=T("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=VS),Qi.init(t,e)}),rk=T("$ZodCheckIncludes",(t,e)=>{it.init(t,e);let r=In(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),nk=T("$ZodCheckStartsWith",(t,e)=>{it.init(t,e);let r=new RegExp(`^${In(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),ok=T("$ZodCheckEndsWith",(t,e)=>{it.init(t,e);let r=new RegExp(`.*${In(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),sk=T("$ZodCheckOverwrite",(t,e)=>{it.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var su,Am=S(()=>{su=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
449
|
-
`).
|
|
450
|
-
|
|
442
|
+
`).trim();if(l.length===0)return;let d=this.#ee(s,a),p=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(l)<=n){r.push({title:d,content:l,hasCode:p}),i=[];return}let h=l.split(/\n\n+/),m=[],f=1,g=()=>{if(m.length===0)return;let y=m.join(`
|
|
443
|
+
|
|
444
|
+
`).trim();if(y.length===0)return;let _=h.length>1?`${d} (${f})`:d;f++,r.push({title:_,content:y,hasCode:y.includes("```")}),m=[]};for(let y of h){m.push(y);let _=m.join(`
|
|
445
|
+
|
|
446
|
+
`);Buffer.byteLength(_)>n&&m.length>1&&(m.pop(),g(),m=[y])}g(),i=[]},u=0;for(;u<o.length;){let l=o[u];if(/^[-_*]{3,}\s*$/.test(l)){c(),u++;continue}let d=l.match(/^(#{1,4})\s+(.+)$/);if(d){c();let h=d[1].length,m=d[2].trim();for(;s.length>0&&s[s.length-1].level>=h;)s.pop();s.push({level:h,text:m}),a=m,i.push(l),u++;continue}let p=l.match(/^(`{3,})(.*)?$/);if(p){let h=p[1],m=[l];for(u++;u<o.length;){if(m.push(o[u]),o[u].startsWith(h)&&o[u].trim()===h){u++;break}u++}i.push(...m);continue}i.push(l),u++}return c(),r}#G(e,n){if(Buffer.byteLength(e)<=n)return e;let r="",o=0;for(let s of e){let i=Buffer.byteLength(s);if(o+i>n)break;r+=s,o+=i}return r.length===0?[...e][0]??"":r}#m(e,n,r){let o=[],s=[],i=1,a=()=>{if(s.length===0)return;let c=s.join(`
|
|
447
|
+
`),u=i===1?n:`${n} (${i})`;o.push({title:u,content:c}),i++,s=[]};for(let c of e){if(Buffer.byteLength(c)>r){a();let l=c,d=1;for(;l.length>0;){let p=this.#G(l,r);if(p.length<l.length){let m=p.lastIndexOf(" "),f=p.lastIndexOf(`
|
|
448
|
+
`),g=Math.max(m,f);g>p.length*jN&&(p=p.slice(0,g))}let h=i===1&&d===1?n:`${n} (${i}.${d})`;o.push({title:h,content:p}),l=l.slice(p.length),d++,i++}continue}let u=s.length>0?s.join(`
|
|
449
|
+
`)+`
|
|
450
|
+
`+c:c;Buffer.byteLength(u)>r&&s.length>0&&a(),s.push(c)}return a(),o}#J(e,n,r=Xc){let o=e.split(/\n\s*\n/);if(o.length>=NN&&o.length<=DN&&o.every(u=>Buffer.byteLength(u)<MN))return o.flatMap((u,l)=>{let d=u.trim();if(d.length===0)return[];let p=d.split(`
|
|
451
|
+
`)[0].slice(0,Rv)||`Section ${l+1}`;return Buffer.byteLength(d)<=r?[{title:p,content:d}]:this.#m(d.split(`
|
|
452
|
+
`),p,r)});let s=e.split(`
|
|
453
|
+
`);if(s.length<=n)return Buffer.byteLength(e)<=r?[{title:"Output",content:e}]:this.#m(s,"Output",r);let i=[],c=Math.max(n-2,1);for(let u=0;u<s.length;u+=c){let l=s.slice(u,u+n);if(l.length===0)break;let d=u+1,p=Math.min(u+l.length,s.length),h=l[0]?.trim().slice(0,Rv),m=l.join(`
|
|
454
|
+
`);if(Buffer.byteLength(m)<=r)i.push({title:h||`Lines ${d}-${p}`,content:m});else{let f=this.#m(l,h||`Lines ${d}-${p}`,r);i.push(...f)}}return i}#U(e,n,r,o){let s=n.length>0?n.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){r.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#U(u,[...n,c],r,o);return}r.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#Q(e,n,r,o);return}r.push({title:s,content:i,hasCode:!1})}#X(e){if(e.length===0)return null;let n=e[0];if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=["id","name","title","path","slug","key","label"],o=n;for(let s of r)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#Y(e,n,r,o,s){let i=e?`${e} > `:"";if(!s)return n===r?`${i}[${n}]`:`${i}[${n}-${r}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#Q(e,n,r,o){let s=n.length>0?n.join(" > "):"(root)",i=this.#X(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#Y(s,c,l,a,i);r.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;l<e.length;l++){a.push(e[l]);let d=JSON.stringify(a,null,2);Buffer.byteLength(d)>o&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#ee(e,n){return e.length===0?n||"Untitled":e.map(r=>r.text).join(" > ")}}});import{readFileSync as Nv,realpathSync as HN}from"node:fs";import{resolve as Ui}from"node:path";function Dv(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function UN(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function BN(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function Av(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function ZN(t,e=!1){let n,r=t.indexOf(":");if(r!==-1){let o=t.slice(0,r),s=t.slice(r+1),i=BN(o),a=Av(s);n=`^${i}(\\s${a})?$`}else n=`^${Av(t)}$`;return new RegExp(n,e?"i":"")}function qN(t,e=!1){let n="",r=0;for(;r<t.length;)t[r]==="*"&&t[r+1]==="*"?r+2<t.length&&t[r+2]==="/"?(n+="(.*/)?",r+=3):(n+=".*",r+=2):t[r]==="*"?(n+="[^/]*",r++):t[r]==="?"?(n+="[^/]",r++):(n+=t[r].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),r++);return new RegExp(`^${n}$`,e?"i":"")}function VN(t,e,n=!1){for(let r of e){let o=Dv(r);if(o&&ZN(o,n).test(t))return r}return null}function Mv(t,e){let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;return n%2===1}function WN(t){let e=[],n="",r=!1,o=!1,s=!1,i=0;for(let a=0;a<t.length;a++){let c=t[a],u=Mv(t,a);c==="'"&&!o&&!s&&!u?(r=!r,n+=c):c==='"'&&!r&&!s&&!u?(o=!o,n+=c):c==="`"&&!r&&!o&&!u?(s=!s,n+=c):!r&&!o&&!s?c==="$"&&t[a+1]==="("&&!u?(i++,n+=c+t[a+1],a++):i>0&&c==="("&&!u?(i++,n+=c):c===")"&&i>0&&!u?(i--,n+=c):i===0&&(c===";"||c===`
|
|
455
|
+
`||c==="\r")&&!u?(e.push(n.trim()),n=""):i===0&&c==="|"&&t[a+1]==="|"||i===0&&c==="&"&&t[a+1]==="&"?(e.push(n.trim()),n="",a++):i===0&&c==="&"&&!u||i===0&&c==="|"?(e.push(n.trim()),n=""):n+=c:n+=c}return n.trim()&&e.push(n.trim()),e.filter(a=>a.length>0)}function jv(t){let e=[],n=!1,r=!1,o=-1,s=[],i=[],a=0;for(let c=0;c<t.length;c++){let u=t[c],l=Mv(t,c);if(u==="'"&&!r&&o===-1&&!l)n=!n;else if(u==='"'&&!n&&o===-1&&!l)r=!r;else if(u==="`"&&!n&&!r&&!l)if(o===-1)o=c+1;else{let d=t.slice(o,c);e.push(d),e.push(...jv(d)),o=-1}else if(!n&&o===-1){if(u==="$"&&t[c+1]==="("&&!l)t[c+2]==="("?(a+=2,c+=2):(s.push(c+2),i.push(a),a++,c++);else if(u==="("&&!l)a++;else if(u===")"&&!l&&(a>0&&a--,i.length>0&&a===i[i.length-1])){i.pop();let d=s.pop(),p=t.slice(d,c);e.push(p)}}}return e}function Lv(t){let e=[],n=WN(t);for(let r of n){e.push(r);for(let o of jv(r))e.push(...Lv(o))}return e}function wm(t){let e;try{e=Nv(t,"utf-8")}catch{return null}let n;try{n=JSON.parse(e)}catch{return null}let r=n?.permissions;if(!r||typeof r!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&Dv(i)!==null):[];return{allow:o(r.allow),deny:o(r.deny),ask:o(r.ask)}}function Em(t,e){let n=[];if(t){let o=Ui(t,".claude","settings.local.json"),s=wm(o);s&&n.push(s);let i=Ui(t,".claude","settings.json"),a=wm(i);a&&n.push(a)}let r=e!==void 0?[e]:ym();for(let o of r){let s=wm(o);s&&n.push(s)}return n}function po(t,e,n){let r=[],o=i=>{let a;try{a=Nv(i,"utf-8")}catch{return null}let c;try{c=JSON.parse(a)}catch{return null}let u=c?.permissions?.deny;if(!Array.isArray(u))return[];let l=[];for(let d of u){if(typeof d!="string")continue;let p=UN(d);p&&p.tool===t&&l.push(p.glob)}return l};if(e){let i=o(Ui(e,".claude","settings.local.json"));i!==null&&r.push(i);let a=o(Ui(e,".claude","settings.json"));a!==null&&r.push(a)}let s=n!==void 0?[n]:ym();for(let i of s){let a=o(i);a!==null&&r.push(a)}return r}function Tm(t,e,n=process.platform==="win32"||process.platform==="darwin"){let r=Lv(t);for(let o of r)for(let s of e){let i=VN(o,s.deny,n);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function mo(t,e,n=process.platform==="win32"||process.platform==="darwin",r){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),r){let i=Ui(r,t);s.add(o(i));try{s.add(o(HN(i)))}catch{}}for(let i of e)for(let a of i){let c=qN(o(a),n);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function GN(t){let e=[],n=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,r;for(;(r=n.exec(t))!==null;){let s=[...r[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function zv(t,e){let n=KN[e];if(!n&&e!=="python")return[];let r=[];if(n)for(let o of n){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&r.push(i)}}return e==="python"&&r.push(...GN(t)),r}var KN,$m=v(()=>{"use strict";kr();KN={python:[/os\.system\(\s*(['"])(.*?)\1\s*\)/g,/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g],javascript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],typescript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],ruby:[/system\(\s*(['"])(.*?)\1/g,/`(.*?)`/g],go:[/exec\.Command\(\s*(['"`])(.*?)\1/g],php:[/shell_exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,/passthru\(\s*(['"`])(.*?)\1/g,/proc_open\(\s*(['"`])(.*?)\1/g],rust:[/Command::new\(\s*(['"`])(.*?)\1/g]}});var Uv={};_e(Uv,{healClaudeJsonMcpArgs:()=>lD,healInstalledPlugins:()=>aD,healMcpJsonArgs:()=>uD,healPluginJsonMcpServers:()=>Qc,healSettingsEnabledPlugins:()=>cD,sweepStaleMcpJson:()=>eu});import{existsSync as Yn,readFileSync as vs,writeFileSync as Zi,readdirSync as oD,unlinkSync as sD,statSync as iD}from"node:fs";import{resolve as vt,sep as fo}from"node:path";function aD({registryPath:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!Yn(t))return{healed:[],skipped:"no-registry"};let r;try{r=vs(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let o;try{o=JSON.parse(r)}catch(c){return{healed:[],error:`parse-failed: ${c&&c.message||c}`}}if(!o||typeof o!="object")return{healed:[],error:"bad-shape"};let s=o.plugins&&o.plugins[n]||[];if(!Array.isArray(s)||s.length===0)return{healed:[],skipped:"no-entry"};let i=[],a=null;for(let c of s){if(!c||typeof c!="object")continue;let u=c.installPath;if(!u||typeof u!="string")continue;let l=vt(u),d=vt(e)+fo;if(!l.startsWith(d))continue;let p=vt(u,".claude-plugin","plugin.json");if(!Yn(p))continue;let h=null;try{let m=JSON.parse(vs(p,"utf-8"));m&&typeof m.version=="string"&&m.version&&(h=m.version)}catch{continue}h&&(a=h,c.version!==h&&(c.version=h,i.includes("entry-version")||i.push("entry-version")))}if(a){(!o.enabledPlugins||typeof o.enabledPlugins!="object"||Array.isArray(o.enabledPlugins))&&(o.enabledPlugins={});let c=o.enabledPlugins[n];(c==null||c===!1||c==="")&&(o.enabledPlugins[n]=!0,i.push("enabled-plugins"))}if(i.length>0)try{Zi(t,JSON.stringify(o,null,2)+`
|
|
456
|
+
`,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function cD({settingsPath:t,pluginKey:e}){if(!t||!Yn(t))return{healed:[],skipped:"no-settings"};let n;try{n=vs(t,"utf-8")}catch(i){return{healed:[],error:`read-failed: ${i&&i.message||i}`}}let r;try{r=JSON.parse(n)}catch(i){return{healed:[],error:`parse-failed: ${i&&i.message||i}`}}let o=[];(!r.enabledPlugins||typeof r.enabledPlugins!="object"||Array.isArray(r.enabledPlugins))&&(r.enabledPlugins={});let s=r.enabledPlugins[e];if(s===!1)return{healed:[],skipped:"explicit-opt-out"};if(s!==!0&&(r.enabledPlugins[e]=!0,o.push("enabled-plugins")),o.length>0)try{Zi(t,JSON.stringify(r,null,2)+`
|
|
457
|
+
`,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:o}}function Qc({pluginRoot:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!e||!n)return{healed:[],skipped:"missing-args"};let r=vt(t),o=vt(e)+fo;if(!r.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=vt(t,".claude-plugin","plugin.json");if(!Yn(s))return{healed:[],skipped:"no-plugin-json"};let i;try{i=vs(s,"utf-8")}catch(f){return{healed:[],error:`read-failed: ${f&&f.message||f}`}}let a;try{a=JSON.parse(i)}catch(f){return{healed:[],error:`parse-failed: ${f&&f.message||f}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=n.split("@")[0],l=c[u];if(!l||typeof l!="object"||!Array.isArray(l.args))return{healed:[],skipped:"no-our-server"};let d=[],p=l.args,h=p.map(f=>typeof f!="string"||f===Bi?f:/[/\\]start\.mjs$/.test(f)?Bi:f);if(h.some((f,g)=>f!==p[g])){l.args=h,d.push("plugin-json-args");try{Zi(s,JSON.stringify(a,null,2)+`
|
|
458
|
+
`,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:d}}function uD({pluginRoot:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!e||!n)return{healed:[],skipped:"missing-args"};let r=vt(t),o=vt(e)+fo;if(!r.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=vt(t,".mcp.json");if(!Yn(s))return{healed:[],skipped:"no-mcp-json"};let i;try{i=vs(s,"utf-8")}catch(f){return{healed:[],error:`read-failed: ${f&&f.message||f}`}}let a;try{a=JSON.parse(i)}catch(f){return{healed:[],error:`parse-failed: ${f&&f.message||f}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=n.split("@")[0],l=c[u];if(!l||typeof l!="object"||!Array.isArray(l.args))return{healed:[],skipped:"no-our-server"};let d=[],p=l.args,h=p.map(f=>typeof f!="string"||f===Bi?f:f==="./start.mjs"||f==="start.mjs"||/[/\\]start\.mjs$/.test(f)?Bi:f);if(h.some((f,g)=>f!==p[g])){l.args=h,d.push("mcp-json-args");try{Zi(s,JSON.stringify(a,null,2)+`
|
|
459
|
+
`,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:d}}function lD({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:n}){if(!t||!Yn(t))return{healed:[],skipped:"no-claude-json"};let r;try{r=vs(t,"utf-8")}catch(l){return{healed:[],error:`read-failed: ${l&&l.message||l}`}}let o;try{o=JSON.parse(r)}catch(l){return{healed:[],error:`parse-failed: ${l&&l.message||l}`}}let s=o&&o.mcpServers;if(!s||typeof s!="object")return{healed:[],skipped:"no-mcp-servers"};let i=e.replace(/\\/g,"/"),a=vt(n),c=a+fo,u=!1;for(let l of Object.values(s))if(!(!l||typeof l!="object"||!Array.isArray(l.args)))for(let d=0;d<l.args.length;d++){let p=l.args[d];if(typeof p!="string")continue;let h=p.replace(/\\/g,"/");if(!h.startsWith(i+"/"))continue;let m=h.slice(i.length+1),f=m.indexOf("/");if(f<0)continue;let g=m.slice(f+1),y=vt(n,g);y!==a&&!(y+fo).startsWith(c)||y!==p&&(l.args[d]=y,u=!0)}if(!u)return{healed:[]};try{Zi(t,JSON.stringify(o,null,2),"utf-8")}catch(l){return{healed:[],error:`write-failed: ${l&&l.message||l}`}}return{healed:["claude-json-mcp-args"]}}function eu({pluginCacheRoot:t,pluginKey:e}){let n=[];if(!t||!e)return{removed:n,skipped:"missing-args"};let r=vt(t);if(!Yn(r))return{removed:n,skipped:"no-cache-root"};let[o,s]=e.split("@");if(!o||!s)return{removed:n,skipped:"bad-plugin-key"};let i=vt(r,o,s),a=r+fo;if(!i.startsWith(a))return{removed:n,skipped:"outside-cache-root"};if(!Yn(i))return{removed:n,skipped:"no-plugin-dir"};let c=[];try{c=oD(i)}catch{return{removed:n,skipped:"readdir-failed"}}for(let u of c){let l=vt(i,u);if(!l.startsWith(i+fo))continue;try{if(!iD(l).isDirectory())continue}catch{continue}let d=vt(l,".mcp.json");if(Yn(d))try{sD(d),n.push(d)}catch{}}return{removed:n}}var Bi,Pm=v(()=>{"use strict";Bi="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ce,Rm,z,An,qi=v(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ce||(ce={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Rm||(Rm={}));z=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),An=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}}});var I,mD,Rt,tu=v(()=>{qi();I=ce.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"]),mD=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Rt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ce.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Rt.create=t=>new Rt(t)});var fD,Qn,Cm=v(()=>{tu();qi();fD=(t,e)=>{let n;switch(t.code){case I.invalid_type:t.received===z.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:ce.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case I.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case I.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=e.defaultError,ce.assertNever(t)}return{message:n}},Qn=fD});function hD(t){Zv=t}function ks(){return Zv}var Zv,nu=v(()=>{Cm();Zv=Qn});function M(t,e){let n=ks(),r=Vi({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Qn?void 0:Qn].filter(o=>!!o)});t.common.issues.push(r)}var Vi,gD,at,G,ho,gt,ru,ou,$r,ws,Om=v(()=>{nu();Cm();Vi=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},gD=[];at=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return G;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return G;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},G=Object.freeze({status:"aborted"}),ho=t=>({status:"dirty",value:t}),gt=t=>({status:"valid",value:t}),ru=t=>t.status==="aborted",ou=t=>t.status==="dirty",$r=t=>t.status==="valid",ws=t=>typeof Promise<"u"&&t instanceof Promise});var qv=v(()=>{});var B,Vv=v(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(B||(B={}))});function te(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}function Jv(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function AD(t){return new RegExp(`^${Jv(t)}$`)}function Xv(t){let e=`${Gv}T${Jv(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function ND(t,e){return!!((e==="v4"||!e)&&TD.test(t)||(e==="v6"||!e)&&PD.test(t))}function DD(t,e){if(!vD.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function MD(t,e){return!!((e==="v4"||!e)&&$D.test(t)||(e==="v6"||!e)&&RD.test(t))}function jD(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Es(t){if(t instanceof Ot){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Ct.create(Es(r))}return new Ot({...t._def,shape:()=>e})}else return t instanceof nr?new nr({...t._def,type:Es(t.element)}):t instanceof Ct?Ct.create(Es(t.unwrap())):t instanceof Dn?Dn.create(Es(t.unwrap())):t instanceof Nn?Nn.create(t.items.map(e=>Es(e))):t}function Am(t,e){let n=An(t),r=An(e);if(t===e)return{valid:!0,data:t};if(n===z.object&&r===z.object){let o=ce.objectKeys(e),s=ce.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Am(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===z.array&&r===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Am(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===z.date&&r===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Yv(t,e){return new To({values:t,typeName:D.ZodEnum,...te(e)})}function Kv(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Qv(t,e={},n){return t?Rr.create().superRefine((r,o)=>{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Kv(e,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Kv(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Rr.create()}var tn,Wv,re,yD,_D,xD,bD,SD,vD,kD,wD,ED,Im,TD,$D,PD,RD,CD,OD,Gv,ID,Pr,go,yo,_o,xo,Ts,bo,So,Rr,tr,fn,$s,nr,Ot,vo,er,su,ko,Nn,iu,Ps,Rs,au,wo,Eo,To,$o,Cr,nn,Ct,Dn,Po,Ro,Cs,LD,Wi,Ki,Co,zD,D,FD,ek,tk,HD,UD,nk,BD,ZD,qD,VD,WD,KD,GD,JD,XD,Nm,YD,QD,e1,t1,n1,r1,o1,s1,i1,a1,c1,u1,l1,d1,p1,m1,f1,h1,g1,y1,_1,x1,b1,S1,rk=v(()=>{tu();nu();Vv();Om();qi();tn=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Wv=(t,e)=>{if($r(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Rt(t.common.issues);return this._error=n,this._error}}};re=class{get description(){return this._def.description}_getType(e){return An(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:An(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new at,ctx:{common:e.parent.common,data:e.data,parsedType:An(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(ws(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:An(e)},o=this._parseSync({data:e,path:r.path,parent:r});return Wv(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:An(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return $r(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>$r(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:An(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(ws(o)?o:Promise.resolve(o));return Wv(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:I.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new nn({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:n=>this["~validate"](n)}}optional(){return Ct.create(this,this._def)}nullable(){return Dn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nr.create(this)}promise(){return Cr.create(this,this._def)}or(e){return vo.create([this,e],this._def)}and(e){return ko.create(this,e,this._def)}transform(e){return new nn({...te(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Po({...te(this._def),innerType:this,defaultValue:n,typeName:D.ZodDefault})}brand(){return new Wi({typeName:D.ZodBranded,type:this,...te(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Ro({...te(this._def),innerType:this,catchValue:n,typeName:D.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Ki.create(this,e)}readonly(){return Co.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},yD=/^c[^\s-]{8,}$/i,_D=/^[0-9a-z]+$/,xD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bD=/^[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,SD=/^[a-z0-9_-]{21}$/i,vD=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,kD=/^[-+]?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)?)??$/,wD=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ED="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",TD=/^(?:(?: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])$/,$D=/^(?:(?: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])$/,PD=/^(([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]))$/,RD=/^(([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])$/,CD=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,OD=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gv="((\\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])))",ID=new RegExp(`^${Gv}$`);Pr=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_type,expected:z.string,received:s.parsedType}),G}let r=new at,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?M(o,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&M(o,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")wD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"email",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Im||(Im=new RegExp(ED,"u")),Im.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"emoji",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")bD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"uuid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")SD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"nanoid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")yD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"cuid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")_D.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"cuid2",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")xD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"ulid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),M(o,{validation:"url",code:I.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"regex",code:I.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Xv(s).test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?ID.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?AD(s).test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?kD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"duration",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?ND(e.data,s.version)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"ip",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?DD(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"jwt",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?MD(e.data,s.version)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"cidr",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?CD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"base64",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?OD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"base64url",code:I.invalid_string,message:s.message}),r.dirty()):ce.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:I.invalid_string,...B.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...B.errToObj(e)})}url(e){return this._addCheck({kind:"url",...B.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...B.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...B.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...B.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...B.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...B.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...B.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...B.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...B.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...B.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...B.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...B.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...B.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...B.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...B.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...B.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...B.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...B.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...B.errToObj(n)})}nonempty(e){return this.min(1,B.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Pr.create=t=>new Pr({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...te(t)});go=class t extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_type,expected:z.number,received:s.parsedType}),G}let r,o=new at;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:I.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?jD(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_finite,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,B.toString(n))}gt(e,n){return this.setLimit("min",e,!1,B.toString(n))}lte(e,n){return this.setLimit("max",e,!0,B.toString(n))}lt(e,n){return this.setLimit("max",e,!1,B.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:B.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:B.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:B.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:B.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:B.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ce.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};go.create=t=>new go({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...te(t)});yo=class t extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let r,o=new at;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return M(n,{code:I.invalid_type,expected:z.bigint,received:n.parsedType}),G}gte(e,n){return this.setLimit("min",e,!0,B.toString(n))}gt(e,n){return this.setLimit("min",e,!1,B.toString(n))}lte(e,n){return this.setLimit("max",e,!0,B.toString(n))}lt(e,n){return this.setLimit("max",e,!1,B.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:B.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};yo.create=t=>new yo({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...te(t)});_o=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:z.boolean,received:r.parsedType}),G}return gt(e.data)}};_o.create=t=>new _o({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...te(t)});xo=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_type,expected:z.date,received:s.parsedType}),G}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_date}),G}let r=new at,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):ce.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:B.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:B.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};xo.create=t=>new xo({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...te(t)});Ts=class extends re{_parse(e){if(this._getType(e)!==z.symbol){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:z.symbol,received:r.parsedType}),G}return gt(e.data)}};Ts.create=t=>new Ts({typeName:D.ZodSymbol,...te(t)});bo=class extends re{_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:z.undefined,received:r.parsedType}),G}return gt(e.data)}};bo.create=t=>new bo({typeName:D.ZodUndefined,...te(t)});So=class extends re{_parse(e){if(this._getType(e)!==z.null){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:z.null,received:r.parsedType}),G}return gt(e.data)}};So.create=t=>new So({typeName:D.ZodNull,...te(t)});Rr=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return gt(e.data)}};Rr.create=t=>new Rr({typeName:D.ZodAny,...te(t)});tr=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return gt(e.data)}};tr.create=t=>new tr({typeName:D.ZodUnknown,...te(t)});fn=class extends re{_parse(e){let n=this._getOrReturnCtx(e);return M(n,{code:I.invalid_type,expected:z.never,received:n.parsedType}),G}};fn.create=t=>new fn({typeName:D.ZodNever,...te(t)});$s=class extends re{_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:z.void,received:r.parsedType}),G}return gt(e.data)}};$s.create=t=>new $s({typeName:D.ZodVoid,...te(t)});nr=class t extends re{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==z.array)return M(n,{code:I.invalid_type,expected:z.array,received:n.parsedType}),G;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(M(n,{code:i?I.too_big:I.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(M(n,{code:I.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(M(n,{code:I.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new tn(n,i,n.path,a)))).then(i=>at.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new tn(n,i,n.path,a)));return at.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:B.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:B.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:B.toString(n)}})}nonempty(e){return this.min(1,e)}};nr.create=(t,e)=>new nr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...te(e)});Ot=class t extends re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=ce.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return M(u,{code:I.invalid_type,expected:z.object,received:u.parsedType}),G}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof fn&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new tn(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof fn){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(M(o,{code:I.unrecognized_keys,keys:a}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new tn(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>at.mergeObjectSync(r,u)):at.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return B.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:B.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of ce.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of ce.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Es(this)}partial(e){let n={};for(let r of ce.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of ce.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Ct;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return Yv(ce.objectKeys(this.shape))}};Ot.create=(t,e)=>new Ot({shape:()=>t,unknownKeys:"strip",catchall:fn.create(),typeName:D.ZodObject,...te(e)});Ot.strictCreate=(t,e)=>new Ot({shape:()=>t,unknownKeys:"strict",catchall:fn.create(),typeName:D.ZodObject,...te(e)});Ot.lazycreate=(t,e)=>new Ot({shape:t,unknownKeys:"strip",catchall:fn.create(),typeName:D.ZodObject,...te(e)});vo=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Rt(a.ctx.common.issues));return M(n,{code:I.invalid_union,unionErrors:i}),G}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Rt(c));return M(n,{code:I.invalid_union,unionErrors:a}),G}}get options(){return this._def.options}};vo.create=(t,e)=>new vo({options:t,typeName:D.ZodUnion,...te(e)});er=t=>t instanceof wo?er(t.schema):t instanceof nn?er(t.innerType()):t instanceof Eo?[t.value]:t instanceof To?t.options:t instanceof $o?ce.objectValues(t.enum):t instanceof Po?er(t._def.innerType):t instanceof bo?[void 0]:t instanceof So?[null]:t instanceof Ct?[void 0,...er(t.unwrap())]:t instanceof Dn?[null,...er(t.unwrap())]:t instanceof Wi||t instanceof Co?er(t.unwrap()):t instanceof Ro?er(t._def.innerType):[],su=class t extends re{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return M(n,{code:I.invalid_type,expected:z.object,received:n.parsedType}),G;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(M(n,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),G)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=er(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...te(r)})}};ko=class extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(ru(s)||ru(i))return G;let a=Am(s.value,i.value);return a.valid?((ou(s)||ou(i))&&n.dirty(),{status:n.value,value:a.data}):(M(r,{code:I.invalid_intersection_types}),G)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};ko.create=(t,e,n)=>new ko({left:t,right:e,typeName:D.ZodIntersection,...te(n)});Nn=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.array)return M(r,{code:I.invalid_type,expected:z.array,received:r.parsedType}),G;if(r.data.length<this._def.items.length)return M(r,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),G;!this._def.rest&&r.data.length>this._def.items.length&&(M(r,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new tn(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>at.mergeArray(n,i)):at.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Nn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nn({items:t,typeName:D.ZodTuple,rest:null,...te(e)})};iu=class t extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return M(r,{code:I.invalid_type,expected:z.object,received:r.parsedType}),G;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new tn(r,a,r.path,a)),value:i._parse(new tn(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?at.mergeObjectAsync(n,o):at.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof re?new t({keyType:e,valueType:n,typeName:D.ZodRecord,...te(r)}):new t({keyType:Pr.create(),valueType:e,typeName:D.ZodRecord,...te(n)})}},Ps=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.map)return M(r,{code:I.invalid_type,expected:z.map,received:r.parsedType}),G;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],u)=>({key:o._parse(new tn(r,a,r.path,[u,"key"])),value:s._parse(new tn(r,c,r.path,[u,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return G;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return G;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}};Ps.create=(t,e,n)=>new Ps({valueType:e,keyType:t,typeName:D.ZodMap,...te(n)});Rs=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.set)return M(r,{code:I.invalid_type,expected:z.set,received:r.parsedType}),G;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(M(r,{code:I.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(M(r,{code:I.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return G;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let a=[...r.data.values()].map((c,u)=>s._parse(new tn(r,c,r.path,u)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:B.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:B.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Rs.create=(t,e)=>new Rs({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...te(e)});au=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.function)return M(n,{code:I.invalid_type,expected:z.function,received:n.parsedType}),G;function r(a,c){return Vi({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ks(),Qn].filter(u=>!!u),issueData:{code:I.invalid_arguments,argumentsError:c}})}function o(a,c){return Vi({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ks(),Qn].filter(u=>!!u),issueData:{code:I.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Cr){let a=this;return gt(async function(...c){let u=new Rt([]),l=await a._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(r(c,h)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw u.addIssue(o(d,h)),u})})}else{let a=this;return gt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Rt([r(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Rt([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Nn.create(e).rest(tr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||Nn.create([]).rest(tr.create()),returns:n||tr.create(),typeName:D.ZodFunction,...te(r)})}},wo=class extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};wo.create=(t,e)=>new wo({getter:t,typeName:D.ZodLazy,...te(e)});Eo=class extends re{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return M(n,{received:n.data,code:I.invalid_literal,expected:this._def.value}),G}return{status:"valid",value:e.data}}get value(){return this._def.value}};Eo.create=(t,e)=>new Eo({value:t,typeName:D.ZodLiteral,...te(e)});To=class t extends re{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{expected:ce.joinValues(r),received:n.parsedType,code:I.invalid_type}),G}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{received:n.data,code:I.invalid_enum_value,options:r}),G}return gt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};To.create=Yv;$o=class extends re{_parse(e){let n=ce.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==z.string&&r.parsedType!==z.number){let o=ce.objectValues(n);return M(r,{expected:ce.joinValues(o),received:r.parsedType,code:I.invalid_type}),G}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ce.objectValues(n);return M(r,{received:r.data,code:I.invalid_enum_value,options:o}),G}return gt(e.data)}get enum(){return this._def.values}};$o.create=(t,e)=>new $o({values:t,typeName:D.ZodNativeEnum,...te(e)});Cr=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.promise&&n.common.async===!1)return M(n,{code:I.invalid_type,expected:z.promise,received:n.parsedType}),G;let r=n.parsedType===z.promise?n.data:Promise.resolve(n.data);return gt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Cr.create=(t,e)=>new Cr({type:t,typeName:D.ZodPromise,...te(e)});nn=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{M(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return G;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?G:c.status==="dirty"?ho(c.value):n.value==="dirty"?ho(c.value):c});{if(n.value==="aborted")return G;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?G:a.status==="dirty"?ho(a.value):n.value==="dirty"?ho(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?G:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?G:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!$r(i))return G;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>$r(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):G);ce.assertNever(o)}};nn.create=(t,e,n)=>new nn({schema:t,typeName:D.ZodEffects,effect:e,...te(n)});nn.createWithPreprocess=(t,e,n)=>new nn({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...te(n)});Ct=class extends re{_parse(e){return this._getType(e)===z.undefined?gt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ct.create=(t,e)=>new Ct({innerType:t,typeName:D.ZodOptional,...te(e)});Dn=class extends re{_parse(e){return this._getType(e)===z.null?gt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Dn.create=(t,e)=>new Dn({innerType:t,typeName:D.ZodNullable,...te(e)});Po=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===z.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Po.create=(t,e)=>new Po({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});Ro=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ws(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Rt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Rt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ro.create=(t,e)=>new Ro({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});Cs=class extends re{_parse(e){if(this._getType(e)!==z.nan){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:z.nan,received:r.parsedType}),G}return{status:"valid",value:e.data}}};Cs.create=t=>new Cs({typeName:D.ZodNaN,...te(t)});LD=Symbol("zod_brand"),Wi=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Ki=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?G:s.status==="dirty"?(n.dirty(),ho(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?G:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:D.ZodPipeline})}},Co=class extends re{_parse(e){let n=this._def.innerType._parse(e),r=o=>($r(o)&&(o.value=Object.freeze(o.value)),o);return ws(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Co.create=(t,e)=>new Co({innerType:t,typeName:D.ZodReadonly,...te(e)});zD={object:Ot.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(D||(D={}));FD=(t,e={message:`Input not instance of ${t.name}`})=>Qv(n=>n instanceof t,e),ek=Pr.create,tk=go.create,HD=Cs.create,UD=yo.create,nk=_o.create,BD=xo.create,ZD=Ts.create,qD=bo.create,VD=So.create,WD=Rr.create,KD=tr.create,GD=fn.create,JD=$s.create,XD=nr.create,Nm=Ot.create,YD=Ot.strictCreate,QD=vo.create,e1=su.create,t1=ko.create,n1=Nn.create,r1=iu.create,o1=Ps.create,s1=Rs.create,i1=au.create,a1=wo.create,c1=Eo.create,u1=To.create,l1=$o.create,d1=Cr.create,p1=nn.create,m1=Ct.create,f1=Dn.create,h1=nn.createWithPreprocess,g1=Ki.create,y1=()=>ek().optional(),_1=()=>tk().optional(),x1=()=>nk().optional(),b1={string:(t=>Pr.create({...t,coerce:!0})),number:(t=>go.create({...t,coerce:!0})),boolean:(t=>_o.create({...t,coerce:!0})),bigint:(t=>yo.create({...t,coerce:!0})),date:(t=>xo.create({...t,coerce:!0}))},S1=G});var j={};_e(j,{BRAND:()=>LD,DIRTY:()=>ho,EMPTY_PATH:()=>gD,INVALID:()=>G,NEVER:()=>S1,OK:()=>gt,ParseStatus:()=>at,Schema:()=>re,ZodAny:()=>Rr,ZodArray:()=>nr,ZodBigInt:()=>yo,ZodBoolean:()=>_o,ZodBranded:()=>Wi,ZodCatch:()=>Ro,ZodDate:()=>xo,ZodDefault:()=>Po,ZodDiscriminatedUnion:()=>su,ZodEffects:()=>nn,ZodEnum:()=>To,ZodError:()=>Rt,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>au,ZodIntersection:()=>ko,ZodIssueCode:()=>I,ZodLazy:()=>wo,ZodLiteral:()=>Eo,ZodMap:()=>Ps,ZodNaN:()=>Cs,ZodNativeEnum:()=>$o,ZodNever:()=>fn,ZodNull:()=>So,ZodNullable:()=>Dn,ZodNumber:()=>go,ZodObject:()=>Ot,ZodOptional:()=>Ct,ZodParsedType:()=>z,ZodPipeline:()=>Ki,ZodPromise:()=>Cr,ZodReadonly:()=>Co,ZodRecord:()=>iu,ZodSchema:()=>re,ZodSet:()=>Rs,ZodString:()=>Pr,ZodSymbol:()=>Ts,ZodTransformer:()=>nn,ZodTuple:()=>Nn,ZodType:()=>re,ZodUndefined:()=>bo,ZodUnion:()=>vo,ZodUnknown:()=>tr,ZodVoid:()=>$s,addIssueToContext:()=>M,any:()=>WD,array:()=>XD,bigint:()=>UD,boolean:()=>nk,coerce:()=>b1,custom:()=>Qv,date:()=>BD,datetimeRegex:()=>Xv,defaultErrorMap:()=>Qn,discriminatedUnion:()=>e1,effect:()=>p1,enum:()=>u1,function:()=>i1,getErrorMap:()=>ks,getParsedType:()=>An,instanceof:()=>FD,intersection:()=>t1,isAborted:()=>ru,isAsync:()=>ws,isDirty:()=>ou,isValid:()=>$r,late:()=>zD,lazy:()=>a1,literal:()=>c1,makeIssue:()=>Vi,map:()=>o1,nan:()=>HD,nativeEnum:()=>l1,never:()=>GD,null:()=>VD,nullable:()=>f1,number:()=>tk,object:()=>Nm,objectUtil:()=>Rm,oboolean:()=>x1,onumber:()=>_1,optional:()=>m1,ostring:()=>y1,pipeline:()=>g1,preprocess:()=>h1,promise:()=>d1,quotelessJson:()=>mD,record:()=>r1,set:()=>s1,setErrorMap:()=>hD,strictObject:()=>YD,string:()=>ek,symbol:()=>ZD,transformer:()=>p1,tuple:()=>n1,undefined:()=>qD,union:()=>QD,unknown:()=>KD,util:()=>ce,void:()=>JD});var cu=v(()=>{nu();Om();qv();qi();rk();tu()});var Gi=v(()=>{cu()});function $(t,e,n){function r(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Ut(t){return t&&Object.assign(uu,t),uu}var k1,rr,uu,Os=v(()=>{k1=Object.freeze({status:"aborted"});rr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},uu={}});var ue={};_e(ue,{BIGINT_FORMAT_RANGES:()=>sk,Class:()=>Mm,NUMBER_FORMAT_RANGES:()=>Bm,aborted:()=>Io,allowsEval:()=>Fm,assert:()=>P1,assertEqual:()=>w1,assertIs:()=>T1,assertNever:()=>$1,assertNotEqual:()=>E1,assignProp:()=>zm,cached:()=>Yi,captureStackTrace:()=>du,cleanEnum:()=>H1,cleanRegex:()=>ea,clone:()=>Bt,createTransparentProxy:()=>N1,defineLazy:()=>Ee,esc:()=>Oo,escapeRegex:()=>Or,extend:()=>j1,finalizeIssue:()=>hn,floatSafeRemainder:()=>Lm,getElementAtPath:()=>R1,getEnumValues:()=>Xi,getLengthableOrigin:()=>ta,getParsedType:()=>A1,getSizableOrigin:()=>ik,isObject:()=>Is,isPlainObject:()=>As,issue:()=>Zm,joinValues:()=>lu,jsonStringifyReplacer:()=>jm,merge:()=>L1,normalizeParams:()=>J,nullish:()=>Qi,numKeys:()=>I1,omit:()=>M1,optionalKeys:()=>Um,partial:()=>z1,pick:()=>D1,prefixIssues:()=>Mn,primitiveTypes:()=>ok,promiseAllObject:()=>C1,propertyKeyTypes:()=>Hm,randomString:()=>O1,required:()=>F1,stringifyPrimitive:()=>pu,unwrapMessage:()=>Ji});function w1(t){return t}function E1(t){return t}function T1(t){}function $1(t){throw new Error}function P1(t){}function Xi(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function lu(t,e="|"){return t.map(n=>pu(n)).join(e)}function jm(t,e){return typeof e=="bigint"?e.toString():e}function Yi(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Qi(t){return t==null}function ea(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Lm(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Ee(t,e,n){Object.defineProperty(t,e,{get(){{let o=n();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function zm(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function R1(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function C1(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function O1(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Oo(t){return JSON.stringify(t)}function Is(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function As(t){if(Is(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(Is(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function I1(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}function Or(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Bt(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function J(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function N1(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function pu(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Um(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function D1(t,e){let n={},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(n[o]=r.shape[o])}return Bt(t,{...t._zod.def,shape:n,checks:[]})}function M1(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete n[o]}return Bt(t,{...t._zod.def,shape:n,checks:[]})}function j1(t,e){if(!As(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return zm(this,"shape",r),r},checks:[]};return Bt(t,n)}function L1(t,e){return Bt(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return zm(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function z1(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=t?new t({type:"optional",innerType:r[s]}):r[s])}else for(let s in r)o[s]=t?new t({type:"optional",innerType:r[s]}):r[s];return Bt(e,{...e._zod.def,shape:o,checks:[]})}function F1(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(let s in r)o[s]=new t({type:"nonoptional",innerType:r[s]});return Bt(e,{...e._zod.def,shape:o,checks:[]})}function Io(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Mn(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Ji(t){return typeof t=="string"?t:t?.message}function hn(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let o=Ji(t.inst?._zod.def?.error?.(t))??Ji(e?.error?.(t))??Ji(n.customError?.(t))??Ji(n.localeError?.(t))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function ik(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ta(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Zm(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function H1(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var du,Fm,A1,Hm,ok,Bm,sk,Mm,jn=v(()=>{du=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Fm=Yi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});A1=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Hm=new Set(["string","number","symbol"]),ok=new Set(["string","number","bigint","boolean","symbol","undefined"]);Bm={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},sk={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Mm=class{constructor(...e){}}});function qm(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function Vm(t,e){let n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),r}var ak,mu,na,Wm=v(()=>{Os();jn();ak=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,jm,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},mu=$("$ZodError",ak),na=$("$ZodError",ak,{Parent:Error})});var Km,Gm,Jm,Xm,Ym,Ao,Qm,No,ef=v(()=>{Os();Wm();jn();Km=t=>(e,n,r,o)=>{let s=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new rr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>hn(c,s,Ut())));throw du(a,o?.callee),a}return i.value},Gm=Km(na),Jm=t=>async(e,n,r,o)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>hn(c,s,Ut())));throw du(a,o?.callee),a}return i.value},Xm=Jm(na),Ym=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new rr;return s.issues.length?{success:!1,error:new(t??mu)(s.issues.map(i=>hn(i,o,Ut())))}:{success:!0,data:s.value}},Ao=Ym(na),Qm=t=>async(e,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>hn(i,o,Ut())))}:{success:!0,data:s.value}},No=Qm(na)});function yk(){return new RegExp(B1,"u")}function $k(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Pk(t){return new RegExp(`^${$k(t)}$`)}function Rk(t){let e=$k({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Ek}T(?:${r})$`)}var ck,uk,lk,dk,pk,mk,fk,hk,tf,gk,B1,_k,xk,bk,Sk,vk,nf,kk,wk,Ek,Tk,Ck,Ok,Ik,Ak,Nk,Dk,Mk,hu=v(()=>{ck=/^[cC][^\s-]{8,}$/,uk=/^[0-9a-z]+$/,lk=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,dk=/^[0-9a-vA-V]{20}$/,pk=/^[A-Za-z0-9]{27}$/,mk=/^[a-zA-Z0-9_-]{21}$/,fk=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,hk=/^([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})$/,tf=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/,gk=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,B1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";_k=/^(?:(?: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])$/,xk=/^(([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})$/,bk=/^((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])$/,Sk=/^(([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])$/,vk=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,nf=/^[A-Za-z0-9_-]*$/,kk=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,wk=/^\+(?:[0-9]){6,14}[0-9]$/,Ek="(?:(?:\\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])))",Tk=new RegExp(`^${Ek}$`);Ck=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Ok=/^\d+$/,Ik=/^-?\d+(?:\.\d+)?/i,Ak=/true|false/i,Nk=/null/i,Dk=/^[^A-Z]*$/,Mk=/^[^a-z]*$/});var ct,jk,rf,of,Lk,zk,Fk,Hk,Uk,ra,Bk,Zk,qk,Vk,Wk,Kk,Gk,gu=v(()=>{Os();hu();jn();ct=$("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),jk={number:"number",bigint:"bigint",object:"date"},rf=$("$ZodCheckLessThan",(t,e)=>{ct.init(t,e);let n=jk[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),of=$("$ZodCheckGreaterThan",(t,e)=>{ct.init(t,e);let n=jk[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Lk=$("$ZodCheckMultipleOf",(t,e)=>{ct.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):Lm(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),zk=$("$ZodCheckNumberFormat",(t,e)=>{ct.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=Bm[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=Ok)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Fk=$("$ZodCheckMaxLength",(t,e)=>{var n;ct.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Qi(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let i=ta(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Hk=$("$ZodCheckMinLength",(t,e)=>{var n;ct.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Qi(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=ta(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Uk=$("$ZodCheckLengthEquals",(t,e)=>{var n;ct.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Qi(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=ta(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),ra=$("$ZodCheckStringFormat",(t,e)=>{var n,r;ct.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Bk=$("$ZodCheckRegex",(t,e)=>{ra.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Zk=$("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Dk),ra.init(t,e)}),qk=$("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Mk),ra.init(t,e)}),Vk=$("$ZodCheckIncludes",(t,e)=>{ct.init(t,e);let n=Or(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Wk=$("$ZodCheckStartsWith",(t,e)=>{ct.init(t,e);let n=new RegExp(`^${Or(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Kk=$("$ZodCheckEndsWith",(t,e)=>{ct.init(t,e);let n=new RegExp(`.*${Or(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),Gk=$("$ZodCheckOverwrite",(t,e)=>{ct.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}})});var yu,sf=v(()=>{yu=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
|
|
460
|
+
`).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...n,o.join(`
|
|
461
|
+
`))}}});var Xk,af=v(()=>{Xk={major:4,minor:0,patch:0}});function d0(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function Z1(t){if(!nf.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return d0(n)}function q1(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function Yk(t,e,n){t.issues.length&&e.issues.push(...Mn(n,t.issues)),e.value[n]=t.value}function _u(t,e,n){t.issues.length&&e.issues.push(...Mn(n,t.issues)),e.value[n]=t.value}function Qk(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...Mn(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function e0(t,e,n,r){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(o=>o.issues.map(s=>hn(s,r,Ut())))}),e}function cf(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(As(t)&&As(e)){let n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=cf(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<t.length;r++){let o=t[r],s=e[r],i=cf(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function t0(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),Io(t))return t;let r=cf(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}function n0(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function r0(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function o0(t,e,n){return Io(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}function s0(t){return t.value=Object.freeze(t.value),t}function i0(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(Zm(o))}}var ve,oa,Te,uf,lf,df,pf,mf,ff,hf,gf,yf,_f,xf,a0,c0,u0,l0,bf,Sf,vf,kf,wf,Ef,Tf,$f,xu,Pf,Rf,Cf,Of,If,Af,bu,Su,Nf,Df,Mf,jf,Lf,zf,Ff,Hf,Uf,Bf,Zf,qf,Vf,Wf,Kf,p0=v(()=>{gu();Os();sf();ef();hu();jn();af();jn();ve=$("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Xk;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Io(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new rr;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=Io(s,d)))});else{if(s.issues.length===d)continue;c||(c=Io(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new rr;return a.then(c=>o(c,r,i))}return o(a,r,i)}}t["~standard"]={validate:o=>{try{let s=Ao(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return No(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),oa=$("$ZodString",(t,e)=>{ve.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ck(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),Te=$("$ZodStringFormat",(t,e)=>{ra.init(t,e),oa.init(t,e)}),uf=$("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=hk),Te.init(t,e)}),lf=$("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=tf(r))}else e.pattern??(e.pattern=tf());Te.init(t,e)}),df=$("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=gk),Te.init(t,e)}),pf=$("$ZodURL",(t,e)=>{Te.init(t,e),t._zod.check=n=>{try{let r=n.value,o=new URL(r),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:kk.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),mf=$("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=yk()),Te.init(t,e)}),ff=$("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=mk),Te.init(t,e)}),hf=$("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=ck),Te.init(t,e)}),gf=$("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=uk),Te.init(t,e)}),yf=$("$ZodULID",(t,e)=>{e.pattern??(e.pattern=lk),Te.init(t,e)}),_f=$("$ZodXID",(t,e)=>{e.pattern??(e.pattern=dk),Te.init(t,e)}),xf=$("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=pk),Te.init(t,e)}),a0=$("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Rk(e)),Te.init(t,e)}),c0=$("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Tk),Te.init(t,e)}),u0=$("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Pk(e)),Te.init(t,e)}),l0=$("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=fk),Te.init(t,e)}),bf=$("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=_k),Te.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),Sf=$("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=xk),Te.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),vf=$("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=bk),Te.init(t,e)}),kf=$("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Sk),Te.init(t,e),t._zod.check=n=>{let[r,o]=n.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});wf=$("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=vk),Te.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{d0(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});Ef=$("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=nf),Te.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{Z1(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Tf=$("$ZodE164",(t,e)=>{e.pattern??(e.pattern=wk),Te.init(t,e)});$f=$("$ZodJWT",(t,e)=>{Te.init(t,e),t._zod.check=n=>{q1(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),xu=$("$ZodNumber",(t,e)=>{ve.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ik,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),n}}),Pf=$("$ZodNumber",(t,e)=>{zk.init(t,e),xu.init(t,e)}),Rf=$("$ZodBoolean",(t,e)=>{ve.init(t,e),t._zod.pattern=Ak,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}}),Cf=$("$ZodNull",(t,e)=>{ve.init(t,e),t._zod.pattern=Nk,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}}),Of=$("$ZodUnknown",(t,e)=>{ve.init(t,e),t._zod.parse=n=>n}),If=$("$ZodNever",(t,e)=>{ve.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});Af=$("$ZodArray",(t,e)=>{ve.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},r);c instanceof Promise?s.push(c.then(u=>Yk(u,n,i))):Yk(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});bu=$("$ZodObject",(t,e)=>{ve.init(t,e);let n=Yi(()=>{let d=Object.keys(e.shape);for(let h of d)if(!(e.shape[h]instanceof ve))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let p=Um(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});Ee(t._zod,"propValues",()=>{let d=e.shape,p={};for(let h in d){let m=d[h]._zod;if(m.values){p[h]??(p[h]=new Set);for(let f of m.values)p[h].add(f)}}return p});let r=d=>{let p=new yu(["shape","payload","ctx"]),h=n.value,m=_=>{let x=Oo(_);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};p.write("const input = payload.value;");let f=Object.create(null),g=0;for(let _ of h.keys)f[_]=`key_${g++}`;p.write("const newResult = {}");for(let _ of h.keys)if(h.optionalKeys.has(_)){let x=f[_];p.write(`const ${x} = ${m(_)};`);let S=Oo(_);p.write(`
|
|
451
462
|
if (${x}.issues.length) {
|
|
452
|
-
if (input[${
|
|
453
|
-
if (${
|
|
454
|
-
newResult[${
|
|
463
|
+
if (input[${S}] === undefined) {
|
|
464
|
+
if (${S} in input) {
|
|
465
|
+
newResult[${S}] = undefined;
|
|
455
466
|
}
|
|
456
467
|
} else {
|
|
457
468
|
payload.issues = payload.issues.concat(
|
|
458
469
|
${x}.issues.map((iss) => ({
|
|
459
470
|
...iss,
|
|
460
|
-
path: iss.path ? [${
|
|
471
|
+
path: iss.path ? [${S}, ...iss.path] : [${S}],
|
|
461
472
|
}))
|
|
462
473
|
);
|
|
463
474
|
}
|
|
464
475
|
} else if (${x}.value === undefined) {
|
|
465
|
-
if (${
|
|
476
|
+
if (${S} in input) newResult[${S}] = undefined;
|
|
466
477
|
} else {
|
|
467
|
-
newResult[${
|
|
478
|
+
newResult[${S}] = ${x}.value;
|
|
468
479
|
}
|
|
469
480
|
`)}else{let x=f[_];p.write(`const ${x} = ${m(_)};`),p.write(`
|
|
470
481
|
if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
|
|
471
482
|
...iss,
|
|
472
|
-
path: iss.path ? [${
|
|
473
|
-
})));`),p.write(`newResult[${Co(_)}] = ${x}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let y=p.compile();return(_,x)=>y(d,_,x)},o,s=Is,i=!Xc.jitless,c=i&&fm.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let h=d.value;if(!s(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),d=o(d,p);else{d.value={};let x=l.shape;for(let v of l.keys){let E=x[v],C=E._zod.run({value:h[v],issues:[]},p),b=E._zod.optin==="optional"&&E._zod.optout==="optional";C instanceof Promise?m.push(C.then(k=>b?uk(k,d,v,h):iu(k,d,v))):b?uk(C,d,v,h):iu(C,d,v)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let f=[],g=l.keySet,y=u._zod,_=y.def.type;for(let x of Object.keys(h)){if(g.has(x))continue;if(_==="never"){f.push(x);continue}let v=y.run({value:h[x],issues:[]},p);v instanceof Promise?m.push(v.then(E=>iu(E,d,x))):iu(v,d,x)}return f.length&&d.issues.push({code:"unrecognized_keys",keys:f,input:h,inst:t}),m.length?Promise.all(m).then(()=>d):d}});uu=T("$ZodUnion",(t,e)=>{ve.init(t,e),Te(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Te(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Te(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Te(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Ji(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>lk(i,r,t,n)):lk(s,r,t,n)}}),cf=T("$ZodDiscriminatedUnion",(t,e)=>{uu.init(t,e);let r=t._zod.parse;Te(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Ki(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Is(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),uf=T("$ZodIntersection",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>dk(r,c,u)):dk(r,s,i)}});lf=T("$ZodRecord",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!As(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...jr(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...jr(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>gr(u,n,Ft())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...jr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...jr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),df=T("$ZodEnum",(t,e)=>{ve.init(t,e);let r=Wi(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>hm.has(typeof n)).map(n=>typeof n=="string"?In(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),pf=T("$ZodLiteral",(t,e)=>{ve.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?In(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),mf=T("$ZodTransform",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new sn;return r.value=o,r}}),ff=T("$ZodOptional",(t,e)=>{ve.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Te(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Te(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ji(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),hf=T("$ZodNullable",(t,e)=>{ve.init(t,e),Te(t._zod,"optin",()=>e.innerType._zod.optin),Te(t._zod,"optout",()=>e.innerType._zod.optout),Te(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ji(r.source)}|null)$`):void 0}),Te(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),gf=T("$ZodDefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Te(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>pk(s,e)):pk(o,e)}});yf=T("$ZodPrefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Te(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),_f=T("$ZodNonOptional",(t,e)=>{ve.init(t,e),Te(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>mk(s,t)):mk(o,t)}});xf=T("$ZodCatch",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Te(t._zod,"optout",()=>e.innerType._zod.optout),Te(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>gr(i,n,Ft()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>gr(s,n,Ft()))},input:r.value}),r.issues=[]),r)}}),bf=T("$ZodPipe",(t,e)=>{ve.init(t,e),Te(t._zod,"values",()=>e.in._zod.values),Te(t._zod,"optin",()=>e.in._zod.optin),Te(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>fk(s,e,n)):fk(o,e,n)}});vf=T("$ZodReadonly",(t,e)=>{ve.init(t,e),Te(t._zod,"propValues",()=>e.innerType._zod.propValues),Te(t._zod,"values",()=>e.innerType._zod.values),Te(t._zod,"optin",()=>e.innerType._zod.optin),Te(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(hk):hk(o)}});Sf=T("$ZodCustom",(t,e)=>{it.init(t,e),ve.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>gk(s,r,n,t));gk(o,r,n,t)}})});function kk(){return{localeError:$D()}}var ED,$D,wk=S(()=>{Lr();ED=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},$D=()=>{let t={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 e(n){return t[n]??null}let r={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 n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${ED(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${eu(n.values[0])}`:`Invalid option: expected one of ${Yc(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Yc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var lu=S(()=>{});function Ek(){return new ta}var ta,An,wf=S(()=>{ta=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};An=Ek()});function Ef(t,e){return new t({type:"string",...X(e)})}function $f(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...X(e)})}function du(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...X(e)})}function Tf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...X(e)})}function Pf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(e)})}function Rf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(e)})}function Cf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(e)})}function Of(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...X(e)})}function If(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...X(e)})}function Af(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(e)})}function Nf(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...X(e)})}function Df(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(e)})}function Mf(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...X(e)})}function jf(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...X(e)})}function Lf(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(e)})}function zf(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(e)})}function Ff(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(e)})}function Hf(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(e)})}function Uf(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(e)})}function Bf(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...X(e)})}function Zf(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...X(e)})}function qf(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...X(e)})}function Vf(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...X(e)})}function $k(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(e)})}function Tk(t,e){return new t({type:"string",format:"date",check:"string_format",...X(e)})}function Pk(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...X(e)})}function Rk(t,e){return new t({type:"string",format:"duration",check:"string_format",...X(e)})}function Wf(t,e){return new t({type:"number",checks:[],...X(e)})}function Kf(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...X(e)})}function Gf(t,e){return new t({type:"boolean",...X(e)})}function Jf(t,e){return new t({type:"null",...X(e)})}function Xf(t){return new t({type:"unknown"})}function Yf(t,e){return new t({type:"never",...X(e)})}function pu(t,e){return new Om({check:"less_than",...X(e),value:t,inclusive:!1})}function ra(t,e){return new Om({check:"less_than",...X(e),value:t,inclusive:!0})}function mu(t,e){return new Im({check:"greater_than",...X(e),value:t,inclusive:!1})}function na(t,e){return new Im({check:"greater_than",...X(e),value:t,inclusive:!0})}function fu(t,e){return new KS({check:"multiple_of",...X(e),value:t})}function hu(t,e){return new JS({check:"max_length",...X(e),maximum:t})}function Ns(t,e){return new XS({check:"min_length",...X(e),minimum:t})}function gu(t,e){return new YS({check:"length_equals",...X(e),length:t})}function Qf(t,e){return new QS({check:"string_format",format:"regex",...X(e),pattern:t})}function eh(t){return new ek({check:"string_format",format:"lowercase",...X(t)})}function th(t){return new tk({check:"string_format",format:"uppercase",...X(t)})}function rh(t,e){return new rk({check:"string_format",format:"includes",...X(e),includes:t})}function nh(t,e){return new nk({check:"string_format",format:"starts_with",...X(e),prefix:t})}function oh(t,e){return new ok({check:"string_format",format:"ends_with",...X(e),suffix:t})}function No(t){return new sk({check:"overwrite",tx:t})}function sh(t){return No(e=>e.normalize(t))}function ih(){return No(t=>t.trim())}function ah(){return No(t=>t.toLowerCase())}function ch(){return No(t=>t.toUpperCase())}function Ck(t,e,r){return new t({type:"array",element:e,...X(r)})}function uh(t,e,r){let n=X(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function lh(t,e,r){return new t({type:"custom",check:"custom",fn:e,...X(r)})}var Ok=S(()=>{ou();Lr()});var Ik=S(()=>{});function dh(t,e){if(t instanceof ta){let n=new yu(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new yu(e);return r.process(t),r.emit(t,e)}function Ye(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.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 Ye(o.element,r);case"object":{for(let s in o.shape)if(Ye(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ye(s,r))return!0;return!1}case"intersection":return Ye(o.left,r)||Ye(o.right,r);case"tuple":{for(let s of o.items)if(Ye(s,r))return!0;return!!(o.rest&&Ye(o.rest,r))}case"record":return Ye(o.keyType,r)||Ye(o.valueType,r);case"map":return Ye(o.keyType,r)||Ye(o.valueType,r);case"set":return Ye(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ye(o.innerType,r);case"lazy":return Ye(o.getter(),r);case"default":return Ye(o.innerType,r);case"prefault":return Ye(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ye(o.in,r)||Ye(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var yu,Ak=S(()=>{wf();Lr();yu=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??An,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let h=a.schema;switch(o.type){case"string":{let m=h;m.type="string";let{minimum:f,maximum:g,format:y,patterns:_,contentEncoding:x}=e._zod.bag;if(typeof f=="number"&&(m.minLength=f),typeof g=="number"&&(m.maxLength=g),y&&(m.format=s[y]??y,m.format===""&&delete m.format),x&&(m.contentEncoding=x),_&&_.size>0){let v=[..._];v.length===1?m.pattern=v[0].source:v.length>1&&(a.schema.allOf=[...v.map(E=>({...this.target==="draft-7"?{type:"string"}:{},pattern:E.source}))])}break}case"number":{let m=h,{minimum:f,maximum:g,format:y,multipleOf:_,exclusiveMaximum:x,exclusiveMinimum:v}=e._zod.bag;typeof y=="string"&&y.includes("int")?m.type="integer":m.type="number",typeof v=="number"&&(m.exclusiveMinimum=v),typeof f=="number"&&(m.minimum=f,typeof v=="number"&&(v>=f?delete m.minimum:delete m.exclusiveMinimum)),typeof x=="number"&&(m.exclusiveMaximum=x),typeof g=="number"&&(m.maximum=g,typeof x=="number"&&(x<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof _=="number"&&(m.multipleOf=_);break}case"boolean":{let m=h;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=h,{minimum:f,maximum:g}=e._zod.bag;typeof f=="number"&&(m.minItems=f),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let m=h;m.type="object",m.properties={};let f=o.shape;for(let _ in f)m.properties[_]=this.process(f[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(f)),y=new Set([...g].filter(_=>{let x=o.shape[_]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));y.size>0&&(m.required=Array.from(y)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=h;m.anyOf=o.options.map((f,g)=>this.process(f,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let m=h,f=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=x=>"allOf"in x&&Object.keys(x).length===1,_=[...y(f)?f.allOf:[f],...y(g)?g.allOf:[g]];m.allOf=_;break}case"tuple":{let m=h;m.type="array";let f=o.items.map((_,x)=>this.process(_,{...d,path:[...d.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?m.prefixItems=f:m.items=f,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?m.items=_:m.additionalItems=_}o.rest&&(m.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof y=="number"&&(m.maxItems=y);break}case"record":{let m=h;m.type="object",m.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=h,f=Wi(o.entries);f.every(g=>typeof g=="number")&&(m.type="number"),f.every(g=>typeof g=="string")&&(m.type="string"),m.enum=f;break}case"literal":{let m=h,f=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");f.push(Number(g))}else f.push(g);if(f.length!==0)if(f.length===1){let g=f[0];m.type=g===null?"null":typeof g,m.const=g}else f.every(g=>typeof g=="number")&&(m.type="number"),f.every(g=>typeof g=="string")&&(m.type="string"),f.every(g=>typeof g=="boolean")&&(m.type="string"),f.every(g=>g===null)&&(m.type="null"),m.enum=f;break}case"file":{let m=h,f={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(f.minLength=g),y!==void 0&&(f.maxLength=y),_?_.length===1?(f.contentMediaType=_[0],Object.assign(m,f)):m.anyOf=_.map(x=>({...f,contentMediaType:x})):Object.assign(m,f);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,d);h.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let m=h;m.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=h,f=e._zod.pattern;if(!f)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=f.source;break}case"pipe":{let m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,d),a.ref=m;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,d),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Ye(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let f=n.external.registry.get(l[0])?.id,g=n.external.uri??(_=>_);if(f)return{ref:g(f)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===o)return{ref:"#"};let h=`#/${d}/`,m=l[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:h+m}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:p,defId:h}=s(l);d.def={...d.schema},h&&(d.defId=h);let m=d.schema;for(let f in m)delete m[f];m.$ref=p};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
474
|
-
|
|
475
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let h=n.external.registry.get(l[0])?.id;if(e!==l[0]&&h){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let p=this.seen.get(l),h=p.def??p.schema,m={...h};if(p.ref===null)return;let f=p.ref;if(p.ref=null,f){a(f,d);let g=this.seen.get(f).schema;g.$ref&&d.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(g)):(Object.assign(h,g),Object.assign(h,m))}p.isParent||this.override({zodSchema:l,jsonSchema:h,path:p.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var Nk=S(()=>{});var kt=S(()=>{Os();Pm();vm();Sk();ou();Nm();Lr();nu();lu();wf();Am();Ik();Ok();Ak();Nk()});var ph=S(()=>{kt()});function mh(t,e){let r={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new c1(r)}var a1,c1,Dk=S(()=>{kt();kt();ph();a1=T("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ve.init(t,e),t.def=e,t.parse=(r,n)=>km(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Io(t,r,n),t.parseAsync=async(r,n)=>Em(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ao(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Ht(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),c1=T("ZodMiniObject",(t,e)=>{cu.init(t,e),a1.init(t,e),ue.defineLazy(t,"shape",()=>e.shape)})});var Mk=S(()=>{});var jk=S(()=>{});var Lk=S(()=>{});var zk=S(()=>{kt();ph();Dk();Mk();kt();lu();jk();Lk()});var Fk=S(()=>{zk()});var fh=S(()=>{Fk()});function nr(t){return!!t._zod}function Mo(t){let e=Object.values(t);if(e.length===0)return mh({});let r=e.every(nr),n=e.every(o=>!nr(o));if(r)return mh(t);if(n)return cm(t);throw new Error("Mixed Zod versions detected in object shape.")}function Nn(t,e){return nr(t)?Io(t,e):t.safeParse(e)}async function _u(t,e){return nr(t)?await Ao(t,e):await t.safeParseAsync(e)}function Dn(t){if(!t)return;let e;if(nr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ds(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Mo(t)}}if(nr(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function xu(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Uk(t){return t.description}function Bk(t){if(nr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function bu(t){if(nr(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var oa=S(()=>{qi();fh()});var hh=S(()=>{kt()});var sa={};we(sa,{ZodISODate:()=>qk,ZodISODateTime:()=>Zk,ZodISODuration:()=>Wk,ZodISOTime:()=>Vk,date:()=>yh,datetime:()=>gh,duration:()=>xh,time:()=>_h});function gh(t){return $k(Zk,t)}function yh(t){return Tk(qk,t)}function _h(t){return Pk(Vk,t)}function xh(t){return Rk(Wk,t)}var Zk,qk,Vk,Wk,bh=S(()=>{kt();vh();Zk=T("ZodISODateTime",(t,e)=>{yk.init(t,e),Me.init(t,e)});qk=T("ZodISODate",(t,e)=>{_k.init(t,e),Me.init(t,e)});Vk=T("ZodISOTime",(t,e)=>{xk.init(t,e),Me.init(t,e)});Wk=T("ZodISODuration",(t,e)=>{bk.init(t,e),Me.init(t,e)})});var Kk,s6,ia,Sh=S(()=>{kt();kt();Kk=(t,e)=>{tu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>bm(t,r)},flatten:{value:r=>xm(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},s6=T("ZodError",Kk),ia=T("ZodError",Kk,{Parent:Error})});var Gk,Jk,Xk,Yk,kh=S(()=>{kt();Sh();Gk=Sm(ia),Jk=wm(ia),Xk=$m(ia),Yk=Tm(ia)});function $(t){return Ef(_1,t)}function ye(t){return Wf(n0,t)}function e0(t){return Kf(M1,t)}function ot(t){return Gf(j1,t)}function o0(t){return Jf(L1,t)}function je(){return Xf(z1)}function H1(t){return Yf(F1,t)}function le(t,e){return Ck(U1,t,e)}function H(t,e){let r={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new s0(r)}function wt(t,e){return new s0({type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},catchall:je(),...ue.normalizeParams(e)})}function Ie(t,e){return new i0({type:"union",options:t,...ue.normalizeParams(e)})}function $h(t,e,r){return new B1({type:"union",options:e,discriminator:t,...ue.normalizeParams(r)})}function Su(t,e){return new Z1({type:"intersection",left:t,right:e})}function Re(t,e,r){return new q1({type:"record",keyType:t,valueType:e,...ue.normalizeParams(r)})}function At(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new wh({type:"enum",entries:r,...ue.normalizeParams(e)})}function q(t,e){return new V1({type:"literal",values:Array.isArray(t)?t:[t],...ue.normalizeParams(e)})}function a0(t){return new W1({type:"transform",transform:t})}function Le(t){return new c0({type:"optional",innerType:t})}function t0(t){return new K1({type:"nullable",innerType:t})}function J1(t,e){return new G1({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Y1(t,e){return new X1({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Q1(t,e){return new u0({type:"nonoptional",innerType:t,...ue.normalizeParams(e)})}function tM(t,e){return new eM({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Eh(t,e){return new rM({type:"pipe",in:t,out:e})}function oM(t){return new nM({type:"readonly",innerType:t})}function sM(t){let e=new it({check:"custom"});return e._zod.check=t,e}function d0(t,e){return uh(l0,t??(()=>!0),e)}function iM(t,e={}){return lh(l0,t,e)}function aM(t){let e=sM(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ue.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ue.issue(o))}},t(r.value,r)));return e}function Th(t,e){return Eh(a0(t),e)}var Ue,r0,_1,Me,x1,Qk,vu,b1,v1,S1,k1,w1,E1,$1,T1,P1,R1,C1,O1,I1,A1,N1,D1,n0,M1,j1,L1,z1,F1,U1,s0,i0,B1,Z1,q1,wh,V1,W1,c0,K1,G1,X1,u0,eM,rM,nM,l0,vh=S(()=>{kt();kt();hh();bh();kh();Ue=T("ZodType",(t,e)=>(ve.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Ht(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Gk(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Xk(t,r,n),t.parseAsync=async(r,n)=>Jk(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Yk(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(iM(r,n)),t.superRefine=r=>t.check(aM(r)),t.overwrite=r=>t.check(No(r)),t.optional=()=>Le(t),t.nullable=()=>t0(t),t.nullish=()=>Le(t0(t)),t.nonoptional=r=>Q1(t,r),t.array=()=>le(t),t.or=r=>Ie([t,r]),t.and=r=>Su(t,r),t.transform=r=>Eh(t,a0(r)),t.default=r=>J1(t,r),t.prefault=r=>Y1(t,r),t.catch=r=>tM(t,r),t.pipe=r=>Eh(t,r),t.readonly=()=>oM(t),t.describe=r=>{let n=t.clone();return An.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return An.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return An.get(t);let n=t.clone();return An.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),r0=T("_ZodString",(t,e)=>{ea.init(t,e),Ue.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Qf(...n)),t.includes=(...n)=>t.check(rh(...n)),t.startsWith=(...n)=>t.check(nh(...n)),t.endsWith=(...n)=>t.check(oh(...n)),t.min=(...n)=>t.check(Ns(...n)),t.max=(...n)=>t.check(hu(...n)),t.length=(...n)=>t.check(gu(...n)),t.nonempty=(...n)=>t.check(Ns(1,...n)),t.lowercase=n=>t.check(eh(n)),t.uppercase=n=>t.check(th(n)),t.trim=()=>t.check(ih()),t.normalize=(...n)=>t.check(sh(...n)),t.toLowerCase=()=>t.check(ah()),t.toUpperCase=()=>t.check(ch())}),_1=T("ZodString",(t,e)=>{ea.init(t,e),r0.init(t,e),t.email=r=>t.check($f(x1,r)),t.url=r=>t.check(Of(b1,r)),t.jwt=r=>t.check(Vf(D1,r)),t.emoji=r=>t.check(If(v1,r)),t.guid=r=>t.check(du(Qk,r)),t.uuid=r=>t.check(Tf(vu,r)),t.uuidv4=r=>t.check(Pf(vu,r)),t.uuidv6=r=>t.check(Rf(vu,r)),t.uuidv7=r=>t.check(Cf(vu,r)),t.nanoid=r=>t.check(Af(S1,r)),t.guid=r=>t.check(du(Qk,r)),t.cuid=r=>t.check(Nf(k1,r)),t.cuid2=r=>t.check(Df(w1,r)),t.ulid=r=>t.check(Mf(E1,r)),t.base64=r=>t.check(Bf(I1,r)),t.base64url=r=>t.check(Zf(A1,r)),t.xid=r=>t.check(jf($1,r)),t.ksuid=r=>t.check(Lf(T1,r)),t.ipv4=r=>t.check(zf(P1,r)),t.ipv6=r=>t.check(Ff(R1,r)),t.cidrv4=r=>t.check(Hf(C1,r)),t.cidrv6=r=>t.check(Uf(O1,r)),t.e164=r=>t.check(qf(N1,r)),t.datetime=r=>t.check(gh(r)),t.date=r=>t.check(yh(r)),t.time=r=>t.check(_h(r)),t.duration=r=>t.check(xh(r))});Me=T("ZodStringFormat",(t,e)=>{Pe.init(t,e),r0.init(t,e)}),x1=T("ZodEmail",(t,e)=>{Lm.init(t,e),Me.init(t,e)}),Qk=T("ZodGUID",(t,e)=>{Mm.init(t,e),Me.init(t,e)}),vu=T("ZodUUID",(t,e)=>{jm.init(t,e),Me.init(t,e)}),b1=T("ZodURL",(t,e)=>{zm.init(t,e),Me.init(t,e)}),v1=T("ZodEmoji",(t,e)=>{Fm.init(t,e),Me.init(t,e)}),S1=T("ZodNanoID",(t,e)=>{Hm.init(t,e),Me.init(t,e)}),k1=T("ZodCUID",(t,e)=>{Um.init(t,e),Me.init(t,e)}),w1=T("ZodCUID2",(t,e)=>{Bm.init(t,e),Me.init(t,e)}),E1=T("ZodULID",(t,e)=>{Zm.init(t,e),Me.init(t,e)}),$1=T("ZodXID",(t,e)=>{qm.init(t,e),Me.init(t,e)}),T1=T("ZodKSUID",(t,e)=>{Vm.init(t,e),Me.init(t,e)}),P1=T("ZodIPv4",(t,e)=>{Wm.init(t,e),Me.init(t,e)}),R1=T("ZodIPv6",(t,e)=>{Km.init(t,e),Me.init(t,e)}),C1=T("ZodCIDRv4",(t,e)=>{Gm.init(t,e),Me.init(t,e)}),O1=T("ZodCIDRv6",(t,e)=>{Jm.init(t,e),Me.init(t,e)}),I1=T("ZodBase64",(t,e)=>{Xm.init(t,e),Me.init(t,e)}),A1=T("ZodBase64URL",(t,e)=>{Ym.init(t,e),Me.init(t,e)}),N1=T("ZodE164",(t,e)=>{Qm.init(t,e),Me.init(t,e)}),D1=T("ZodJWT",(t,e)=>{ef.init(t,e),Me.init(t,e)}),n0=T("ZodNumber",(t,e)=>{au.init(t,e),Ue.init(t,e),t.gt=(n,o)=>t.check(mu(n,o)),t.gte=(n,o)=>t.check(na(n,o)),t.min=(n,o)=>t.check(na(n,o)),t.lt=(n,o)=>t.check(pu(n,o)),t.lte=(n,o)=>t.check(ra(n,o)),t.max=(n,o)=>t.check(ra(n,o)),t.int=n=>t.check(e0(n)),t.safe=n=>t.check(e0(n)),t.positive=n=>t.check(mu(0,n)),t.nonnegative=n=>t.check(na(0,n)),t.negative=n=>t.check(pu(0,n)),t.nonpositive=n=>t.check(ra(0,n)),t.multipleOf=(n,o)=>t.check(fu(n,o)),t.step=(n,o)=>t.check(fu(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});M1=T("ZodNumberFormat",(t,e)=>{tf.init(t,e),n0.init(t,e)});j1=T("ZodBoolean",(t,e)=>{rf.init(t,e),Ue.init(t,e)});L1=T("ZodNull",(t,e)=>{nf.init(t,e),Ue.init(t,e)});z1=T("ZodUnknown",(t,e)=>{of.init(t,e),Ue.init(t,e)});F1=T("ZodNever",(t,e)=>{sf.init(t,e),Ue.init(t,e)});U1=T("ZodArray",(t,e)=>{af.init(t,e),Ue.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Ns(r,n)),t.nonempty=r=>t.check(Ns(1,r)),t.max=(r,n)=>t.check(hu(r,n)),t.length=(r,n)=>t.check(gu(r,n)),t.unwrap=()=>t.element});s0=T("ZodObject",(t,e)=>{cu.init(t,e),Ue.init(t,e),ue.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>At(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:je()}),t.loose=()=>t.clone({...t._zod.def,catchall:je()}),t.strict=()=>t.clone({...t._zod.def,catchall:H1()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ue.extend(t,r),t.merge=r=>ue.merge(t,r),t.pick=r=>ue.pick(t,r),t.omit=r=>ue.omit(t,r),t.partial=(...r)=>ue.partial(c0,t,r[0]),t.required=(...r)=>ue.required(u0,t,r[0])});i0=T("ZodUnion",(t,e)=>{uu.init(t,e),Ue.init(t,e),t.options=e.options});B1=T("ZodDiscriminatedUnion",(t,e)=>{i0.init(t,e),cf.init(t,e)});Z1=T("ZodIntersection",(t,e)=>{uf.init(t,e),Ue.init(t,e)});q1=T("ZodRecord",(t,e)=>{lf.init(t,e),Ue.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});wh=T("ZodEnum",(t,e)=>{df.init(t,e),Ue.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new wh({...e,checks:[],...ue.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new wh({...e,checks:[],...ue.normalizeParams(o),entries:s})}});V1=T("ZodLiteral",(t,e)=>{pf.init(t,e),Ue.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});W1=T("ZodTransform",(t,e)=>{mf.init(t,e),Ue.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ue.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ue.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});c0=T("ZodOptional",(t,e)=>{ff.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});K1=T("ZodNullable",(t,e)=>{hf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});G1=T("ZodDefault",(t,e)=>{gf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});X1=T("ZodPrefault",(t,e)=>{yf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});u0=T("ZodNonOptional",(t,e)=>{_f.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});eM=T("ZodCatch",(t,e)=>{xf.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});rM=T("ZodPipe",(t,e)=>{bf.init(t,e),Ue.init(t,e),t.in=e.in,t.out=e.out});nM=T("ZodReadonly",(t,e)=>{vf.init(t,e),Ue.init(t,e)});l0=T("ZodCustom",(t,e)=>{Sf.init(t,e),Ue.init(t,e)})});var p0=S(()=>{});var m0=S(()=>{});var f0=S(()=>{kt();vh();hh();Sh();kh();p0();kt();wk();lu();bh();m0();Ft(kk())});var h0=S(()=>{f0()});var g0=S(()=>{h0()});function A0(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function N0(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Rh,y0,Mn,wu,Qe,_0,x0,v6,lM,dM,Ch,Ut,aa,b0,at,or,sr,ct,Eu,v0,Oh,S0,k0,Ih,ca,G,Ah,w0,E0,S6,$u,pM,Tu,mM,ua,Ms,$0,fM,hM,gM,yM,_M,xM,Nh,bM,vM,Dh,Pu,SM,kM,Ru,wM,la,da,EM,pa,js,$M,ma,Cu,Ou,Iu,k6,Au,Nu,Du,T0,P0,R0,Mh,C0,fa,Ls,O0,TM,zs,PM,Fs,RM,jh,CM,Mu,OM,IM,AM,NM,DM,MM,jM,LM,zM,FM,Hs,HM,UM,ju,Lh,zh,Fh,BM,ZM,qM,Hh,VM,WM,KM,GM,JM,I0,Us,XM,Lu,w6,YM,Bs,QM,E6,ha,ej,Uh,tj,rj,nj,oj,sj,ij,aj,ku,cj,uj,lj,ga,Bh,dj,pj,mj,fj,hj,gj,yj,_j,xj,bj,vj,Sj,kj,wj,Ej,$j,Tj,Pj,Zs,Rj,Cj,Oj,zu,Ij,Aj,Nj,Zh,Dj,$6,T6,P6,R6,C6,O6,Z,Ph,jo=S(()=>{g0();Rh="2025-11-25",y0=[Rh,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Mn="io.modelcontextprotocol/related-task",wu="2.0",Qe=d0(t=>t!==null&&(typeof t=="object"||typeof t=="function")),_0=Ie([$(),ye().int()]),x0=$(),v6=wt({ttl:ye().optional(),pollInterval:ye().optional()}),lM=H({ttl:ye().optional()}),dM=H({taskId:$()}),Ch=wt({progressToken:_0.optional(),[Mn]:dM.optional()}),Ut=H({_meta:Ch.optional()}),aa=Ut.extend({task:lM.optional()}),b0=t=>aa.safeParse(t).success,at=H({method:$(),params:Ut.loose().optional()}),or=H({_meta:Ch.optional()}),sr=H({method:$(),params:or.loose().optional()}),ct=wt({_meta:Ch.optional()}),Eu=Ie([$(),ye().int()]),v0=H({jsonrpc:q(wu),id:Eu,...at.shape}).strict(),Oh=t=>v0.safeParse(t).success,S0=H({jsonrpc:q(wu),...sr.shape}).strict(),k0=t=>S0.safeParse(t).success,Ih=H({jsonrpc:q(wu),id:Eu,result:ct}).strict(),ca=t=>Ih.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(G||(G={}));Ah=H({jsonrpc:q(wu),id:Eu.optional(),error:H({code:ye().int(),message:$(),data:je().optional()})}).strict(),w0=t=>Ah.safeParse(t).success,E0=Ie([v0,S0,Ih,Ah]),S6=Ie([Ih,Ah]),$u=ct.strict(),pM=or.extend({requestId:Eu.optional(),reason:$().optional()}),Tu=sr.extend({method:q("notifications/cancelled"),params:pM}),mM=H({src:$(),mimeType:$().optional(),sizes:le($()).optional(),theme:At(["light","dark"]).optional()}),ua=H({icons:le(mM).optional()}),Ms=H({name:$(),title:$().optional()}),$0=Ms.extend({...Ms.shape,...ua.shape,version:$(),websiteUrl:$().optional(),description:$().optional()}),fM=Su(H({applyDefaults:ot().optional()}),Re($(),je())),hM=Th(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Su(H({form:fM.optional(),url:Qe.optional()}),Re($(),je()).optional())),gM=wt({list:Qe.optional(),cancel:Qe.optional(),requests:wt({sampling:wt({createMessage:Qe.optional()}).optional(),elicitation:wt({create:Qe.optional()}).optional()}).optional()}),yM=wt({list:Qe.optional(),cancel:Qe.optional(),requests:wt({tools:wt({call:Qe.optional()}).optional()}).optional()}),_M=H({experimental:Re($(),Qe).optional(),sampling:H({context:Qe.optional(),tools:Qe.optional()}).optional(),elicitation:hM.optional(),roots:H({listChanged:ot().optional()}).optional(),tasks:gM.optional(),extensions:Re($(),Qe).optional()}),xM=Ut.extend({protocolVersion:$(),capabilities:_M,clientInfo:$0}),Nh=at.extend({method:q("initialize"),params:xM}),bM=H({experimental:Re($(),Qe).optional(),logging:Qe.optional(),completions:Qe.optional(),prompts:H({listChanged:ot().optional()}).optional(),resources:H({subscribe:ot().optional(),listChanged:ot().optional()}).optional(),tools:H({listChanged:ot().optional()}).optional(),tasks:yM.optional(),extensions:Re($(),Qe).optional()}),vM=ct.extend({protocolVersion:$(),capabilities:bM,serverInfo:$0,instructions:$().optional()}),Dh=sr.extend({method:q("notifications/initialized"),params:or.optional()}),Pu=at.extend({method:q("ping"),params:Ut.optional()}),SM=H({progress:ye(),total:Le(ye()),message:Le($())}),kM=H({...or.shape,...SM.shape,progressToken:_0}),Ru=sr.extend({method:q("notifications/progress"),params:kM}),wM=Ut.extend({cursor:x0.optional()}),la=at.extend({params:wM.optional()}),da=ct.extend({nextCursor:x0.optional()}),EM=At(["working","input_required","completed","failed","cancelled"]),pa=H({taskId:$(),status:EM,ttl:Ie([ye(),o0()]),createdAt:$(),lastUpdatedAt:$(),pollInterval:Le(ye()),statusMessage:Le($())}),js=ct.extend({task:pa}),$M=or.merge(pa),ma=sr.extend({method:q("notifications/tasks/status"),params:$M}),Cu=at.extend({method:q("tasks/get"),params:Ut.extend({taskId:$()})}),Ou=ct.merge(pa),Iu=at.extend({method:q("tasks/result"),params:Ut.extend({taskId:$()})}),k6=ct.loose(),Au=la.extend({method:q("tasks/list")}),Nu=da.extend({tasks:le(pa)}),Du=at.extend({method:q("tasks/cancel"),params:Ut.extend({taskId:$()})}),T0=ct.merge(pa),P0=H({uri:$(),mimeType:Le($()),_meta:Re($(),je()).optional()}),R0=P0.extend({text:$()}),Mh=$().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),C0=P0.extend({blob:Mh}),fa=At(["user","assistant"]),Ls=H({audience:le(fa).optional(),priority:ye().min(0).max(1).optional(),lastModified:sa.datetime({offset:!0}).optional()}),O0=H({...Ms.shape,...ua.shape,uri:$(),description:Le($()),mimeType:Le($()),size:Le(ye()),annotations:Ls.optional(),_meta:Le(wt({}))}),TM=H({...Ms.shape,...ua.shape,uriTemplate:$(),description:Le($()),mimeType:Le($()),annotations:Ls.optional(),_meta:Le(wt({}))}),zs=la.extend({method:q("resources/list")}),PM=da.extend({resources:le(O0)}),Fs=la.extend({method:q("resources/templates/list")}),RM=da.extend({resourceTemplates:le(TM)}),jh=Ut.extend({uri:$()}),CM=jh,Mu=at.extend({method:q("resources/read"),params:CM}),OM=ct.extend({contents:le(Ie([R0,C0]))}),IM=sr.extend({method:q("notifications/resources/list_changed"),params:or.optional()}),AM=jh,NM=at.extend({method:q("resources/subscribe"),params:AM}),DM=jh,MM=at.extend({method:q("resources/unsubscribe"),params:DM}),jM=or.extend({uri:$()}),LM=sr.extend({method:q("notifications/resources/updated"),params:jM}),zM=H({name:$(),description:Le($()),required:Le(ot())}),FM=H({...Ms.shape,...ua.shape,description:Le($()),arguments:Le(le(zM)),_meta:Le(wt({}))}),Hs=la.extend({method:q("prompts/list")}),HM=da.extend({prompts:le(FM)}),UM=Ut.extend({name:$(),arguments:Re($(),$()).optional()}),ju=at.extend({method:q("prompts/get"),params:UM}),Lh=H({type:q("text"),text:$(),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),zh=H({type:q("image"),data:Mh,mimeType:$(),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),Fh=H({type:q("audio"),data:Mh,mimeType:$(),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),BM=H({type:q("tool_use"),name:$(),id:$(),input:Re($(),je()),_meta:Re($(),je()).optional()}),ZM=H({type:q("resource"),resource:Ie([R0,C0]),annotations:Ls.optional(),_meta:Re($(),je()).optional()}),qM=O0.extend({type:q("resource_link")}),Hh=Ie([Lh,zh,Fh,qM,ZM]),VM=H({role:fa,content:Hh}),WM=ct.extend({description:$().optional(),messages:le(VM)}),KM=sr.extend({method:q("notifications/prompts/list_changed"),params:or.optional()}),GM=H({title:$().optional(),readOnlyHint:ot().optional(),destructiveHint:ot().optional(),idempotentHint:ot().optional(),openWorldHint:ot().optional()}),JM=H({taskSupport:At(["required","optional","forbidden"]).optional()}),I0=H({...Ms.shape,...ua.shape,description:$().optional(),inputSchema:H({type:q("object"),properties:Re($(),Qe).optional(),required:le($()).optional()}).catchall(je()),outputSchema:H({type:q("object"),properties:Re($(),Qe).optional(),required:le($()).optional()}).catchall(je()).optional(),annotations:GM.optional(),execution:JM.optional(),_meta:Re($(),je()).optional()}),Us=la.extend({method:q("tools/list")}),XM=da.extend({tools:le(I0)}),Lu=ct.extend({content:le(Hh).default([]),structuredContent:Re($(),je()).optional(),isError:ot().optional()}),w6=Lu.or(ct.extend({toolResult:je()})),YM=aa.extend({name:$(),arguments:Re($(),je()).optional()}),Bs=at.extend({method:q("tools/call"),params:YM}),QM=sr.extend({method:q("notifications/tools/list_changed"),params:or.optional()}),E6=H({autoRefresh:ot().default(!0),debounceMs:ye().int().nonnegative().default(300)}),ha=At(["debug","info","notice","warning","error","critical","alert","emergency"]),ej=Ut.extend({level:ha}),Uh=at.extend({method:q("logging/setLevel"),params:ej}),tj=or.extend({level:ha,logger:$().optional(),data:je()}),rj=sr.extend({method:q("notifications/message"),params:tj}),nj=H({name:$().optional()}),oj=H({hints:le(nj).optional(),costPriority:ye().min(0).max(1).optional(),speedPriority:ye().min(0).max(1).optional(),intelligencePriority:ye().min(0).max(1).optional()}),sj=H({mode:At(["auto","required","none"]).optional()}),ij=H({type:q("tool_result"),toolUseId:$().describe("The unique identifier for the corresponding tool call."),content:le(Hh).default([]),structuredContent:H({}).loose().optional(),isError:ot().optional(),_meta:Re($(),je()).optional()}),aj=$h("type",[Lh,zh,Fh]),ku=$h("type",[Lh,zh,Fh,BM,ij]),cj=H({role:fa,content:Ie([ku,le(ku)]),_meta:Re($(),je()).optional()}),uj=aa.extend({messages:le(cj),modelPreferences:oj.optional(),systemPrompt:$().optional(),includeContext:At(["none","thisServer","allServers"]).optional(),temperature:ye().optional(),maxTokens:ye().int(),stopSequences:le($()).optional(),metadata:Qe.optional(),tools:le(I0).optional(),toolChoice:sj.optional()}),lj=at.extend({method:q("sampling/createMessage"),params:uj}),ga=ct.extend({model:$(),stopReason:Le(At(["endTurn","stopSequence","maxTokens"]).or($())),role:fa,content:aj}),Bh=ct.extend({model:$(),stopReason:Le(At(["endTurn","stopSequence","maxTokens","toolUse"]).or($())),role:fa,content:Ie([ku,le(ku)])}),dj=H({type:q("boolean"),title:$().optional(),description:$().optional(),default:ot().optional()}),pj=H({type:q("string"),title:$().optional(),description:$().optional(),minLength:ye().optional(),maxLength:ye().optional(),format:At(["email","uri","date","date-time"]).optional(),default:$().optional()}),mj=H({type:At(["number","integer"]),title:$().optional(),description:$().optional(),minimum:ye().optional(),maximum:ye().optional(),default:ye().optional()}),fj=H({type:q("string"),title:$().optional(),description:$().optional(),enum:le($()),default:$().optional()}),hj=H({type:q("string"),title:$().optional(),description:$().optional(),oneOf:le(H({const:$(),title:$()})),default:$().optional()}),gj=H({type:q("string"),title:$().optional(),description:$().optional(),enum:le($()),enumNames:le($()).optional(),default:$().optional()}),yj=Ie([fj,hj]),_j=H({type:q("array"),title:$().optional(),description:$().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:H({type:q("string"),enum:le($())}),default:le($()).optional()}),xj=H({type:q("array"),title:$().optional(),description:$().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:H({anyOf:le(H({const:$(),title:$()}))}),default:le($()).optional()}),bj=Ie([_j,xj]),vj=Ie([gj,yj,bj]),Sj=Ie([vj,dj,pj,mj]),kj=aa.extend({mode:q("form").optional(),message:$(),requestedSchema:H({type:q("object"),properties:Re($(),Sj),required:le($()).optional()})}),wj=aa.extend({mode:q("url"),message:$(),elicitationId:$(),url:$().url()}),Ej=Ie([kj,wj]),$j=at.extend({method:q("elicitation/create"),params:Ej}),Tj=or.extend({elicitationId:$()}),Pj=sr.extend({method:q("notifications/elicitation/complete"),params:Tj}),Zs=ct.extend({action:At(["accept","decline","cancel"]),content:Th(t=>t===null?void 0:t,Re($(),Ie([$(),ye(),ot(),le($())])).optional())}),Rj=H({type:q("ref/resource"),uri:$()}),Cj=H({type:q("ref/prompt"),name:$()}),Oj=Ut.extend({ref:Ie([Cj,Rj]),argument:H({name:$(),value:$()}),context:H({arguments:Re($(),$()).optional()}).optional()}),zu=at.extend({method:q("completion/complete"),params:Oj});Ij=ct.extend({completion:wt({values:le($()).max(100),total:Le(ye().int()),hasMore:Le(ot())})}),Aj=H({uri:$().startsWith("file://"),name:$().optional(),_meta:Re($(),je()).optional()}),Nj=at.extend({method:q("roots/list"),params:Ut.optional()}),Zh=ct.extend({roots:le(Aj)}),Dj=sr.extend({method:q("notifications/roots/list_changed"),params:or.optional()}),$6=Ie([Pu,Nh,zu,Uh,ju,Hs,zs,Fs,Mu,NM,MM,Bs,Us,Cu,Iu,Au,Du]),T6=Ie([Tu,Ru,Dh,Dj,ma]),P6=Ie([$u,ga,Bh,Zs,Zh,Ou,Nu,js]),R6=Ie([Pu,lj,$j,Nj,Cu,Iu,Au,Du]),C6=Ie([Tu,Ru,rj,LM,IM,QM,KM,ma,Pj]),O6=Ie([$u,vM,Ij,WM,HM,PM,RM,OM,Lu,XM,Ou,Nu,js]),Z=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===G.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ph(o.elicitations,r)}return new t(e,r,n)}},Ph=class extends Z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(G.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function jn(t){return t==="completed"||t==="failed"||t==="cancelled"}var D0=S(()=>{});var j0,M0,L0,Fu=S(()=>{j0=Symbol("Let zodToJsonSchema decide on which parser to use"),M0={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},L0=t=>typeof t=="string"?{...M0,name:t}:{...M0,...t}});var z0,qh=S(()=>{Fu();z0=t=>{let e=L0(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Vh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function de(t,e,r,n,o){t[e]=r,Vh(t,e,n,o)}var Ln=S(()=>{});var Hu,Uu=S(()=>{Hu=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function ze(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Hu(e,t.currentPath):e.join("/")}}var ir=S(()=>{Uu()});function F0(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(r.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(r,"minItems",t.exactLength.value,t.exactLength.message,e),de(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Wh=S(()=>{qi();Ln();Ge()});function H0(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var Kh=S(()=>{Ln()});function U0(){return{type:"boolean"}}var Gh=S(()=>{});function Bu(t,e){return Y(t.type._def,e)}var Zu=S(()=>{Ge()});var B0,Jh=S(()=>{Ge();B0=(t,e)=>Y(t.innerType._def,e)});function Xh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Xh(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Mj(t,e)}}var Mj,Yh=S(()=>{Ln();Mj=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":de(r,"minimum",n.value,n.message,e);break;case"max":de(r,"maximum",n.value,n.message,e);break}return r}});function Z0(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var Qh=S(()=>{Ge()});function q0(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):ze(e)}var eg=S(()=>{Ge();ir()});function V0(t){return{type:"string",enum:Array.from(t.values)}}var tg=S(()=>{});function W0(t,e){let r=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(jj(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var jj,rg=S(()=>{Ge();jj=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function K0(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var ng=S(()=>{});function qu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":_r(r,"email",n.message,e);break;case"format:idn-email":_r(r,"idn-email",n.message,e);break;case"pattern:zod":Et(r,yr.email,n.message,e);break}break;case"url":_r(r,"uri",n.message,e);break;case"uuid":_r(r,"uuid",n.message,e);break;case"regex":Et(r,n.regex,n.message,e);break;case"cuid":Et(r,yr.cuid,n.message,e);break;case"cuid2":Et(r,yr.cuid2,n.message,e);break;case"startsWith":Et(r,RegExp(`^${sg(n.value,e)}`),n.message,e);break;case"endsWith":Et(r,RegExp(`${sg(n.value,e)}$`),n.message,e);break;case"datetime":_r(r,"date-time",n.message,e);break;case"date":_r(r,"date",n.message,e);break;case"time":_r(r,"time",n.message,e);break;case"duration":_r(r,"duration",n.message,e);break;case"length":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Et(r,RegExp(sg(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&_r(r,"ipv4",n.message,e),n.version!=="v4"&&_r(r,"ipv6",n.message,e);break}case"base64url":Et(r,yr.base64url,n.message,e);break;case"jwt":Et(r,yr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Et(r,yr.ipv4Cidr,n.message,e),n.version!=="v4"&&Et(r,yr.ipv6Cidr,n.message,e);break}case"emoji":Et(r,yr.emoji(),n.message,e);break;case"ulid":{Et(r,yr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{_r(r,"binary",n.message,e);break}case"contentEncoding:base64":{de(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Et(r,yr.base64,n.message,e);break}}break}case"nanoid":Et(r,yr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function sg(t,e){return e.patternStrategy==="escape"?zj(t):t}function zj(t){let e="";for(let r=0;r<t.length;r++)Lj.has(t[r])||(e+="\\"),e+=t[r];return e}function _r(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):de(t,"format",e,r,n)}function Et(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:G0(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):de(t,"pattern",G0(e,n),r,n)}function G0(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
476
|
-
]))`;continue}else if(
|
|
477
|
-
]))`;continue}}if(
|
|
478
|
-
`:`[${
|
|
479
|
-
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var og,yr,Lj,Vu=S(()=>{Ln();yr={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:()=>(og===void 0&&(og=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),og),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-_]*$/};Lj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Wu(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ze(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=qu(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Bu(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Ku=S(()=>{qi();Ge();Vu();Zu();ir()});function J0(t,e){if(e.mapStrategy==="record")return Wu(t,e);let r=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ze(e),n=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ze(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var ig=S(()=>{Ge();Ku();ir()});function X0(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var ag=S(()=>{});function Y0(t){return t.target==="openAi"?void 0:{not:ze({...t,currentPath:[...t.currentPath,"not"]})}}var cg=S(()=>{ir()});function Q0(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ug=S(()=>{});function tw(t,e){if(e.target==="openApi3")return ew(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ya&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ya[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return ew(t,e)}var ya,ew,Gu=S(()=>{Ge();ya={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};ew=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Y(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function rw(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ya[t.innerType._def.typeName],nullable:!0}:{type:[ya[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var lg=S(()=>{Ge();Gu()});function nw(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Vh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var dg=S(()=>{Ln()});function ow(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=Hj(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=Y(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=Fj(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Fj(t,e){if(t.catchall._def.typeName!=="ZodNever")return Y(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Hj(t){try{return t.isOptional()}catch{return!0}}var pg=S(()=>{Ge()});var sw,mg=S(()=>{Ge();ir();sw=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ze(e)},r]}:ze(e)}});var iw,fg=S(()=>{Ge();iw=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let r=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function aw(t,e){return Y(t.type._def,e)}var hg=S(()=>{Ge()});function cw(t,e){let n={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var gg=S(()=>{Ln();Ge()});function uw(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var yg=S(()=>{Ge()});function lw(t){return{not:ze(t)}}var _g=S(()=>{ir()});function dw(t){return ze(t)}var xg=S(()=>{ir()});var pw,bg=S(()=>{Ge();pw=(t,e)=>Y(t.innerType._def,e)});var mw,vg=S(()=>{qi();ir();Wh();Kh();Gh();Zu();Jh();Yh();Qh();eg();tg();rg();ng();ig();ag();cg();ug();lg();dg();pg();mg();fg();hg();Ku();gg();Vu();yg();_g();Gu();xg();bg();mw=(t,e,r)=>{switch(e){case D.ZodString:return qu(t,r);case D.ZodNumber:return nw(t,r);case D.ZodObject:return ow(t,r);case D.ZodBigInt:return H0(t,r);case D.ZodBoolean:return U0();case D.ZodDate:return Xh(t,r);case D.ZodUndefined:return lw(r);case D.ZodNull:return Q0(r);case D.ZodArray:return F0(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return tw(t,r);case D.ZodIntersection:return W0(t,r);case D.ZodTuple:return uw(t,r);case D.ZodRecord:return Wu(t,r);case D.ZodLiteral:return K0(t,r);case D.ZodEnum:return V0(t);case D.ZodNativeEnum:return X0(t);case D.ZodNullable:return rw(t,r);case D.ZodOptional:return sw(t,r);case D.ZodMap:return J0(t,r);case D.ZodSet:return cw(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return aw(t,r);case D.ZodNaN:case D.ZodNever:return Y0(r);case D.ZodEffects:return q0(t,r);case D.ZodAny:return ze(r);case D.ZodUnknown:return dw(r);case D.ZodDefault:return Z0(t,r);case D.ZodBranded:return Bu(t,r);case D.ZodReadonly:return pw(t,r);case D.ZodCatch:return B0(t,r);case D.ZodPipeline:return iw(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}}});function Y(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==j0)return a}if(n&&!r){let a=Uj(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=mw(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&Bj(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Uj,Bj,Ge=S(()=>{Fu();vg();Uu();ir();Uj=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Hu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ze(e)):e.$refStrategy==="seen"?ze(e):void 0}},Bj=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var fw=S(()=>{});var Sg,kg=S(()=>{Ge();qh();ir();Sg=(t,e)=>{let r=z0(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Y(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ze(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Y(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??ze(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var hw=S(()=>{Fu();qh();Ln();Uu();Ge();fw();ir();Wh();Kh();Gh();Zu();Jh();Yh();Qh();eg();tg();rg();ng();ig();ag();cg();ug();lg();dg();pg();mg();fg();hg();bg();Ku();gg();Vu();yg();_g();Gu();xg();vg();kg();kg()});function Zj(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function wg(t,e){return nr(t)?dh(t,{target:Zj(e?.target),io:e?.pipeStrategy??"input"}):Sg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Eg(t){let r=Dn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bu(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function $g(t,e){let r=Nn(t,e);if(!r.success)throw r.error;return r.data}var Tg=S(()=>{fh();oa();hw()});function gw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yw(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];gw(i)&&gw(s)?r[o]={...i,...s}:r[o]=s}return r}var qj,Ju,_w=S(()=>{oa();jo();D0();Tg();qj=6e4,Ju=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Tu,r=>{this._oncancel(r)}),this.setNotificationHandler(Ru,r=>{this._onprogress(r)}),this.setRequestHandler(Pu,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Cu,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(G.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Iu,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new Z(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new Z(G.InvalidParams,`Task not found: ${s}`);if(!jn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(jn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Mn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Au,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new Z(G.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Du,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(jn(o.status))throw new Z(G.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new Z(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof Z?o:new Z(G.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),Z.fromError(G.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),ca(s)||w0(s)?this._onresponse(s):Oh(s)?this._onrequest(s,i):k0(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=Z.fromError(G.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Mn]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:G.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=b0(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new Z(G.ConnectionClosed,"Request was cancelled");let h={...p,relatedRequestId:e.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});let m=h.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,h)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:G.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ca(e))n(e);else{let i=new Z(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(ca(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),ca(e))o(e);else{let i=Z.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(G.InternalError,String(i))}}return}let s;try{let i=await this.request(e,js,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Z(G.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},jn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new Z(G.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Z(G.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(G.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=_=>{l(_)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(_){d(_);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Mn]:c}});let m=_=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>this._onerror(new Error(`Failed to send cancellation: ${v}`)));let x=_ instanceof Z?_:new Z(G.RequestTimeout,String(_));l(x)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return l(_);try{let x=Nn(r,_.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let f=n?.timeout??qj,g=()=>m(Z.fromError(G.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(p,f,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=x=>{let v=this._responseHandlers.get(p);v?v(x):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(y,{type:"request",message:h,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(p),l(x)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),l(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ou,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Nu,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},T0,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Mn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Mn]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Mn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Eg(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=$g(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Eg(e);this._notificationHandlers.set(n,o=>{let s=$g(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Oh(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new Z(G.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new Z(G.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new Z(G.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new Z(G.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=ma.parse({method:"notifications/tasks/status",params:a});await this.notification(c),jn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new Z(G.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(jn(a.status))throw new Z(G.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=ma.parse({method:"notifications/tasks/status",params:c});await this.notification(u),jn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var ba=L(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var _a=class{};he._CodeOrName=_a;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Lo=class extends _a{constructor(e){if(super(),!he.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};he.Name=Lo;var ar=class extends _a{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Lo&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=ar;he.nil=new ar("");function xw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Rg(r,e[n]),r.push(t[++n]);return new ar(r)}he._=xw;var Pg=new ar("+");function bw(t,...e){let r=[xa(t[0])],n=0;for(;n<e.length;)r.push(Pg),Rg(r,e[n]),r.push(Pg,xa(t[++n]));return Vj(r),new ar(r)}he.str=bw;function Rg(t,e){e instanceof ar?t.push(...e._items):e instanceof Lo?t.push(e):t.push(Gj(e))}he.addCodeArg=Rg;function Vj(t){let e=1;for(;e<t.length-1;){if(t[e]===Pg){let r=Wj(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Wj(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Lo||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Lo))return`"${t}${e.slice(1)}`}function Kj(t,e){return e.emptyStr()?t:t.emptyStr()?e:bw`${t}${e}`}he.strConcat=Kj;function Gj(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:xa(Array.isArray(t)?t.join(","):t)}function Jj(t){return new ar(xa(t))}he.stringify=Jj;function xa(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=xa;function Xj(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new ar(`.${t}`):xw`[${t}]`}he.getProperty=Xj;function Yj(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new ar(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=Yj;function Qj(t){return new ar(t.toString())}he.regexpCode=Qj});var Ig=L(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.ValueScope=Dt.ValueScopeName=Dt.Scope=Dt.varKinds=Dt.UsedValueState=void 0;var Nt=ba(),Cg=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Xu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Xu||(Dt.UsedValueState=Xu={}));Dt.varKinds={const:new Nt.Name("const"),let:new Nt.Name("let"),var:new Nt.Name("var")};var Yu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Nt.Name?e:this.name(e)}name(e){return new Nt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Dt.Scope=Yu;var Qu=class extends Nt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Nt._)`.${new Nt.Name(r)}[${n}]`}};Dt.ValueScopeName=Qu;var eL=(0,Nt._)`\n`,Og=class extends Yu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?eL:Nt.nil}}get(){return this._scope}name(e){return new Qu(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Nt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Nt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Xu.Started);let l=r(u);if(l){let d=this.opts.es5?Dt.varKinds.var:Dt.varKinds.const;s=(0,Nt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Nt._)`${s}${l}${this.opts._n}`;else throw new Cg(u);c.set(u,Xu.Completed)})}return s}};Dt.ValueScope=Og});var oe=L(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.or=se.and=se.not=se.CodeGen=se.operators=se.varKinds=se.ValueScopeName=se.ValueScope=se.Scope=se.Name=se.regexpCode=se.stringify=se.getProperty=se.nil=se.strConcat=se.str=se._=void 0;var pe=ba(),xr=Ig(),zn=ba();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return zn._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return zn.str}});Object.defineProperty(se,"strConcat",{enumerable:!0,get:function(){return zn.strConcat}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return zn.nil}});Object.defineProperty(se,"getProperty",{enumerable:!0,get:function(){return zn.getProperty}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return zn.stringify}});Object.defineProperty(se,"regexpCode",{enumerable:!0,get:function(){return zn.regexpCode}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return zn.Name}});var nl=Ig();Object.defineProperty(se,"Scope",{enumerable:!0,get:function(){return nl.Scope}});Object.defineProperty(se,"ValueScope",{enumerable:!0,get:function(){return nl.ValueScope}});Object.defineProperty(se,"ValueScopeName",{enumerable:!0,get:function(){return nl.ValueScopeName}});Object.defineProperty(se,"varKinds",{enumerable:!0,get:function(){return nl.varKinds}});se.operators={GT:new pe._Code(">"),GTE:new pe._Code(">="),LT:new pe._Code("<"),LTE:new pe._Code("<="),EQ:new pe._Code("==="),NEQ:new pe._Code("!=="),NOT:new pe._Code("!"),OR:new pe._Code("||"),AND:new pe._Code("&&"),ADD:new pe._Code("+")};var an=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ag=class extends an{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?xr.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Vs(this.rhs,e,r)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},el=class extends an{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Vs(this.rhs,e,r),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return rl(e,this.rhs)}},Ng=class extends el{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Dg=class extends an{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Mg=class extends an{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},jg=class extends an{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Lg=class extends an{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Vs(this.code,e,r),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},va=class extends an{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(tL(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Ho(e,r.names),{})}},cn=class extends va{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},zg=class extends va{},qs=class extends cn{};qs.kind="else";var zo=class t extends cn{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new qs(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(vw(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Vs(this.condition,e,r),this}get names(){let e=super.names;return rl(e,this.condition),this.else&&Ho(e,this.else.names),e}};zo.kind="if";var Fo=class extends cn{};Fo.kind="for";var Fg=class extends Fo{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Vs(this.iteration,e,r),this}get names(){return Ho(super.names,this.iteration.names)}},Hg=class extends Fo{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?xr.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=rl(super.names,this.from);return rl(e,this.to)}},tl=class extends Fo{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Vs(this.iterable,e,r),this}get names(){return Ho(super.names,this.iterable.names)}},Sa=class extends cn{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Sa.kind="func";var ka=class extends va{render(e){return"return "+super.render(e)}};ka.kind="return";var Ug=class extends cn{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Ho(e,this.catch.names),this.finally&&Ho(e,this.finally.names),e}},wa=class extends cn{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};wa.kind="catch";var Ea=class extends cn{render(e){return"finally"+super.render(e)}};Ea.kind="finally";var Bg=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
480
|
-
`:""},this._extScope=e,this._scope=new xr.Scope({parent:e}),this._nodes=[new zg]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Ag(e,s,n)),s}const(e,r,n){return this._def(xr.varKinds.const,e,r,n)}let(e,r,n){return this._def(xr.varKinds.let,e,r,n)}var(e,r,n){return this._def(xr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new el(e,r,n))}add(e,r){return this._leafNode(new Ng(e,se.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new Lg(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,pe.addCodeArg)(r,o));return r.push("}"),new pe._Code(r)}if(e,r,n){if(this._blockNode(new zo(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new zo(e))}else(){return this._elseNode(new qs)}endIf(){return this._endBlockNode(zo,qs)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Fg(e),r)}forRange(e,r,n,o,s=this.opts.es5?xr.varKinds.var:xr.varKinds.let){let i=this._scope.toName(e);return this._for(new Hg(s,i,r,n),()=>o(i))}forOf(e,r,n,o=xr.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof pe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(s,(0,pe._)`${i}[${a}]`),n(s)})}return this._for(new tl("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?xr.varKinds.var:xr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new tl("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Fo)}label(e){return this._leafNode(new Dg(e))}break(e){return this._leafNode(new Mg(e))}return(e){let r=new ka;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ka)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Ug;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new wa(s),r(s)}return n&&(this._currNode=o.finally=new Ea,this.code(n)),this._endBlockNode(wa,Ea)}throw(e){return this._leafNode(new jg(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=pe.nil,n,o){return this._blockNode(new Sa(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Sa)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof zo))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};se.CodeGen=Bg;function Ho(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function rl(t,e){return e instanceof pe._CodeOrName?Ho(t,e.names):t}function Vs(t,e,r){if(t instanceof pe.Name)return n(t);if(!o(t))return t;return new pe._Code(t._items.reduce((s,i)=>(i instanceof pe.Name&&(i=n(i)),i instanceof pe._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof pe._Code&&s._items.some(i=>i instanceof pe.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function tL(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function vw(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${Zg(t)}`}se.not=vw;var rL=Sw(se.operators.AND);function nL(...t){return t.reduce(rL)}se.and=nL;var oL=Sw(se.operators.OR);function sL(...t){return t.reduce(oL)}se.or=sL;function Sw(t){return(e,r)=>e===pe.nil?r:r===pe.nil?e:(0,pe._)`${Zg(e)} ${t} ${Zg(r)}`}function Zg(t){return t instanceof pe.Name?t:(0,pe._)`(${t})`}});var me=L(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.checkStrictMode=ae.getErrorPath=ae.Type=ae.useFunc=ae.setEvaluated=ae.evaluatedPropsToName=ae.mergeEvaluated=ae.eachItem=ae.unescapeJsonPointer=ae.escapeJsonPointer=ae.escapeFragment=ae.unescapeFragment=ae.schemaRefOrVal=ae.schemaHasRulesButRef=ae.schemaHasRules=ae.checkUnknownRules=ae.alwaysValidSchema=ae.toHash=void 0;var Ee=oe(),iL=ba();function aL(t){let e={};for(let r of t)e[r]=!0;return e}ae.toHash=aL;function cL(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Ew(t,e),!$w(e,t.self.RULES.all))}ae.alwaysValidSchema=cL;function Ew(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Rw(t,`unknown keyword: "${s}"`)}ae.checkUnknownRules=Ew;function $w(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ae.schemaHasRules=$w;function uL(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ae.schemaHasRulesButRef=uL;function lL({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ee._)`${r}`}return(0,Ee._)`${t}${e}${(0,Ee.getProperty)(n)}`}ae.schemaRefOrVal=lL;function dL(t){return Tw(decodeURIComponent(t))}ae.unescapeFragment=dL;function pL(t){return encodeURIComponent(Vg(t))}ae.escapeFragment=pL;function Vg(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ae.escapeJsonPointer=Vg;function Tw(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ae.unescapeJsonPointer=Tw;function mL(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ae.eachItem=mL;function kw({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ee.Name?(s instanceof Ee.Name?t(o,s,i):e(o,s,i),i):s instanceof Ee.Name?(e(o,i,s),s):r(s,i);return a===Ee.Name&&!(c instanceof Ee.Name)?n(o,c):c}}ae.mergeEvaluated={props:kw({mergeNames:(t,e,r)=>t.if((0,Ee._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ee._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ee._)`${r} || {}`).code((0,Ee._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ee._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ee._)`${r} || {}`),Wg(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Pw}),items:kw({mergeNames:(t,e,r)=>t.if((0,Ee._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ee._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ee._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ee._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Pw(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ee._)`{}`);return e!==void 0&&Wg(t,r,e),r}ae.evaluatedPropsToName=Pw;function Wg(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ee._)`${e}${(0,Ee.getProperty)(n)}`,!0))}ae.setEvaluated=Wg;var ww={};function fL(t,e){return t.scopeValue("func",{ref:e,code:ww[e.code]||(ww[e.code]=new iL._Code(e.code))})}ae.useFunc=fL;var qg;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(qg||(ae.Type=qg={}));function hL(t,e,r){if(t instanceof Ee.Name){let n=e===qg.Num;return r?n?(0,Ee._)`"[" + ${t} + "]"`:(0,Ee._)`"['" + ${t} + "']"`:n?(0,Ee._)`"/" + ${t}`:(0,Ee._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ee.getProperty)(t).toString():"/"+Vg(t)}ae.getErrorPath=hL;function Rw(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ae.checkStrictMode=Rw});var un=L(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});var ft=oe(),gL={data:new ft.Name("data"),valCxt:new ft.Name("valCxt"),instancePath:new ft.Name("instancePath"),parentData:new ft.Name("parentData"),parentDataProperty:new ft.Name("parentDataProperty"),rootData:new ft.Name("rootData"),dynamicAnchors:new ft.Name("dynamicAnchors"),vErrors:new ft.Name("vErrors"),errors:new ft.Name("errors"),this:new ft.Name("this"),self:new ft.Name("self"),scope:new ft.Name("scope"),json:new ft.Name("json"),jsonPos:new ft.Name("jsonPos"),jsonLen:new ft.Name("jsonLen"),jsonPart:new ft.Name("jsonPart")};Kg.default=gL});var $a=L(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.extendErrors=ht.resetErrorsCount=ht.reportExtraError=ht.reportError=ht.keyword$DataError=ht.keywordError=void 0;var fe=oe(),ol=me(),$t=un();ht.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};ht.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,fe.str)`"${t}" keyword must be ${e} ($data)`:(0,fe.str)`"${t}" keyword is invalid ($data)`};function yL(t,e=ht.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Iw(t,e,r);n??(i||a)?Cw(s,c):Ow(o,(0,fe._)`[${c}]`)}ht.reportError=yL;function _L(t,e=ht.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Iw(t,e,r);Cw(o,a),s||i||Ow(n,$t.default.vErrors)}ht.reportExtraError=_L;function xL(t,e){t.assign($t.default.errors,e),t.if((0,fe._)`${$t.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${$t.default.vErrors}.length`,e),()=>t.assign($t.default.vErrors,null)))}ht.resetErrorsCount=xL;function bL({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,$t.default.errors,a=>{t.const(i,(0,fe._)`${$t.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)($t.default.instancePath,s.errorPath))),t.assign((0,fe._)`${i}.schemaPath`,(0,fe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,fe._)`${i}.schema`,r),t.assign((0,fe._)`${i}.data`,n))})}ht.extendErrors=bL;function Cw(t,e){let r=t.const("err",e);t.if((0,fe._)`${$t.default.vErrors} === null`,()=>t.assign($t.default.vErrors,(0,fe._)`[${r}]`),(0,fe._)`${$t.default.vErrors}.push(${r})`),t.code((0,fe._)`${$t.default.errors}++`)}function Ow(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,fe._)`new ${t.ValidationError}(${e})`):(r.assign((0,fe._)`${n}.errors`,e),r.return(!1))}var Uo={keyword:new fe.Name("keyword"),schemaPath:new fe.Name("schemaPath"),params:new fe.Name("params"),propertyName:new fe.Name("propertyName"),message:new fe.Name("message"),schema:new fe.Name("schema"),parentSchema:new fe.Name("parentSchema")};function Iw(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,fe._)`{}`:vL(t,e,r)}function vL(t,e,r={}){let{gen:n,it:o}=t,s=[SL(o,r),kL(t,r)];return wL(t,e,s),n.object(...s)}function SL({errorPath:t},{instancePath:e}){let r=e?(0,fe.str)`${t}${(0,ol.getErrorPath)(e,ol.Type.Str)}`:t;return[$t.default.instancePath,(0,fe.strConcat)($t.default.instancePath,r)]}function kL({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,fe.str)`${e}/${t}`;return r&&(o=(0,fe.str)`${o}${(0,ol.getErrorPath)(r,ol.Type.Str)}`),[Uo.schemaPath,o]}function wL(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Uo.keyword,o],[Uo.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&n.push([Uo.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Uo.schema,i],[Uo.parentSchema,(0,fe._)`${l}${d}`],[$t.default.data,s]),u&&n.push([Uo.propertyName,u])}});var Nw=L(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.boolOrEmptySchema=Ws.topBoolOrEmptySchema=void 0;var EL=$a(),$L=oe(),TL=un(),PL={message:"boolean schema is false"};function RL(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Aw(t,!1):typeof r=="object"&&r.$async===!0?e.return(TL.default.data):(e.assign((0,$L._)`${n}.errors`,null),e.return(!0))}Ws.topBoolOrEmptySchema=RL;function CL(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Aw(t)):r.var(e,!0)}Ws.boolOrEmptySchema=CL;function Aw(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,EL.reportError)(o,PL,void 0,e)}});var Gg=L(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.getRules=Ks.isJSONType=void 0;var OL=["string","number","integer","boolean","null","object","array"],IL=new Set(OL);function AL(t){return typeof t=="string"&&IL.has(t)}Ks.isJSONType=AL;function NL(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Ks.getRules=NL});var Jg=L(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.shouldUseRule=Fn.shouldUseGroup=Fn.schemaHasRulesForType=void 0;function DL({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Dw(t,n)}Fn.schemaHasRulesForType=DL;function Dw(t,e){return e.rules.some(r=>Mw(t,r))}Fn.shouldUseGroup=Dw;function Mw(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Fn.shouldUseRule=Mw});var Ta=L(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.reportTypeError=gt.checkDataTypes=gt.checkDataType=gt.coerceAndCheckDataType=gt.getJSONTypes=gt.getSchemaTypes=gt.DataType=void 0;var ML=Gg(),jL=Jg(),LL=$a(),re=oe(),jw=me(),Gs;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Gs||(gt.DataType=Gs={}));function zL(t){let e=Lw(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}gt.getSchemaTypes=zL;function Lw(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(ML.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}gt.getJSONTypes=Lw;function FL(t,e){let{gen:r,data:n,opts:o}=t,s=HL(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,jL.schemaHasRulesForType)(t,e[0]));if(i){let a=Yg(e,n,o.strictNumbers,Gs.Wrong);r.if(a,()=>{s.length?UL(t,e,s):Qg(t)})}return i}gt.coerceAndCheckDataType=FL;var zw=new Set(["string","number","integer","boolean","null"]);function HL(t,e){return e?t.filter(r=>zw.has(r)||e==="array"&&r==="array"):[]}function UL(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,re._)`typeof ${o}`),a=n.let("coerced",(0,re._)`undefined`);s.coerceTypes==="array"&&n.if((0,re._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,re._)`${o}[0]`).assign(i,(0,re._)`typeof ${o}`).if(Yg(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,re._)`${a} !== undefined`);for(let u of r)(zw.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Qg(t),n.endIf(),n.if((0,re._)`${a} !== undefined`,()=>{n.assign(o,a),BL(t,a)});function c(u){switch(u){case"string":n.elseIf((0,re._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,re._)`"" + ${o}`).elseIf((0,re._)`${o} === null`).assign(a,(0,re._)`""`);return;case"number":n.elseIf((0,re._)`${i} == "boolean" || ${o} === null
|
|
481
|
-
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,
|
|
482
|
-
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,
|
|
483
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,re._)`[${o}]`)}}}function BL({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,re._)`${e} !== undefined`,()=>t.assign((0,re._)`${e}[${r}]`,n))}function Xg(t,e,r,n=Gs.Correct){let o=n===Gs.Correct?re.operators.EQ:re.operators.NEQ,s;switch(t){case"null":return(0,re._)`${e} ${o} null`;case"array":s=(0,re._)`Array.isArray(${e})`;break;case"object":s=(0,re._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,re._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,re._)`typeof ${e} ${o} ${t}`}return n===Gs.Correct?s:(0,re.not)(s);function i(a=re.nil){return(0,re.and)((0,re._)`typeof ${e} == "number"`,a,r?(0,re._)`isFinite(${e})`:re.nil)}}gt.checkDataType=Xg;function Yg(t,e,r,n){if(t.length===1)return Xg(t[0],e,r,n);let o,s=(0,jw.toHash)(t);if(s.array&&s.object){let i=(0,re._)`typeof ${e} != "object"`;o=s.null?i:(0,re._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=re.nil;s.number&&delete s.integer;for(let i in s)o=(0,re.and)(o,Xg(i,e,r,n));return o}gt.checkDataTypes=Yg;var ZL={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,re._)`{type: ${t}}`:(0,re._)`{type: ${e}}`};function Qg(t){let e=qL(t);(0,LL.reportError)(e,ZL)}gt.reportTypeError=Qg;function qL(t){let{gen:e,data:r,schema:n}=t,o=(0,jw.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Hw=L(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});sl.assignDefaults=void 0;var Js=oe(),VL=me();function WL(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Fw(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Fw(t,s,o.default))}sl.assignDefaults=WL;function Fw(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Js._)`${s}${(0,Js.getProperty)(e)}`;if(o){(0,VL.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Js._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Js._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Js._)`${a} = ${(0,Js.stringify)(r)}`)}});var cr=L(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.validateUnion=Se.validateArray=Se.usePattern=Se.callValidateCode=Se.schemaProperties=Se.allSchemaProperties=Se.noPropertyInData=Se.propertyInData=Se.isOwnProperty=Se.hasPropFunc=Se.reportMissingProp=Se.checkMissingProp=Se.checkReportMissingProp=void 0;var Ae=oe(),ey=me(),Hn=un(),KL=me();function GL(t,e){let{gen:r,data:n,it:o}=t;r.if(ry(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ae._)`${e}`},!0),t.error()})}Se.checkReportMissingProp=GL;function JL({gen:t,data:e,it:{opts:r}},n,o){return(0,Ae.or)(...n.map(s=>(0,Ae.and)(ry(t,e,s,r.ownProperties),(0,Ae._)`${o} = ${s}`)))}Se.checkMissingProp=JL;function XL(t,e){t.setParams({missingProperty:e},!0),t.error()}Se.reportMissingProp=XL;function Uw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ae._)`Object.prototype.hasOwnProperty`})}Se.hasPropFunc=Uw;function ty(t,e,r){return(0,Ae._)`${Uw(t)}.call(${e}, ${r})`}Se.isOwnProperty=ty;function YL(t,e,r,n){let o=(0,Ae._)`${e}${(0,Ae.getProperty)(r)} !== undefined`;return n?(0,Ae._)`${o} && ${ty(t,e,r)}`:o}Se.propertyInData=YL;function ry(t,e,r,n){let o=(0,Ae._)`${e}${(0,Ae.getProperty)(r)} === undefined`;return n?(0,Ae.or)(o,(0,Ae.not)(ty(t,e,r))):o}Se.noPropertyInData=ry;function Bw(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Se.allSchemaProperties=Bw;function QL(t,e){return Bw(e).filter(r=>!(0,ey.alwaysValidSchema)(t,e[r]))}Se.schemaProperties=QL;function ez({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Ae._)`${t}, ${e}, ${n}${o}`:e,d=[[Hn.default.instancePath,(0,Ae.strConcat)(Hn.default.instancePath,s)],[Hn.default.parentData,i.parentData],[Hn.default.parentDataProperty,i.parentDataProperty],[Hn.default.rootData,Hn.default.rootData]];i.opts.dynamicRef&&d.push([Hn.default.dynamicAnchors,Hn.default.dynamicAnchors]);let p=(0,Ae._)`${l}, ${r.object(...d)}`;return c!==Ae.nil?(0,Ae._)`${a}.call(${c}, ${p})`:(0,Ae._)`${a}(${p})`}Se.callValidateCode=ez;var tz=(0,Ae._)`new RegExp`;function rz({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ae._)`${o.code==="new RegExp"?tz:(0,KL.useFunc)(t,o)}(${r}, ${n})`})}Se.usePattern=rz;function nz(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Ae._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:ey.Type.Num},s),e.if((0,Ae.not)(s),a)})}}Se.validateArray=nz;function oz(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,ey.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Ae._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ae.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Se.validateUnion=oz});var Vw=L(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.validateKeywordUsage=zr.validSchemaType=zr.funcKeywordCode=zr.macroKeywordCode=void 0;var Tt=oe(),Bo=un(),sz=cr(),iz=$a();function az(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=qw(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Tt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}zr.macroKeywordCode=az;function cz(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;lz(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=qw(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)f(),e.modifying&&Zw(t),g(()=>t.error());else{let y=e.async?h():m();e.modifying&&Zw(t),g(()=>uz(t,y))}}function h(){let y=n.let("ruleErrs",null);return n.try(()=>f((0,Tt._)`await `),_=>n.assign(d,!1).if((0,Tt._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,Tt._)`${_}.errors`),()=>n.throw(_))),y}function m(){let y=(0,Tt._)`${l}.errors`;return n.assign(y,null),f(Tt.nil),y}function f(y=e.async?(0,Tt._)`await `:Tt.nil){let _=c.opts.passContext?Bo.default.this:Bo.default.self,x=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Tt._)`${y}${(0,sz.callValidateCode)(t,l,_,x)}`,e.modifying)}function g(y){var _;n.if((0,Tt.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}zr.funcKeywordCode=cz;function Zw(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Tt._)`${n.parentData}[${n.parentDataProperty}]`))}function uz(t,e){let{gen:r}=t;r.if((0,Tt._)`Array.isArray(${e})`,()=>{r.assign(Bo.default.vErrors,(0,Tt._)`${Bo.default.vErrors} === null ? ${e} : ${Bo.default.vErrors}.concat(${e})`).assign(Bo.default.errors,(0,Tt._)`${Bo.default.vErrors}.length`),(0,iz.extendErrors)(t)},()=>t.error())}function lz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function qw(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Tt.stringify)(r)})}function dz(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}zr.validSchemaType=dz;function pz({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}zr.validateKeywordUsage=pz});var Kw=L(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.extendSubschemaMode=Un.extendSubschemaData=Un.getSubschema=void 0;var Fr=oe(),Ww=me();function mz(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Fr._)`${t.schemaPath}${(0,Fr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Fr._)`${t.schemaPath}${(0,Fr.getProperty)(e)}${(0,Fr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Ww.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Un.getSubschema=mz;function fz(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,Fr._)`${e.data}${(0,Fr.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Fr.str)`${u}${(0,Ww.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Fr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Fr.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Un.extendSubschemaData=fz;function hz(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Un.extendSubschemaMode=hz});var ny=L((WG,Gw)=>{"use strict";Gw.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Xw=L((KG,Jw)=>{"use strict";var Bn=Jw.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};il(e,n,o,t,"",t)};Bn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Bn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Bn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Bn.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function il(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Bn.arrayKeywords)for(var p=0;p<d.length;p++)il(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in Bn.propsKeywords){if(d&&typeof d=="object")for(var h in d)il(t,e,r,d[h],o+"/"+l+"/"+gz(h),s,o,l,n,h)}else(l in Bn.keywords||t.allKeys&&!(l in Bn.skipKeywords))&&il(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function gz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Pa=L(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.getSchemaRefs=Mt.resolveUrl=Mt.normalizeId=Mt._getFullPath=Mt.getFullPath=Mt.inlineRef=void 0;var yz=me(),_z=ny(),xz=Xw(),bz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function vz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!oy(t):e?Yw(t)<=e:!1}Mt.inlineRef=vz;var Sz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function oy(t){for(let e in t){if(Sz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(oy)||typeof r=="object"&&oy(r))return!0}return!1}function Yw(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!bz.has(r)&&(typeof t[r]=="object"&&(0,yz.eachItem)(t[r],n=>e+=Yw(n)),e===1/0))return 1/0}return e}function Qw(t,e="",r){r!==!1&&(e=Xs(e));let n=t.parse(e);return eE(t,n)}Mt.getFullPath=Qw;function eE(t,e){return t.serialize(e).split("#")[0]+"#"}Mt._getFullPath=eE;var kz=/#\/?$/;function Xs(t){return t?t.replace(kz,""):""}Mt.normalizeId=Xs;function wz(t,e,r){return r=Xs(r),t.resolve(e,r)}Mt.resolveUrl=wz;var Ez=/^[a-z_][-a-z0-9._]*$/i;function $z(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Xs(t[r]||e),s={"":o},i=Qw(n,o,!1),a={},c=new Set;return xz(t,{allKeys:!0},(d,p,h,m)=>{if(m===void 0)return;let f=i+p,g=s[m];typeof d[r]=="string"&&(g=y.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[p]=g;function y(x){let v=this.opts.uriResolver.resolve;if(x=Xs(g?v(g,x):x),c.has(x))throw l(x);c.add(x);let E=this.refs[x];return typeof E=="string"&&(E=this.refs[E]),typeof E=="object"?u(d,E.schema,x):x!==Xs(f)&&(x[0]==="#"?(u(d,a[x],x),a[x]=d):this.refs[x]=f),x}function _(x){if(typeof x=="string"){if(!Ez.test(x))throw new Error(`invalid anchor "${x}"`);y.call(this,`#${x}`)}}}),a;function u(d,p,h){if(p!==void 0&&!_z(d,p))throw l(h)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Mt.getSchemaRefs=$z});var Oa=L(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.getData=Zn.KeywordCxt=Zn.validateFunctionCode=void 0;var sE=Nw(),tE=Ta(),iy=Jg(),al=Ta(),Tz=Hw(),Ca=Vw(),sy=Kw(),V=oe(),ee=un(),Pz=Pa(),ln=me(),Ra=$a();function Rz(t){if(cE(t)&&(uE(t),aE(t))){Iz(t);return}iE(t,()=>(0,sE.topBoolOrEmptySchema)(t))}Zn.validateFunctionCode=Rz;function iE({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,V._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{t.code((0,V._)`"use strict"; ${rE(r,o)}`),Oz(t,o),t.code(s)}):t.func(e,(0,V._)`${ee.default.data}, ${Cz(o)}`,n.$async,()=>t.code(rE(r,o)).code(s))}function Cz(t){return(0,V._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,V._)`, ${ee.default.dynamicAnchors}={}`:V.nil}}={}`}function Oz(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,V._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,V._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,V._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,V._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,V._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,V._)`""`),t.var(ee.default.parentData,(0,V._)`undefined`),t.var(ee.default.parentDataProperty,(0,V._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,V._)`{}`)})}function Iz(t){let{schema:e,opts:r,gen:n}=t;iE(t,()=>{r.$comment&&e.$comment&&dE(t),jz(t),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&Az(t),lE(t),Fz(t)})}function Az(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,V._)`${r}.evaluated`),e.if((0,V._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,V._)`${t.evaluated}.props`,(0,V._)`undefined`)),e.if((0,V._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,V._)`${t.evaluated}.items`,(0,V._)`undefined`))}function rE(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,V._)`/*# sourceURL=${r} */`:V.nil}function Nz(t,e){if(cE(t)&&(uE(t),aE(t))){Dz(t,e);return}(0,sE.boolOrEmptySchema)(t,e)}function aE({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function cE(t){return typeof t.schema!="boolean"}function Dz(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&dE(t),Lz(t),zz(t);let s=n.const("_errs",ee.default.errors);lE(t,s),n.var(e,(0,V._)`${s} === ${ee.default.errors}`)}function uE(t){(0,ln.checkUnknownRules)(t),Mz(t)}function lE(t,e){if(t.opts.jtd)return nE(t,[],!1,e);let r=(0,tE.getSchemaTypes)(t.schema),n=(0,tE.coerceAndCheckDataType)(t,r);nE(t,r,!n,e)}function Mz(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ln.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function jz(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ln.checkStrictMode)(t,"default is ignored in the schema root")}function Lz(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Pz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function zz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function dE({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,V._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,V.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,V._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Fz(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,V._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,V._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,V._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&Hz(t),e.return((0,V._)`${ee.default.errors} === 0`))}function Hz({gen:t,evaluated:e,props:r,items:n}){r instanceof V.Name&&t.assign((0,V._)`${e}.props`,r),n instanceof V.Name&&t.assign((0,V._)`${e}.items`,n)}function nE(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ln.schemaHasRulesButRef)(s,l))){o.block(()=>mE(t,"$ref",l.all.$ref.definition));return}c.jtd||Uz(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,iy.shouldUseGroup)(s,p)&&(p.type?(o.if((0,al.checkDataType)(p.type,i,c.strictNumbers)),oE(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,al.reportTypeError)(t)),o.endIf()):oE(t,p),a||o.if((0,V._)`${ee.default.errors} === ${n||0}`))}}function oE(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,Tz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,iy.shouldUseRule)(n,s)&&mE(t,s.keyword,s.definition,e.type)})}function Uz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Bz(t,e),t.opts.allowUnionTypes||Zz(t,e),qz(t,t.dataTypes))}function Bz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{pE(t.dataTypes,r)||ay(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Wz(t,e)}}function Zz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ay(t,"use allowUnionTypes to allow union type keyword")}function qz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,iy.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Vz(e,i))&&ay(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Vz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function pE(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Wz(t,e){let r=[];for(let n of t.dataTypes)pE(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function ay(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ln.checkStrictMode)(t,e,t.opts.strictTypes)}var cl=class{constructor(e,r,n){if((0,Ca.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ln.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",fE(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ca.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ee.default.errors))}result(e,r,n){this.failResult((0,V.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,V.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,V._)`${r} !== undefined && (${(0,V.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Ra.reportExtraError:Ra.reportError)(this,this.def.error,r)}$dataError(){(0,Ra.reportError)(this,this.def.$dataError||Ra.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ra.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=V.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=V.nil,r=V.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,V.or)((0,V._)`${o} === undefined`,r)),e!==V.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==V.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,V.or)(i(),a());function i(){if(n.length){if(!(r instanceof V.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,V._)`${(0,al.checkDataTypes)(c,r,s.opts.strictNumbers,al.DataType.Wrong)}`}return V.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,V._)`!${c}(${r})`}return V.nil}}subschema(e,r){let n=(0,sy.getSubschema)(this.it,e);(0,sy.extendSubschemaData)(n,this.it,e),(0,sy.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Nz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ln.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ln.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,V.Name)),!0}};Zn.KeywordCxt=cl;function mE(t,e,r,n){let o=new cl(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ca.funcKeywordCode)(o,r):"macro"in r?(0,Ca.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ca.funcKeywordCode)(o,r)}var Kz=/^\/(?:[^~]|~0|~1)*$/,Gz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function fE(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!Kz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=Gz.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,V._)`${s}${(0,V.getProperty)((0,ln.unescapeJsonPointer)(u))}`,i=(0,V._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Zn.getData=fE});var ul=L(uy=>{"use strict";Object.defineProperty(uy,"__esModule",{value:!0});var cy=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};uy.default=cy});var Ia=L(py=>{"use strict";Object.defineProperty(py,"__esModule",{value:!0});var ly=Pa(),dy=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,ly.resolveUrl)(e,r,n),this.missingSchema=(0,ly.normalizeId)((0,ly.getFullPath)(e,this.missingRef))}};py.default=dy});var dl=L(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.resolveSchema=ur.getCompilingSchema=ur.resolveRef=ur.compileSchema=ur.SchemaEnv=void 0;var br=oe(),Jz=ul(),Zo=un(),vr=Pa(),hE=me(),Xz=Oa(),Ys=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,vr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ur.SchemaEnv=Ys;function fy(t){let e=gE.call(this,t);if(e)return e;let r=(0,vr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new br.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:Jz.default,code:(0,br._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Zo.default.data,parentData:Zo.default.parentData,parentDataProperty:Zo.default.parentDataProperty,dataNames:[Zo.default.data],dataPathArr:[br.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,br.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:br.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,br._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,Xz.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Zo.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let h=new Function(`${Zo.default.self}`,`${Zo.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:f}=u;h.evaluated={props:m instanceof br.Name?void 0:m,items:f instanceof br.Name?void 0:f,dynamicProps:m instanceof br.Name,dynamicItems:f instanceof br.Name},h.source&&(h.source.evaluated=(0,br.stringify)(h.evaluated))}return t.validate=h,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}ur.compileSchema=fy;function Yz(t,e,r){var n;r=(0,vr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=tF.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Ys({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Qz.call(this,s)}ur.resolveRef=Yz;function Qz(t){return(0,vr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:fy.call(this,t)}function gE(t){for(let e of this._compilations)if(eF(e,t))return e}ur.getCompilingSchema=gE;function eF(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function tF(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ll.call(this,t,e)}function ll(t,e){let r=this.opts.uriResolver.parse(e),n=(0,vr._getFullPath)(this.opts.uriResolver,r),o=(0,vr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return my.call(this,r,t);let s=(0,vr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ll.call(this,t,i);return typeof a?.schema!="object"?void 0:my.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||fy.call(this,i),s===(0,vr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,vr.resolveUrl)(this.opts.uriResolver,o,u)),new Ys({schema:a,schemaId:c,root:t,baseId:o})}return my.call(this,r,i)}}ur.resolveSchema=ll;var rF=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function my(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,hE.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!rF.has(a)&&u&&(e=(0,vr.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,hE.schemaHasRulesButRef)(r,this.RULES)){let a=(0,vr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ll.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Ys({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var yE=L((eJ,nF)=>{nF.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var gy=L((tJ,vE)=>{"use strict";var oF=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),xE=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function hy(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var sF=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _E(t){return t.length=0,!0}function iF(t,e,r){if(t.length){let n=hy(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function aF(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=iF;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=_E}else{o.push(u);continue}}return o.length&&(a===_E?r.zone=o.join(""):i?n.push(o.join("")):n.push(hy(o))),r.address=n.join(""),r}function bE(t){if(cF(t,":")<2)return{host:t,isIPV6:!1};let e=aF(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function cF(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function uF(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function lF(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function dF(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!xE(r)){let n=bE(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}vE.exports={nonSimpleDomain:sF,recomposeAuthority:dF,normalizeComponentEncoding:lF,removeDotSegments:uF,isIPv4:xE,isUUID:oF,normalizeIPv6:bE,stringArrayToHexStripped:hy}});var $E=L((rJ,EE)=>{"use strict";var{isUUID:pF}=gy(),mF=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,fF=["http","https","ws","wss","urn","urn:uuid"];function hF(t){return fF.indexOf(t)!==-1}function yy(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function SE(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function kE(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function gF(t){return t.secure=yy(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function yF(t){if((t.port===(yy(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function _F(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(mF);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=_y(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function xF(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=_y(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function bF(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!pF(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function vF(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var wE={scheme:"http",domainHost:!0,parse:SE,serialize:kE},SF={scheme:"https",domainHost:wE.domainHost,parse:SE,serialize:kE},pl={scheme:"ws",domainHost:!0,parse:gF,serialize:yF},kF={scheme:"wss",domainHost:pl.domainHost,parse:pl.parse,serialize:pl.serialize},wF={scheme:"urn",parse:_F,serialize:xF,skipNormalize:!0},EF={scheme:"urn:uuid",parse:bF,serialize:vF,skipNormalize:!0},ml={http:wE,https:SF,ws:pl,wss:kF,urn:wF,"urn:uuid":EF};Object.setPrototypeOf(ml,null);function _y(t){return t&&(ml[t]||ml[t.toLowerCase()])||void 0}EE.exports={wsIsSecure:yy,SCHEMES:ml,isValidSchemeName:hF,getSchemeHandler:_y}});var RE=L((nJ,hl)=>{"use strict";var{normalizeIPv6:$F,removeDotSegments:Aa,recomposeAuthority:TF,normalizeComponentEncoding:fl,isIPv4:PF,nonSimpleDomain:RF}=gy(),{SCHEMES:CF,getSchemeHandler:TE}=$E();function OF(t,e){return typeof t=="string"?t=Hr(dn(t,e),e):typeof t=="object"&&(t=dn(Hr(t,e),e)),t}function IF(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=PE(dn(t,n),dn(e,n),n,!0);return n.skipEscape=!0,Hr(o,n)}function PE(t,e,r,n){let o={};return n||(t=dn(Hr(t,r),r),e=dn(Hr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Aa(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Aa(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Aa(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Aa(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function AF(t,e,r){return typeof t=="string"?(t=unescape(t),t=Hr(fl(dn(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Hr(fl(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Hr(fl(dn(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Hr(fl(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Hr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=TE(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=TF(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Aa(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var NF=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function dn(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(NF);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(PF(n.host)===!1){let c=$F(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=TE(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&RF(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var xy={SCHEMES:CF,normalize:OF,resolve:IF,resolveComponent:PE,equal:AF,serialize:Hr,parse:dn};hl.exports=xy;hl.exports.default=xy;hl.exports.fastUri=xy});var OE=L(by=>{"use strict";Object.defineProperty(by,"__esModule",{value:!0});var CE=RE();CE.code='require("ajv/dist/runtime/uri").default';by.default=CE});var zE=L(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.CodeGen=ut.Name=ut.nil=ut.stringify=ut.str=ut._=ut.KeywordCxt=void 0;var DF=Oa();Object.defineProperty(ut,"KeywordCxt",{enumerable:!0,get:function(){return DF.KeywordCxt}});var Qs=oe();Object.defineProperty(ut,"_",{enumerable:!0,get:function(){return Qs._}});Object.defineProperty(ut,"str",{enumerable:!0,get:function(){return Qs.str}});Object.defineProperty(ut,"stringify",{enumerable:!0,get:function(){return Qs.stringify}});Object.defineProperty(ut,"nil",{enumerable:!0,get:function(){return Qs.nil}});Object.defineProperty(ut,"Name",{enumerable:!0,get:function(){return Qs.Name}});Object.defineProperty(ut,"CodeGen",{enumerable:!0,get:function(){return Qs.CodeGen}});var MF=ul(),ME=Ia(),jF=Gg(),Na=dl(),LF=oe(),Da=Pa(),gl=Ta(),Sy=me(),IE=yE(),zF=OE(),jE=(t,e)=>new RegExp(t,e);jE.code="new RegExp";var FF=["removeAdditional","useDefaults","coerceTypes"],HF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),UF={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},BF={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},AE=200;function ZF(t){var e,r,n,o,s,i,a,c,u,l,d,p,h,m,f,g,y,_,x,v,E,C,b,k,P;let N=t.strict,R=(e=t.code)===null||e===void 0?void 0:e.optimize,O=R===!0||R===void 0?1:R||0,F=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:jE,K=(o=t.uriResolver)!==null&&o!==void 0?o:zF.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:N)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:N)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:N)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:N)!==null&&p!==void 0?p:"log",strictRequired:(m=(h=t.strictRequired)!==null&&h!==void 0?h:N)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:O,regExp:F}:{optimize:O,regExp:F},loopRequired:(f=t.loopRequired)!==null&&f!==void 0?f:AE,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:AE,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(v=t.schemaId)!==null&&v!==void 0?v:"$id",addUsedSchema:(E=t.addUsedSchema)!==null&&E!==void 0?E:!0,validateSchema:(C=t.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(b=t.validateFormats)!==null&&b!==void 0?b:!0,unicodeRegExp:(k=t.unicodeRegExp)!==null&&k!==void 0?k:!0,int32range:(P=t.int32range)!==null&&P!==void 0?P:!0,uriResolver:K}}var Ma=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...ZF(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new LF.ValueScope({scope:{},prefixes:HF,es5:r,lines:n}),this.logger=JF(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,jF.getRules)(),NE.call(this,UF,e,"NOT SUPPORTED"),NE.call(this,BF,e,"DEPRECATED","warn"),this._metaOpts=KF.call(this),e.formats&&VF.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&WF.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),qF.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=IE;n==="id"&&(o={...IE},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof ME.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Da.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=DE.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Na.SchemaEnv({schema:{},schemaId:n});if(r=Na.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=DE.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Da.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(YF.call(this,n,r),!r)return(0,Sy.eachItem)(n,s=>vy.call(this,s)),this;eH.call(this,r);let o={...r,type:(0,gl.getJSONTypes)(r.type),schemaType:(0,gl.getJSONTypes)(r.schemaType)};return(0,Sy.eachItem)(n,o.type.length===0?s=>vy.call(this,s,o):s=>o.type.forEach(i=>vy.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=LE(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Da.normalizeId)(i||n);let u=Da.getSchemaRefs.call(this,e,n);return c=new Na.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Na.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Na.compileSchema.call(this,e)}finally{this.opts=r}}};Ma.ValidationError=MF.default;Ma.MissingRefError=ME.default;ut.default=Ma;function NE(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function DE(t){return t=(0,Da.normalizeId)(t),this.schemas[t]||this.refs[t]}function qF(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function VF(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function WF(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function KF(){let t={...this.opts};for(let e of FF)delete t[e];return t}var GF={log(){},warn(){},error(){}};function JF(t){if(t===!1)return GF;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var XF=/^[a-z_$][a-z0-9_$:-]*$/i;function YF(t,e){let{RULES:r}=this;if((0,Sy.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!XF.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function vy(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,gl.getJSONTypes)(e.type),schemaType:(0,gl.getJSONTypes)(e.schemaType)}};e.before?QF.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function QF(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function eH(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=LE(e)),t.validateSchema=this.compile(e,!0))}var tH={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function LE(t){return{anyOf:[t,tH]}}});var FE=L(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});var rH={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ky.default=rH});var ZE=L(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.callRef=qo.getValidate=void 0;var nH=Ia(),HE=cr(),jt=oe(),ei=un(),UE=dl(),yl=me(),oH={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=UE.resolveRef.call(c,u,o,r);if(l===void 0)throw new nH.default(n.opts.uriResolver,o,r);if(l instanceof UE.SchemaEnv)return p(l);return h(l);function d(){if(s===u)return _l(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return _l(t,(0,jt._)`${m}.validate`,u,u.$async)}function p(m){let f=BE(t,m);_l(t,f,m,m.$async)}function h(m){let f=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,jt.stringify)(m)}:{ref:m}),g=e.name("valid"),y=t.subschema({schema:m,dataTypes:[],schemaPath:jt.nil,topSchemaRef:f,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function BE(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,jt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}qo.getValidate=BE;function _l(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ei.default.this:jt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,jt._)`await ${(0,HE.callValidateCode)(t,e,u)}`),h(e),i||o.assign(m,!0)},f=>{o.if((0,jt._)`!(${f} instanceof ${s.ValidationError})`,()=>o.throw(f)),p(f),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,HE.callValidateCode)(t,e,u),()=>h(e),()=>p(e))}function p(m){let f=(0,jt._)`${m}.errors`;o.assign(ei.default.vErrors,(0,jt._)`${ei.default.vErrors} === null ? ${f} : ${ei.default.vErrors}.concat(${f})`),o.assign(ei.default.errors,(0,jt._)`${ei.default.vErrors}.length`)}function h(m){var f;if(!s.opts.unevaluated)return;let g=(f=r?.validate)===null||f===void 0?void 0:f.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=yl.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,jt._)`${m}.evaluated.props`);s.props=yl.mergeEvaluated.props(o,y,s.props,jt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=yl.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,jt._)`${m}.evaluated.items`);s.items=yl.mergeEvaluated.items(o,y,s.items,jt.Name)}}}qo.callRef=_l;qo.default=oH});var qE=L(wy=>{"use strict";Object.defineProperty(wy,"__esModule",{value:!0});var sH=FE(),iH=ZE(),aH=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",sH.default,iH.default];wy.default=aH});var VE=L(Ey=>{"use strict";Object.defineProperty(Ey,"__esModule",{value:!0});var xl=oe(),qn=xl.operators,bl={maximum:{okStr:"<=",ok:qn.LTE,fail:qn.GT},minimum:{okStr:">=",ok:qn.GTE,fail:qn.LT},exclusiveMaximum:{okStr:"<",ok:qn.LT,fail:qn.GTE},exclusiveMinimum:{okStr:">",ok:qn.GT,fail:qn.LTE}},cH={message:({keyword:t,schemaCode:e})=>(0,xl.str)`must be ${bl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,xl._)`{comparison: ${bl[t].okStr}, limit: ${e}}`},uH={keyword:Object.keys(bl),type:"number",schemaType:"number",$data:!0,error:cH,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,xl._)`${r} ${bl[e].fail} ${n} || isNaN(${r})`)}};Ey.default=uH});var WE=L($y=>{"use strict";Object.defineProperty($y,"__esModule",{value:!0});var ja=oe(),lH={message:({schemaCode:t})=>(0,ja.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ja._)`{multipleOf: ${t}}`},dH={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:lH,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ja._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ja._)`${i} !== parseInt(${i})`;t.fail$data((0,ja._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};$y.default=dH});var GE=L(Ty=>{"use strict";Object.defineProperty(Ty,"__esModule",{value:!0});function KE(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Ty.default=KE;KE.code='require("ajv/dist/runtime/ucs2length").default'});var JE=L(Py=>{"use strict";Object.defineProperty(Py,"__esModule",{value:!0});var Vo=oe(),pH=me(),mH=GE(),fH={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Vo.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Vo._)`{limit: ${t}}`},hH={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:fH,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Vo.operators.GT:Vo.operators.LT,i=o.opts.unicode===!1?(0,Vo._)`${r}.length`:(0,Vo._)`${(0,pH.useFunc)(t.gen,mH.default)}(${r})`;t.fail$data((0,Vo._)`${i} ${s} ${n}`)}};Py.default=hH});var XE=L(Ry=>{"use strict";Object.defineProperty(Ry,"__esModule",{value:!0});var gH=cr(),yH=me(),ti=oe(),_H={message:({schemaCode:t})=>(0,ti.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ti._)`{pattern: ${t}}`},xH={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:_H,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,ti._)`new RegExp`:(0,yH.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ti._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,ti._)`!${l}`)}else{let c=(0,gH.usePattern)(t,o);t.fail$data((0,ti._)`!${c}.test(${r})`)}}};Ry.default=xH});var YE=L(Cy=>{"use strict";Object.defineProperty(Cy,"__esModule",{value:!0});var La=oe(),bH={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,La.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,La._)`{limit: ${t}}`},vH={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:bH,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?La.operators.GT:La.operators.LT;t.fail$data((0,La._)`Object.keys(${r}).length ${o} ${n}`)}};Cy.default=vH});var QE=L(Oy=>{"use strict";Object.defineProperty(Oy,"__esModule",{value:!0});var za=cr(),Fa=oe(),SH=me(),kH={message:({params:{missingProperty:t}})=>(0,Fa.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Fa._)`{missingProperty: ${t}}`},wH={keyword:"required",type:"object",schemaType:"array",$data:!0,error:kH,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let h=t.parentSchema.properties,{definedProperties:m}=t.it;for(let f of r)if(h?.[f]===void 0&&!m.has(f)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${f}" is not defined at "${g}" (strictRequired)`;(0,SH.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Fa.nil,d);else for(let h of r)(0,za.checkReportMissingProp)(t,h)}function l(){let h=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(h,m)),t.ok(m)}else e.if((0,za.checkMissingProp)(t,r,h)),(0,za.reportMissingProp)(t,h),e.else()}function d(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,za.noPropertyInData)(e,o,h,a.ownProperties),()=>t.error())})}function p(h,m){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(m,(0,za.propertyInData)(e,o,h,a.ownProperties)),e.if((0,Fa.not)(m),()=>{t.error(),e.break()})},Fa.nil)}}};Oy.default=wH});var e$=L(Iy=>{"use strict";Object.defineProperty(Iy,"__esModule",{value:!0});var Ha=oe(),EH={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ha.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ha._)`{limit: ${t}}`},$H={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:EH,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ha.operators.GT:Ha.operators.LT;t.fail$data((0,Ha._)`${r}.length ${o} ${n}`)}};Iy.default=$H});var vl=L(Ay=>{"use strict";Object.defineProperty(Ay,"__esModule",{value:!0});var t$=ny();t$.code='require("ajv/dist/runtime/equal").default';Ay.default=t$});var r$=L(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var Ny=Ta(),lt=oe(),TH=me(),PH=vl(),RH={message:({params:{i:t,j:e}})=>(0,lt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,lt._)`{i: ${t}, j: ${e}}`},CH={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:RH,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Ny.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,lt._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,lt._)`${r}.length`),f=e.let("j");t.setParams({i:m,j:f}),e.assign(c,!0),e.if((0,lt._)`${m} > 1`,()=>(d()?p:h)(m,f))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,f){let g=e.name("item"),y=(0,Ny.checkDataTypes)(u,g,a.opts.strictNumbers,Ny.DataType.Wrong),_=e.const("indices",(0,lt._)`{}`);e.for((0,lt._)`;${m}--;`,()=>{e.let(g,(0,lt._)`${r}[${m}]`),e.if(y,(0,lt._)`continue`),u.length>1&&e.if((0,lt._)`typeof ${g} == "string"`,(0,lt._)`${g} += "_"`),e.if((0,lt._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(f,(0,lt._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,lt._)`${_}[${g}] = ${m}`)})}function h(m,f){let g=(0,TH.useFunc)(e,PH.default),y=e.name("outer");e.label(y).for((0,lt._)`;${m}--;`,()=>e.for((0,lt._)`${f} = ${m}; ${f}--;`,()=>e.if((0,lt._)`${g}(${r}[${m}], ${r}[${f}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Dy.default=CH});var n$=L(jy=>{"use strict";Object.defineProperty(jy,"__esModule",{value:!0});var My=oe(),OH=me(),IH=vl(),AH={message:"must be equal to constant",params:({schemaCode:t})=>(0,My._)`{allowedValue: ${t}}`},NH={keyword:"const",$data:!0,error:AH,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,My._)`!${(0,OH.useFunc)(e,IH.default)}(${r}, ${o})`):t.fail((0,My._)`${s} !== ${r}`)}};jy.default=NH});var o$=L(Ly=>{"use strict";Object.defineProperty(Ly,"__esModule",{value:!0});var Ua=oe(),DH=me(),MH=vl(),jH={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ua._)`{allowedValues: ${t}}`},LH={keyword:"enum",schemaType:"array",$data:!0,error:jH,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,DH.useFunc)(e,MH.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let h=e.const("vSchema",s);l=(0,Ua.or)(...o.map((m,f)=>p(h,f)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,h=>e.if((0,Ua._)`${u()}(${r}, ${h})`,()=>e.assign(l,!0).break()))}function p(h,m){let f=o[m];return typeof f=="object"&&f!==null?(0,Ua._)`${u()}(${r}, ${h}[${m}])`:(0,Ua._)`${r} === ${f}`}}};Ly.default=LH});var s$=L(zy=>{"use strict";Object.defineProperty(zy,"__esModule",{value:!0});var zH=VE(),FH=WE(),HH=JE(),UH=XE(),BH=YE(),ZH=QE(),qH=e$(),VH=r$(),WH=n$(),KH=o$(),GH=[zH.default,FH.default,HH.default,UH.default,BH.default,ZH.default,qH.default,VH.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},WH.default,KH.default];zy.default=GH});var Hy=L(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.validateAdditionalItems=void 0;var Wo=oe(),Fy=me(),JH={message:({params:{len:t}})=>(0,Wo.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Wo._)`{limit: ${t}}`},XH={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:JH,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Fy.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}i$(t,n)}};function i$(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Wo._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Wo._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Fy.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Wo._)`${a} <= ${e.length}`);r.if((0,Wo.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Fy.Type.Num},u),i.allErrors||r.if((0,Wo.not)(u),()=>r.break())})}}Ba.validateAdditionalItems=i$;Ba.default=XH});var Uy=L(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.validateTuple=void 0;var a$=oe(),Sl=me(),YH=cr(),QH={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return c$(t,"additionalItems",e);r.items=!0,!(0,Sl.alwaysValidSchema)(r,e)&&t.ok((0,YH.validateArray)(t))}};function c$(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Sl.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,a$._)`${s}.length`);r.forEach((d,p)=>{(0,Sl.alwaysValidSchema)(a,d)||(n.if((0,a$._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:h}=a,m=r.length,f=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!f){let g=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,Sl.checkStrictMode)(a,g,p.strictTuples)}}}Za.validateTuple=c$;Za.default=QH});var u$=L(By=>{"use strict";Object.defineProperty(By,"__esModule",{value:!0});var eU=Uy(),tU={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,eU.validateTuple)(t,"items")};By.default=tU});var d$=L(Zy=>{"use strict";Object.defineProperty(Zy,"__esModule",{value:!0});var l$=oe(),rU=me(),nU=cr(),oU=Hy(),sU={message:({params:{len:t}})=>(0,l$.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,l$._)`{limit: ${t}}`},iU={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:sU,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,rU.alwaysValidSchema)(n,e)&&(o?(0,oU.validateAdditionalItems)(t,o):t.ok((0,nU.validateArray)(t)))}};Zy.default=iU});var p$=L(qy=>{"use strict";Object.defineProperty(qy,"__esModule",{value:!0});var lr=oe(),kl=me(),aU={message:({params:{min:t,max:e}})=>e===void 0?(0,lr.str)`must contain at least ${t} valid item(s)`:(0,lr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,lr._)`{minContains: ${t}}`:(0,lr._)`{minContains: ${t}, maxContains: ${e}}`},cU={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:aU,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,lr._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,kl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,kl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,kl.alwaysValidSchema)(s,r)){let f=(0,lr._)`${l} >= ${i}`;a!==void 0&&(f=(0,lr._)`${f} && ${l} <= ${a}`),t.pass(f);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?h(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,lr._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let f=e.name("_valid"),g=e.let("count",0);h(f,()=>e.if(f,()=>m(g)))}function h(f,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:kl.Type.Num,compositeRule:!0},f),g()})}function m(f){e.code((0,lr._)`${f}++`),a===void 0?e.if((0,lr._)`${f} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,lr._)`${f} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,lr._)`${f} >= ${i}`,()=>e.assign(d,!0)))}}};qy.default=cU});var h$=L(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.validateSchemaDeps=Ur.validatePropertyDeps=Ur.error=void 0;var Vy=oe(),uU=me(),qa=cr();Ur.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Vy.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Vy._)`{property: ${t},
|
|
484
|
-
missingProperty: ${
|
|
483
|
+
path: iss.path ? [${Oo(_)}, ...iss.path] : [${Oo(_)}]
|
|
484
|
+
})));`),p.write(`newResult[${Oo(_)}] = ${x}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let y=p.compile();return(_,x)=>y(d,_,x)},o,s=Is,i=!uu.jitless,c=i&&Fm.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=n.value);let h=d.value;if(!s(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=r(e.shape)),d=o(d,p);else{d.value={};let x=l.shape;for(let S of l.keys){let E=x[S],A=E._zod.run({value:h[S],issues:[]},p),b=E._zod.optin==="optional"&&E._zod.optout==="optional";A instanceof Promise?m.push(A.then(T=>b?Qk(T,d,S,h):_u(T,d,S))):b?Qk(A,d,S,h):_u(A,d,S)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let f=[],g=l.keySet,y=u._zod,_=y.def.type;for(let x of Object.keys(h)){if(g.has(x))continue;if(_==="never"){f.push(x);continue}let S=y.run({value:h[x],issues:[]},p);S instanceof Promise?m.push(S.then(E=>_u(E,d,x))):_u(S,d,x)}return f.length&&d.issues.push({code:"unrecognized_keys",keys:f,input:h,inst:t}),m.length?Promise.all(m).then(()=>d):d}});Su=$("$ZodUnion",(t,e)=>{ve.init(t,e),Ee(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Ee(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Ee(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Ee(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>ea(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:n.value,issues:[]},r);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>e0(i,n,t,r)):e0(s,n,t,r)}}),Nf=$("$ZodDiscriminatedUnion",(t,e)=>{Su.init(t,e);let n=t._zod.parse;Ee(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let r=Yi(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Is(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Df=$("$ZodIntersection",(t,e)=>{ve.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>t0(n,c,u)):t0(n,s,i)}});Mf=$("$ZodRecord",(t,e)=>{ve.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!As(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;n.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},r);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&n.issues.push(...Mn(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...Mn(c,u.issues)),n.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{n.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>hn(u,r,Ut())),input:i,path:[i],inst:t}),n.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},r);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&n.issues.push(...Mn(i,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(...Mn(i,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}}),jf=$("$ZodEnum",(t,e)=>{ve.init(t,e);let n=Xi(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>Hm.has(typeof r)).map(r=>typeof r=="string"?Or(r):r.toString()).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),Lf=$("$ZodLiteral",(t,e)=>{ve.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Or(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}}),zf=$("$ZodTransform",(t,e)=>{ve.init(t,e),t._zod.parse=(n,r)=>{let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new rr;return n.value=o,n}}),Ff=$("$ZodOptional",(t,e)=>{ve.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ee(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ee(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${ea(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),Hf=$("$ZodNullable",(t,e)=>{ve.init(t,e),Ee(t._zod,"optin",()=>e.innerType._zod.optin),Ee(t._zod,"optout",()=>e.innerType._zod.optout),Ee(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${ea(n.source)}|null)$`):void 0}),Ee(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),Uf=$("$ZodDefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Ee(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>n0(s,e)):n0(o,e)}});Bf=$("$ZodPrefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Ee(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),Zf=$("$ZodNonOptional",(t,e)=>{ve.init(t,e),Ee(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>r0(s,t)):r0(o,t)}});qf=$("$ZodCatch",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Ee(t._zod,"optout",()=>e.innerType._zod.optout),Ee(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>hn(i,r,Ut()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>hn(s,r,Ut()))},input:n.value}),n.issues=[]),n)}}),Vf=$("$ZodPipe",(t,e)=>{ve.init(t,e),Ee(t._zod,"values",()=>e.in._zod.values),Ee(t._zod,"optin",()=>e.in._zod.optin),Ee(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>o0(s,e,r)):o0(o,e,r)}});Wf=$("$ZodReadonly",(t,e)=>{ve.init(t,e),Ee(t._zod,"propValues",()=>e.innerType._zod.propValues),Ee(t._zod,"values",()=>e.innerType._zod.values),Ee(t._zod,"optin",()=>e.innerType._zod.optin),Ee(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s0):s0(o)}});Kf=$("$ZodCustom",(t,e)=>{ct.init(t,e),ve.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>i0(s,n,r,t));i0(o,n,r,t)}})});function m0(){return{localeError:W1()}}var V1,W1,f0=v(()=>{jn();V1=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},W1=()=>{let t={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 e(r){return t[r]??null}let n={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 r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${V1(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${pu(r.values[0])}`:`Invalid option: expected one of ${lu(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${lu(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}}});var vu=v(()=>{});function h0(){return new sa}var sa,Ir,Jf=v(()=>{sa=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){let r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};Ir=h0()});function Xf(t,e){return new t({type:"string",...J(e)})}function Yf(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...J(e)})}function ku(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...J(e)})}function Qf(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...J(e)})}function eh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...J(e)})}function th(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...J(e)})}function nh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...J(e)})}function rh(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...J(e)})}function oh(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...J(e)})}function sh(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...J(e)})}function ih(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...J(e)})}function ah(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...J(e)})}function ch(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...J(e)})}function uh(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...J(e)})}function lh(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...J(e)})}function dh(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...J(e)})}function ph(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...J(e)})}function mh(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...J(e)})}function fh(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...J(e)})}function hh(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...J(e)})}function gh(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...J(e)})}function yh(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...J(e)})}function _h(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...J(e)})}function g0(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...J(e)})}function y0(t,e){return new t({type:"string",format:"date",check:"string_format",...J(e)})}function _0(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...J(e)})}function x0(t,e){return new t({type:"string",format:"duration",check:"string_format",...J(e)})}function xh(t,e){return new t({type:"number",checks:[],...J(e)})}function bh(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...J(e)})}function Sh(t,e){return new t({type:"boolean",...J(e)})}function vh(t,e){return new t({type:"null",...J(e)})}function kh(t){return new t({type:"unknown"})}function wh(t,e){return new t({type:"never",...J(e)})}function wu(t,e){return new rf({check:"less_than",...J(e),value:t,inclusive:!1})}function ia(t,e){return new rf({check:"less_than",...J(e),value:t,inclusive:!0})}function Eu(t,e){return new of({check:"greater_than",...J(e),value:t,inclusive:!1})}function aa(t,e){return new of({check:"greater_than",...J(e),value:t,inclusive:!0})}function Tu(t,e){return new Lk({check:"multiple_of",...J(e),value:t})}function $u(t,e){return new Fk({check:"max_length",...J(e),maximum:t})}function Ns(t,e){return new Hk({check:"min_length",...J(e),minimum:t})}function Pu(t,e){return new Uk({check:"length_equals",...J(e),length:t})}function Eh(t,e){return new Bk({check:"string_format",format:"regex",...J(e),pattern:t})}function Th(t){return new Zk({check:"string_format",format:"lowercase",...J(t)})}function $h(t){return new qk({check:"string_format",format:"uppercase",...J(t)})}function Ph(t,e){return new Vk({check:"string_format",format:"includes",...J(e),includes:t})}function Rh(t,e){return new Wk({check:"string_format",format:"starts_with",...J(e),prefix:t})}function Ch(t,e){return new Kk({check:"string_format",format:"ends_with",...J(e),suffix:t})}function Do(t){return new Gk({check:"overwrite",tx:t})}function Oh(t){return Do(e=>e.normalize(t))}function Ih(){return Do(t=>t.trim())}function Ah(){return Do(t=>t.toLowerCase())}function Nh(){return Do(t=>t.toUpperCase())}function b0(t,e,n){return new t({type:"array",element:e,...J(n)})}function Dh(t,e,n){let r=J(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function Mh(t,e,n){return new t({type:"custom",check:"custom",fn:e,...J(n)})}var S0=v(()=>{gu();jn()});var v0=v(()=>{});function jh(t,e){if(t instanceof sa){let r=new Ru(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;r.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=r.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let n=new Ru(e);return n.process(t),n.emit(t,e)}function et(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let o=t._zod.def;switch(o.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 et(o.element,n);case"object":{for(let s in o.shape)if(et(o.shape[s],n))return!0;return!1}case"union":{for(let s of o.options)if(et(s,n))return!0;return!1}case"intersection":return et(o.left,n)||et(o.right,n);case"tuple":{for(let s of o.items)if(et(s,n))return!0;return!!(o.rest&&et(o.rest,n))}case"record":return et(o.keyType,n)||et(o.valueType,n);case"map":return et(o.keyType,n)||et(o.valueType,n);case"set":return et(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return et(o.innerType,n);case"lazy":return et(o.getter(),n);case"default":return et(o.innerType,n);case"prefault":return et(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return et(o.in,n)||et(o.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Ru,k0=v(()=>{Jf();jn();Ru=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Ir,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let h=a.schema;switch(o.type){case"string":{let m=h;m.type="string";let{minimum:f,maximum:g,format:y,patterns:_,contentEncoding:x}=e._zod.bag;if(typeof f=="number"&&(m.minLength=f),typeof g=="number"&&(m.maxLength=g),y&&(m.format=s[y]??y,m.format===""&&delete m.format),x&&(m.contentEncoding=x),_&&_.size>0){let S=[..._];S.length===1?m.pattern=S[0].source:S.length>1&&(a.schema.allOf=[...S.map(E=>({...this.target==="draft-7"?{type:"string"}:{},pattern:E.source}))])}break}case"number":{let m=h,{minimum:f,maximum:g,format:y,multipleOf:_,exclusiveMaximum:x,exclusiveMinimum:S}=e._zod.bag;typeof y=="string"&&y.includes("int")?m.type="integer":m.type="number",typeof S=="number"&&(m.exclusiveMinimum=S),typeof f=="number"&&(m.minimum=f,typeof S=="number"&&(S>=f?delete m.minimum:delete m.exclusiveMinimum)),typeof x=="number"&&(m.exclusiveMaximum=x),typeof g=="number"&&(m.maximum=g,typeof x=="number"&&(x<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof _=="number"&&(m.multipleOf=_);break}case"boolean":{let m=h;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=h,{minimum:f,maximum:g}=e._zod.bag;typeof f=="number"&&(m.minItems=f),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let m=h;m.type="object",m.properties={};let f=o.shape;for(let _ in f)m.properties[_]=this.process(f[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(f)),y=new Set([...g].filter(_=>{let x=o.shape[_]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));y.size>0&&(m.required=Array.from(y)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=h;m.anyOf=o.options.map((f,g)=>this.process(f,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let m=h,f=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=x=>"allOf"in x&&Object.keys(x).length===1,_=[...y(f)?f.allOf:[f],...y(g)?g.allOf:[g]];m.allOf=_;break}case"tuple":{let m=h;m.type="array";let f=o.items.map((_,x)=>this.process(_,{...d,path:[...d.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?m.prefixItems=f:m.items=f,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?m.items=_:m.additionalItems=_}o.rest&&(m.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof y=="number"&&(m.maxItems=y);break}case"record":{let m=h;m.type="object",m.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=h,f=Xi(o.entries);f.every(g=>typeof g=="number")&&(m.type="number"),f.every(g=>typeof g=="string")&&(m.type="string"),m.enum=f;break}case"literal":{let m=h,f=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");f.push(Number(g))}else f.push(g);if(f.length!==0)if(f.length===1){let g=f[0];m.type=g===null?"null":typeof g,m.const=g}else f.every(g=>typeof g=="number")&&(m.type="number"),f.every(g=>typeof g=="string")&&(m.type="string"),f.every(g=>typeof g=="boolean")&&(m.type="string"),f.every(g=>g===null)&&(m.type="null"),m.enum=f;break}case"file":{let m=h,f={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(f.minLength=g),y!==void 0&&(f.maxLength=y),_?_.length===1?(f.contentMediaType=_[0],Object.assign(m,f)):m.anyOf=_.map(x=>({...f,contentMediaType:x})):Object.assign(m,f);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,d);h.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let m=h;m.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=h,f=e._zod.pattern;if(!f)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=f.source;break}case"pipe":{let m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,d),a.ref=m;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,d),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&et(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,n){let r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){let f=r.external.registry.get(l[0])?.id,g=r.external.uri??(_=>_);if(f)return{ref:g(f)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===o)return{ref:"#"};let h=`#/${d}/`,m=l[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:h+m}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:p,defId:h}=s(l);d.def={...d.schema},h&&(d.defId=h);let m=d.schema;for(let f in m)delete m[f];m.$ref=p};if(r.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
485
|
+
|
|
486
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(r.external){let h=r.external.registry.get(l[0])?.id;if(e!==l[0]&&h){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&r.reused==="ref"){i(l);continue}}let a=(l,d)=>{let p=this.seen.get(l),h=p.def??p.schema,m={...h};if(p.ref===null)return;let f=p.ref;if(p.ref=null,f){a(f,d);let g=this.seen.get(f).schema;g.$ref&&d.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(g)):(Object.assign(h,g),Object.assign(h,m))}p.isParent||this.override({zodSchema:l,jsonSchema:h,path:p.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){let l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(l)}Object.assign(c,o.def);let u=r.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}r.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var w0=v(()=>{});var kt=v(()=>{Os();ef();Wm();p0();gu();af();jn();hu();vu();Jf();sf();v0();S0();k0();w0()});var Lh=v(()=>{kt()});function zh(t,e){let n={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new RM(n)}var PM,RM,E0=v(()=>{kt();kt();Lh();PM=$("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ve.init(t,e),t.def=e,t.parse=(n,r)=>Gm(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Ao(t,n,r),t.parseAsync=async(n,r)=>Xm(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>No(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Bt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))}),RM=$("ZodMiniObject",(t,e)=>{bu.init(t,e),PM.init(t,e),ue.defineLazy(t,"shape",()=>e.shape)})});var T0=v(()=>{});var $0=v(()=>{});var P0=v(()=>{});var R0=v(()=>{kt();Lh();E0();T0();kt();vu();$0();P0()});var C0=v(()=>{R0()});var Fh=v(()=>{C0()});function rn(t){return!!t._zod}function jo(t){let e=Object.values(t);if(e.length===0)return zh({});let n=e.every(rn),r=e.every(o=>!rn(o));if(n)return zh(t);if(r)return Nm(t);throw new Error("Mixed Zod versions detected in object shape.")}function Ar(t,e){return rn(t)?Ao(t,e):t.safeParse(e)}async function Cu(t,e){return rn(t)?await No(t,e):await t.safeParseAsync(e)}function Nr(t){if(!t)return;let e;if(rn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ds(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return jo(t)}}if(rn(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function Ou(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function I0(t){return t.description}function A0(t){if(rn(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Iu(t){if(rn(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var ca=v(()=>{Gi();Fh()});var Hh=v(()=>{kt()});var ua={};_e(ua,{ZodISODate:()=>D0,ZodISODateTime:()=>N0,ZodISODuration:()=>j0,ZodISOTime:()=>M0,date:()=>Bh,datetime:()=>Uh,duration:()=>qh,time:()=>Zh});function Uh(t){return g0(N0,t)}function Bh(t){return y0(D0,t)}function Zh(t){return _0(M0,t)}function qh(t){return x0(j0,t)}var N0,D0,M0,j0,Vh=v(()=>{kt();Wh();N0=$("ZodISODateTime",(t,e)=>{a0.init(t,e),Ne.init(t,e)});D0=$("ZodISODate",(t,e)=>{c0.init(t,e),Ne.init(t,e)});M0=$("ZodISOTime",(t,e)=>{u0.init(t,e),Ne.init(t,e)});j0=$("ZodISODuration",(t,e)=>{l0.init(t,e),Ne.init(t,e)})});var L0,W5,la,Kh=v(()=>{kt();kt();L0=(t,e)=>{mu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Vm(t,n)},flatten:{value:n=>qm(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},W5=$("ZodError",L0),la=$("ZodError",L0,{Parent:Error})});var z0,F0,H0,U0,Gh=v(()=>{kt();Kh();z0=Km(la),F0=Jm(la),H0=Ym(la),U0=Qm(la)});function w(t){return Xf(zM,t)}function ye(t){return xh(W0,t)}function Z0(t){return bh(rj,t)}function ot(t){return Sh(oj,t)}function K0(t){return vh(sj,t)}function De(){return kh(ij)}function cj(t){return wh(aj,t)}function le(t,e){return b0(uj,t,e)}function H(t,e){let n={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new G0(n)}function wt(t,e){return new G0({type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},catchall:De(),...ue.normalizeParams(e)})}function Ce(t,e){return new J0({type:"union",options:t,...ue.normalizeParams(e)})}function Yh(t,e,n){return new lj({type:"union",options:e,discriminator:t,...ue.normalizeParams(n)})}function Nu(t,e){return new dj({type:"intersection",left:t,right:e})}function $e(t,e,n){return new pj({type:"record",keyType:t,valueType:e,...ue.normalizeParams(n)})}function It(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Jh({type:"enum",entries:n,...ue.normalizeParams(e)})}function q(t,e){return new mj({type:"literal",values:Array.isArray(t)?t:[t],...ue.normalizeParams(e)})}function X0(t){return new fj({type:"transform",transform:t})}function Me(t){return new Y0({type:"optional",innerType:t})}function q0(t){return new hj({type:"nullable",innerType:t})}function yj(t,e){return new gj({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function xj(t,e){return new _j({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function bj(t,e){return new Q0({type:"nonoptional",innerType:t,...ue.normalizeParams(e)})}function vj(t,e){return new Sj({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Xh(t,e){return new kj({type:"pipe",in:t,out:e})}function Ej(t){return new wj({type:"readonly",innerType:t})}function Tj(t){let e=new ct({check:"custom"});return e._zod.check=t,e}function tw(t,e){return Dh(ew,t??(()=>!0),e)}function $j(t,e={}){return Mh(ew,t,e)}function Pj(t){let e=Tj(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ue.issue(r,n.value,e._zod.def));else{let o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),n.issues.push(ue.issue(o))}},t(n.value,n)));return e}function Qh(t,e){return Xh(X0(t),e)}var He,V0,zM,Ne,FM,B0,Au,HM,UM,BM,ZM,qM,VM,WM,KM,GM,JM,XM,YM,QM,ej,tj,nj,W0,rj,oj,sj,ij,aj,uj,G0,J0,lj,dj,pj,Jh,mj,fj,Y0,hj,gj,_j,Q0,Sj,kj,wj,ew,Wh=v(()=>{kt();kt();Hh();Vh();Gh();He=$("ZodType",(t,e)=>(ve.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Bt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>z0(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>H0(t,n,r),t.parseAsync=async(n,r)=>F0(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>U0(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check($j(n,r)),t.superRefine=n=>t.check(Pj(n)),t.overwrite=n=>t.check(Do(n)),t.optional=()=>Me(t),t.nullable=()=>q0(t),t.nullish=()=>Me(q0(t)),t.nonoptional=n=>bj(t,n),t.array=()=>le(t),t.or=n=>Ce([t,n]),t.and=n=>Nu(t,n),t.transform=n=>Xh(t,X0(n)),t.default=n=>yj(t,n),t.prefault=n=>xj(t,n),t.catch=n=>vj(t,n),t.pipe=n=>Xh(t,n),t.readonly=()=>Ej(t),t.describe=n=>{let r=t.clone();return Ir.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Ir.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Ir.get(t);let r=t.clone();return Ir.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),V0=$("_ZodString",(t,e)=>{oa.init(t,e),He.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(Eh(...r)),t.includes=(...r)=>t.check(Ph(...r)),t.startsWith=(...r)=>t.check(Rh(...r)),t.endsWith=(...r)=>t.check(Ch(...r)),t.min=(...r)=>t.check(Ns(...r)),t.max=(...r)=>t.check($u(...r)),t.length=(...r)=>t.check(Pu(...r)),t.nonempty=(...r)=>t.check(Ns(1,...r)),t.lowercase=r=>t.check(Th(r)),t.uppercase=r=>t.check($h(r)),t.trim=()=>t.check(Ih()),t.normalize=(...r)=>t.check(Oh(...r)),t.toLowerCase=()=>t.check(Ah()),t.toUpperCase=()=>t.check(Nh())}),zM=$("ZodString",(t,e)=>{oa.init(t,e),V0.init(t,e),t.email=n=>t.check(Yf(FM,n)),t.url=n=>t.check(rh(HM,n)),t.jwt=n=>t.check(_h(nj,n)),t.emoji=n=>t.check(oh(UM,n)),t.guid=n=>t.check(ku(B0,n)),t.uuid=n=>t.check(Qf(Au,n)),t.uuidv4=n=>t.check(eh(Au,n)),t.uuidv6=n=>t.check(th(Au,n)),t.uuidv7=n=>t.check(nh(Au,n)),t.nanoid=n=>t.check(sh(BM,n)),t.guid=n=>t.check(ku(B0,n)),t.cuid=n=>t.check(ih(ZM,n)),t.cuid2=n=>t.check(ah(qM,n)),t.ulid=n=>t.check(ch(VM,n)),t.base64=n=>t.check(hh(QM,n)),t.base64url=n=>t.check(gh(ej,n)),t.xid=n=>t.check(uh(WM,n)),t.ksuid=n=>t.check(lh(KM,n)),t.ipv4=n=>t.check(dh(GM,n)),t.ipv6=n=>t.check(ph(JM,n)),t.cidrv4=n=>t.check(mh(XM,n)),t.cidrv6=n=>t.check(fh(YM,n)),t.e164=n=>t.check(yh(tj,n)),t.datetime=n=>t.check(Uh(n)),t.date=n=>t.check(Bh(n)),t.time=n=>t.check(Zh(n)),t.duration=n=>t.check(qh(n))});Ne=$("ZodStringFormat",(t,e)=>{Te.init(t,e),V0.init(t,e)}),FM=$("ZodEmail",(t,e)=>{df.init(t,e),Ne.init(t,e)}),B0=$("ZodGUID",(t,e)=>{uf.init(t,e),Ne.init(t,e)}),Au=$("ZodUUID",(t,e)=>{lf.init(t,e),Ne.init(t,e)}),HM=$("ZodURL",(t,e)=>{pf.init(t,e),Ne.init(t,e)}),UM=$("ZodEmoji",(t,e)=>{mf.init(t,e),Ne.init(t,e)}),BM=$("ZodNanoID",(t,e)=>{ff.init(t,e),Ne.init(t,e)}),ZM=$("ZodCUID",(t,e)=>{hf.init(t,e),Ne.init(t,e)}),qM=$("ZodCUID2",(t,e)=>{gf.init(t,e),Ne.init(t,e)}),VM=$("ZodULID",(t,e)=>{yf.init(t,e),Ne.init(t,e)}),WM=$("ZodXID",(t,e)=>{_f.init(t,e),Ne.init(t,e)}),KM=$("ZodKSUID",(t,e)=>{xf.init(t,e),Ne.init(t,e)}),GM=$("ZodIPv4",(t,e)=>{bf.init(t,e),Ne.init(t,e)}),JM=$("ZodIPv6",(t,e)=>{Sf.init(t,e),Ne.init(t,e)}),XM=$("ZodCIDRv4",(t,e)=>{vf.init(t,e),Ne.init(t,e)}),YM=$("ZodCIDRv6",(t,e)=>{kf.init(t,e),Ne.init(t,e)}),QM=$("ZodBase64",(t,e)=>{wf.init(t,e),Ne.init(t,e)}),ej=$("ZodBase64URL",(t,e)=>{Ef.init(t,e),Ne.init(t,e)}),tj=$("ZodE164",(t,e)=>{Tf.init(t,e),Ne.init(t,e)}),nj=$("ZodJWT",(t,e)=>{$f.init(t,e),Ne.init(t,e)}),W0=$("ZodNumber",(t,e)=>{xu.init(t,e),He.init(t,e),t.gt=(r,o)=>t.check(Eu(r,o)),t.gte=(r,o)=>t.check(aa(r,o)),t.min=(r,o)=>t.check(aa(r,o)),t.lt=(r,o)=>t.check(wu(r,o)),t.lte=(r,o)=>t.check(ia(r,o)),t.max=(r,o)=>t.check(ia(r,o)),t.int=r=>t.check(Z0(r)),t.safe=r=>t.check(Z0(r)),t.positive=r=>t.check(Eu(0,r)),t.nonnegative=r=>t.check(aa(0,r)),t.negative=r=>t.check(wu(0,r)),t.nonpositive=r=>t.check(ia(0,r)),t.multipleOf=(r,o)=>t.check(Tu(r,o)),t.step=(r,o)=>t.check(Tu(r,o)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});rj=$("ZodNumberFormat",(t,e)=>{Pf.init(t,e),W0.init(t,e)});oj=$("ZodBoolean",(t,e)=>{Rf.init(t,e),He.init(t,e)});sj=$("ZodNull",(t,e)=>{Cf.init(t,e),He.init(t,e)});ij=$("ZodUnknown",(t,e)=>{Of.init(t,e),He.init(t,e)});aj=$("ZodNever",(t,e)=>{If.init(t,e),He.init(t,e)});uj=$("ZodArray",(t,e)=>{Af.init(t,e),He.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Ns(n,r)),t.nonempty=n=>t.check(Ns(1,n)),t.max=(n,r)=>t.check($u(n,r)),t.length=(n,r)=>t.check(Pu(n,r)),t.unwrap=()=>t.element});G0=$("ZodObject",(t,e)=>{bu.init(t,e),He.init(t,e),ue.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>It(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:De()}),t.loose=()=>t.clone({...t._zod.def,catchall:De()}),t.strict=()=>t.clone({...t._zod.def,catchall:cj()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>ue.extend(t,n),t.merge=n=>ue.merge(t,n),t.pick=n=>ue.pick(t,n),t.omit=n=>ue.omit(t,n),t.partial=(...n)=>ue.partial(Y0,t,n[0]),t.required=(...n)=>ue.required(Q0,t,n[0])});J0=$("ZodUnion",(t,e)=>{Su.init(t,e),He.init(t,e),t.options=e.options});lj=$("ZodDiscriminatedUnion",(t,e)=>{J0.init(t,e),Nf.init(t,e)});dj=$("ZodIntersection",(t,e)=>{Df.init(t,e),He.init(t,e)});pj=$("ZodRecord",(t,e)=>{Mf.init(t,e),He.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Jh=$("ZodEnum",(t,e)=>{jf.init(t,e),He.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Jh({...e,checks:[],...ue.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Jh({...e,checks:[],...ue.normalizeParams(o),entries:s})}});mj=$("ZodLiteral",(t,e)=>{Lf.init(t,e),He.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});fj=$("ZodTransform",(t,e)=>{zf.init(t,e),He.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(ue.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(ue.issue(i))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});Y0=$("ZodOptional",(t,e)=>{Ff.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});hj=$("ZodNullable",(t,e)=>{Hf.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});gj=$("ZodDefault",(t,e)=>{Uf.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});_j=$("ZodPrefault",(t,e)=>{Bf.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});Q0=$("ZodNonOptional",(t,e)=>{Zf.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});Sj=$("ZodCatch",(t,e)=>{qf.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});kj=$("ZodPipe",(t,e)=>{Vf.init(t,e),He.init(t,e),t.in=e.in,t.out=e.out});wj=$("ZodReadonly",(t,e)=>{Wf.init(t,e),He.init(t,e)});ew=$("ZodCustom",(t,e)=>{Kf.init(t,e),He.init(t,e)})});var nw=v(()=>{});var rw=v(()=>{});var ow=v(()=>{kt();Wh();Hh();Kh();Gh();nw();kt();f0();vu();Vh();rw();Ut(m0())});var sw=v(()=>{ow()});var iw=v(()=>{sw()});function kw(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function ww(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var tg,aw,Dr,Mu,tt,cw,uw,uK,Oj,Ij,ng,Zt,da,lw,ut,on,sn,lt,ju,dw,rg,pw,mw,og,pa,K,sg,fw,hw,lK,Lu,Aj,zu,Nj,ma,Ms,gw,Dj,Mj,jj,Lj,zj,Fj,ig,Hj,Uj,ag,Fu,Bj,Zj,Hu,qj,fa,ha,Vj,ga,js,Wj,ya,Uu,Bu,Zu,dK,qu,Vu,Wu,yw,_w,xw,cg,bw,_a,Ls,Sw,Kj,zs,Gj,Fs,Jj,ug,Xj,Ku,Yj,Qj,eL,tL,nL,rL,oL,sL,iL,aL,Hs,cL,uL,Gu,lg,dg,pg,lL,dL,pL,mg,mL,fL,hL,gL,yL,vw,Lo,_L,Ju,pK,xL,Us,bL,mK,xa,SL,fg,vL,kL,wL,EL,TL,$L,PL,Du,RL,CL,OL,ba,hg,IL,AL,NL,DL,ML,jL,LL,zL,FL,HL,UL,BL,ZL,qL,VL,WL,KL,GL,Bs,JL,XL,YL,Xu,QL,ez,tz,gg,nz,fK,hK,gK,yK,_K,xK,Z,eg,zo=v(()=>{iw();tg="2025-11-25",aw=[tg,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Dr="io.modelcontextprotocol/related-task",Mu="2.0",tt=tw(t=>t!==null&&(typeof t=="object"||typeof t=="function")),cw=Ce([w(),ye().int()]),uw=w(),uK=wt({ttl:ye().optional(),pollInterval:ye().optional()}),Oj=H({ttl:ye().optional()}),Ij=H({taskId:w()}),ng=wt({progressToken:cw.optional(),[Dr]:Ij.optional()}),Zt=H({_meta:ng.optional()}),da=Zt.extend({task:Oj.optional()}),lw=t=>da.safeParse(t).success,ut=H({method:w(),params:Zt.loose().optional()}),on=H({_meta:ng.optional()}),sn=H({method:w(),params:on.loose().optional()}),lt=wt({_meta:ng.optional()}),ju=Ce([w(),ye().int()]),dw=H({jsonrpc:q(Mu),id:ju,...ut.shape}).strict(),rg=t=>dw.safeParse(t).success,pw=H({jsonrpc:q(Mu),...sn.shape}).strict(),mw=t=>pw.safeParse(t).success,og=H({jsonrpc:q(Mu),id:ju,result:lt}).strict(),pa=t=>og.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(K||(K={}));sg=H({jsonrpc:q(Mu),id:ju.optional(),error:H({code:ye().int(),message:w(),data:De().optional()})}).strict(),fw=t=>sg.safeParse(t).success,hw=Ce([dw,pw,og,sg]),lK=Ce([og,sg]),Lu=lt.strict(),Aj=on.extend({requestId:ju.optional(),reason:w().optional()}),zu=sn.extend({method:q("notifications/cancelled"),params:Aj}),Nj=H({src:w(),mimeType:w().optional(),sizes:le(w()).optional(),theme:It(["light","dark"]).optional()}),ma=H({icons:le(Nj).optional()}),Ms=H({name:w(),title:w().optional()}),gw=Ms.extend({...Ms.shape,...ma.shape,version:w(),websiteUrl:w().optional(),description:w().optional()}),Dj=Nu(H({applyDefaults:ot().optional()}),$e(w(),De())),Mj=Qh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Nu(H({form:Dj.optional(),url:tt.optional()}),$e(w(),De()).optional())),jj=wt({list:tt.optional(),cancel:tt.optional(),requests:wt({sampling:wt({createMessage:tt.optional()}).optional(),elicitation:wt({create:tt.optional()}).optional()}).optional()}),Lj=wt({list:tt.optional(),cancel:tt.optional(),requests:wt({tools:wt({call:tt.optional()}).optional()}).optional()}),zj=H({experimental:$e(w(),tt).optional(),sampling:H({context:tt.optional(),tools:tt.optional()}).optional(),elicitation:Mj.optional(),roots:H({listChanged:ot().optional()}).optional(),tasks:jj.optional(),extensions:$e(w(),tt).optional()}),Fj=Zt.extend({protocolVersion:w(),capabilities:zj,clientInfo:gw}),ig=ut.extend({method:q("initialize"),params:Fj}),Hj=H({experimental:$e(w(),tt).optional(),logging:tt.optional(),completions:tt.optional(),prompts:H({listChanged:ot().optional()}).optional(),resources:H({subscribe:ot().optional(),listChanged:ot().optional()}).optional(),tools:H({listChanged:ot().optional()}).optional(),tasks:Lj.optional(),extensions:$e(w(),tt).optional()}),Uj=lt.extend({protocolVersion:w(),capabilities:Hj,serverInfo:gw,instructions:w().optional()}),ag=sn.extend({method:q("notifications/initialized"),params:on.optional()}),Fu=ut.extend({method:q("ping"),params:Zt.optional()}),Bj=H({progress:ye(),total:Me(ye()),message:Me(w())}),Zj=H({...on.shape,...Bj.shape,progressToken:cw}),Hu=sn.extend({method:q("notifications/progress"),params:Zj}),qj=Zt.extend({cursor:uw.optional()}),fa=ut.extend({params:qj.optional()}),ha=lt.extend({nextCursor:uw.optional()}),Vj=It(["working","input_required","completed","failed","cancelled"]),ga=H({taskId:w(),status:Vj,ttl:Ce([ye(),K0()]),createdAt:w(),lastUpdatedAt:w(),pollInterval:Me(ye()),statusMessage:Me(w())}),js=lt.extend({task:ga}),Wj=on.merge(ga),ya=sn.extend({method:q("notifications/tasks/status"),params:Wj}),Uu=ut.extend({method:q("tasks/get"),params:Zt.extend({taskId:w()})}),Bu=lt.merge(ga),Zu=ut.extend({method:q("tasks/result"),params:Zt.extend({taskId:w()})}),dK=lt.loose(),qu=fa.extend({method:q("tasks/list")}),Vu=ha.extend({tasks:le(ga)}),Wu=ut.extend({method:q("tasks/cancel"),params:Zt.extend({taskId:w()})}),yw=lt.merge(ga),_w=H({uri:w(),mimeType:Me(w()),_meta:$e(w(),De()).optional()}),xw=_w.extend({text:w()}),cg=w().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),bw=_w.extend({blob:cg}),_a=It(["user","assistant"]),Ls=H({audience:le(_a).optional(),priority:ye().min(0).max(1).optional(),lastModified:ua.datetime({offset:!0}).optional()}),Sw=H({...Ms.shape,...ma.shape,uri:w(),description:Me(w()),mimeType:Me(w()),size:Me(ye()),annotations:Ls.optional(),_meta:Me(wt({}))}),Kj=H({...Ms.shape,...ma.shape,uriTemplate:w(),description:Me(w()),mimeType:Me(w()),annotations:Ls.optional(),_meta:Me(wt({}))}),zs=fa.extend({method:q("resources/list")}),Gj=ha.extend({resources:le(Sw)}),Fs=fa.extend({method:q("resources/templates/list")}),Jj=ha.extend({resourceTemplates:le(Kj)}),ug=Zt.extend({uri:w()}),Xj=ug,Ku=ut.extend({method:q("resources/read"),params:Xj}),Yj=lt.extend({contents:le(Ce([xw,bw]))}),Qj=sn.extend({method:q("notifications/resources/list_changed"),params:on.optional()}),eL=ug,tL=ut.extend({method:q("resources/subscribe"),params:eL}),nL=ug,rL=ut.extend({method:q("resources/unsubscribe"),params:nL}),oL=on.extend({uri:w()}),sL=sn.extend({method:q("notifications/resources/updated"),params:oL}),iL=H({name:w(),description:Me(w()),required:Me(ot())}),aL=H({...Ms.shape,...ma.shape,description:Me(w()),arguments:Me(le(iL)),_meta:Me(wt({}))}),Hs=fa.extend({method:q("prompts/list")}),cL=ha.extend({prompts:le(aL)}),uL=Zt.extend({name:w(),arguments:$e(w(),w()).optional()}),Gu=ut.extend({method:q("prompts/get"),params:uL}),lg=H({type:q("text"),text:w(),annotations:Ls.optional(),_meta:$e(w(),De()).optional()}),dg=H({type:q("image"),data:cg,mimeType:w(),annotations:Ls.optional(),_meta:$e(w(),De()).optional()}),pg=H({type:q("audio"),data:cg,mimeType:w(),annotations:Ls.optional(),_meta:$e(w(),De()).optional()}),lL=H({type:q("tool_use"),name:w(),id:w(),input:$e(w(),De()),_meta:$e(w(),De()).optional()}),dL=H({type:q("resource"),resource:Ce([xw,bw]),annotations:Ls.optional(),_meta:$e(w(),De()).optional()}),pL=Sw.extend({type:q("resource_link")}),mg=Ce([lg,dg,pg,pL,dL]),mL=H({role:_a,content:mg}),fL=lt.extend({description:w().optional(),messages:le(mL)}),hL=sn.extend({method:q("notifications/prompts/list_changed"),params:on.optional()}),gL=H({title:w().optional(),readOnlyHint:ot().optional(),destructiveHint:ot().optional(),idempotentHint:ot().optional(),openWorldHint:ot().optional()}),yL=H({taskSupport:It(["required","optional","forbidden"]).optional()}),vw=H({...Ms.shape,...ma.shape,description:w().optional(),inputSchema:H({type:q("object"),properties:$e(w(),tt).optional(),required:le(w()).optional()}).catchall(De()),outputSchema:H({type:q("object"),properties:$e(w(),tt).optional(),required:le(w()).optional()}).catchall(De()).optional(),annotations:gL.optional(),execution:yL.optional(),_meta:$e(w(),De()).optional()}),Lo=fa.extend({method:q("tools/list")}),_L=ha.extend({tools:le(vw)}),Ju=lt.extend({content:le(mg).default([]),structuredContent:$e(w(),De()).optional(),isError:ot().optional()}),pK=Ju.or(lt.extend({toolResult:De()})),xL=da.extend({name:w(),arguments:$e(w(),De()).optional()}),Us=ut.extend({method:q("tools/call"),params:xL}),bL=sn.extend({method:q("notifications/tools/list_changed"),params:on.optional()}),mK=H({autoRefresh:ot().default(!0),debounceMs:ye().int().nonnegative().default(300)}),xa=It(["debug","info","notice","warning","error","critical","alert","emergency"]),SL=Zt.extend({level:xa}),fg=ut.extend({method:q("logging/setLevel"),params:SL}),vL=on.extend({level:xa,logger:w().optional(),data:De()}),kL=sn.extend({method:q("notifications/message"),params:vL}),wL=H({name:w().optional()}),EL=H({hints:le(wL).optional(),costPriority:ye().min(0).max(1).optional(),speedPriority:ye().min(0).max(1).optional(),intelligencePriority:ye().min(0).max(1).optional()}),TL=H({mode:It(["auto","required","none"]).optional()}),$L=H({type:q("tool_result"),toolUseId:w().describe("The unique identifier for the corresponding tool call."),content:le(mg).default([]),structuredContent:H({}).loose().optional(),isError:ot().optional(),_meta:$e(w(),De()).optional()}),PL=Yh("type",[lg,dg,pg]),Du=Yh("type",[lg,dg,pg,lL,$L]),RL=H({role:_a,content:Ce([Du,le(Du)]),_meta:$e(w(),De()).optional()}),CL=da.extend({messages:le(RL),modelPreferences:EL.optional(),systemPrompt:w().optional(),includeContext:It(["none","thisServer","allServers"]).optional(),temperature:ye().optional(),maxTokens:ye().int(),stopSequences:le(w()).optional(),metadata:tt.optional(),tools:le(vw).optional(),toolChoice:TL.optional()}),OL=ut.extend({method:q("sampling/createMessage"),params:CL}),ba=lt.extend({model:w(),stopReason:Me(It(["endTurn","stopSequence","maxTokens"]).or(w())),role:_a,content:PL}),hg=lt.extend({model:w(),stopReason:Me(It(["endTurn","stopSequence","maxTokens","toolUse"]).or(w())),role:_a,content:Ce([Du,le(Du)])}),IL=H({type:q("boolean"),title:w().optional(),description:w().optional(),default:ot().optional()}),AL=H({type:q("string"),title:w().optional(),description:w().optional(),minLength:ye().optional(),maxLength:ye().optional(),format:It(["email","uri","date","date-time"]).optional(),default:w().optional()}),NL=H({type:It(["number","integer"]),title:w().optional(),description:w().optional(),minimum:ye().optional(),maximum:ye().optional(),default:ye().optional()}),DL=H({type:q("string"),title:w().optional(),description:w().optional(),enum:le(w()),default:w().optional()}),ML=H({type:q("string"),title:w().optional(),description:w().optional(),oneOf:le(H({const:w(),title:w()})),default:w().optional()}),jL=H({type:q("string"),title:w().optional(),description:w().optional(),enum:le(w()),enumNames:le(w()).optional(),default:w().optional()}),LL=Ce([DL,ML]),zL=H({type:q("array"),title:w().optional(),description:w().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:H({type:q("string"),enum:le(w())}),default:le(w()).optional()}),FL=H({type:q("array"),title:w().optional(),description:w().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:H({anyOf:le(H({const:w(),title:w()}))}),default:le(w()).optional()}),HL=Ce([zL,FL]),UL=Ce([jL,LL,HL]),BL=Ce([UL,IL,AL,NL]),ZL=da.extend({mode:q("form").optional(),message:w(),requestedSchema:H({type:q("object"),properties:$e(w(),BL),required:le(w()).optional()})}),qL=da.extend({mode:q("url"),message:w(),elicitationId:w(),url:w().url()}),VL=Ce([ZL,qL]),WL=ut.extend({method:q("elicitation/create"),params:VL}),KL=on.extend({elicitationId:w()}),GL=sn.extend({method:q("notifications/elicitation/complete"),params:KL}),Bs=lt.extend({action:It(["accept","decline","cancel"]),content:Qh(t=>t===null?void 0:t,$e(w(),Ce([w(),ye(),ot(),le(w())])).optional())}),JL=H({type:q("ref/resource"),uri:w()}),XL=H({type:q("ref/prompt"),name:w()}),YL=Zt.extend({ref:Ce([XL,JL]),argument:H({name:w(),value:w()}),context:H({arguments:$e(w(),w()).optional()}).optional()}),Xu=ut.extend({method:q("completion/complete"),params:YL});QL=lt.extend({completion:wt({values:le(w()).max(100),total:Me(ye().int()),hasMore:Me(ot())})}),ez=H({uri:w().startsWith("file://"),name:w().optional(),_meta:$e(w(),De()).optional()}),tz=ut.extend({method:q("roots/list"),params:Zt.optional()}),gg=lt.extend({roots:le(ez)}),nz=sn.extend({method:q("notifications/roots/list_changed"),params:on.optional()}),fK=Ce([Fu,ig,Xu,fg,Gu,Hs,zs,Fs,Ku,tL,rL,Us,Lo,Uu,Zu,qu,Wu]),hK=Ce([zu,Hu,ag,nz,ya]),gK=Ce([Lu,ba,hg,Bs,gg,Bu,Vu,js]),yK=Ce([Fu,OL,WL,tz,Uu,Zu,qu,Wu]),_K=Ce([zu,Hu,kL,sL,Qj,bL,hL,ya,GL]),xK=Ce([Lu,Uj,QL,fL,cL,Gj,Jj,Yj,Ju,_L,Bu,Vu,js]),Z=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===K.UrlElicitationRequired&&r){let o=r;if(o.elicitations)return new eg(o.elicitations,n)}return new t(e,n,r)}},eg=class extends Z{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(K.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Mr(t){return t==="completed"||t==="failed"||t==="cancelled"}var Ew=v(()=>{});var $w,Tw,Pw,Yu=v(()=>{$w=Symbol("Let zodToJsonSchema decide on which parser to use"),Tw={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Pw=t=>typeof t=="string"?{...Tw,name:t}:{...Tw,...t}});var Rw,yg=v(()=>{Yu();Rw=t=>{let e=Pw(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});function _g(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function de(t,e,n,r,o){t[e]=n,_g(t,e,r,o)}var jr=v(()=>{});var Qu,el=v(()=>{Qu=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")}});function je(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Qu(e,t.currentPath):e.join("/")}}var an=v(()=>{el()});function Cw(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(n.items=X(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(n,"minItems",t.exactLength.value,t.exactLength.message,e),de(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var xg=v(()=>{Gi();jr();Je()});function Ow(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?de(n,"minimum",r.value,r.message,e):de(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),de(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?de(n,"maximum",r.value,r.message,e):de(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),de(n,"maximum",r.value,r.message,e));break;case"multipleOf":de(n,"multipleOf",r.value,r.message,e);break}return n}var bg=v(()=>{jr()});function Iw(){return{type:"boolean"}}var Sg=v(()=>{});function tl(t,e){return X(t.type._def,e)}var nl=v(()=>{Je()});var Aw,vg=v(()=>{Je();Aw=(t,e)=>X(t.innerType._def,e)});function kg(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>kg(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return rz(t,e)}}var rz,wg=v(()=>{jr();rz=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":de(n,"minimum",r.value,r.message,e);break;case"max":de(n,"maximum",r.value,r.message,e);break}return n}});function Nw(t,e){return{...X(t.innerType._def,e),default:t.defaultValue()}}var Eg=v(()=>{Je()});function Dw(t,e){return e.effectStrategy==="input"?X(t.schema._def,e):je(e)}var Tg=v(()=>{Je();an()});function Mw(t){return{type:"string",enum:Array.from(t.values)}}var $g=v(()=>{});function jw(t,e){let n=[X(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),X(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(s=>{if(oz(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else r=void 0;o.push(i)}}),o.length?{allOf:o,...r}:void 0}var oz,Pg=v(()=>{Je();oz=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Lw(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var Rg=v(()=>{});function rl(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":de(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":de(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":yn(n,"email",r.message,e);break;case"format:idn-email":yn(n,"idn-email",r.message,e);break;case"pattern:zod":Et(n,gn.email,r.message,e);break}break;case"url":yn(n,"uri",r.message,e);break;case"uuid":yn(n,"uuid",r.message,e);break;case"regex":Et(n,r.regex,r.message,e);break;case"cuid":Et(n,gn.cuid,r.message,e);break;case"cuid2":Et(n,gn.cuid2,r.message,e);break;case"startsWith":Et(n,RegExp(`^${Og(r.value,e)}`),r.message,e);break;case"endsWith":Et(n,RegExp(`${Og(r.value,e)}$`),r.message,e);break;case"datetime":yn(n,"date-time",r.message,e);break;case"date":yn(n,"date",r.message,e);break;case"time":yn(n,"time",r.message,e);break;case"duration":yn(n,"duration",r.message,e);break;case"length":de(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),de(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Et(n,RegExp(Og(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&yn(n,"ipv4",r.message,e),r.version!=="v4"&&yn(n,"ipv6",r.message,e);break}case"base64url":Et(n,gn.base64url,r.message,e);break;case"jwt":Et(n,gn.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Et(n,gn.ipv4Cidr,r.message,e),r.version!=="v4"&&Et(n,gn.ipv6Cidr,r.message,e);break}case"emoji":Et(n,gn.emoji(),r.message,e);break;case"ulid":{Et(n,gn.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{yn(n,"binary",r.message,e);break}case"contentEncoding:base64":{de(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Et(n,gn.base64,r.message,e);break}}break}case"nanoid":Et(n,gn.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Og(t,e){return e.patternStrategy==="escape"?iz(t):t}function iz(t){let e="";for(let n=0;n<t.length;n++)sz.has(t[n])||(e+="\\"),e+=t[n];return e}function yn(t,e,n,r){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):de(t,"format",e,n,r)}function Et(t,e,n,r){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:zw(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):de(t,"pattern",zw(e,r),n,r)}function zw(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<r.length;c++){if(s){o+=r[c],s=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){a?(o+=r[c],o+=`${r[c-2]}-${r[c]}`.toUpperCase(),a=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(o+=r[c],a=!0):o+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){o+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){o+=`(^|(?<=[\r
|
|
487
|
+
]))`;continue}else if(r[c]==="$"){o+=`($|(?=[\r
|
|
488
|
+
]))`;continue}}if(n.s&&r[c]==="."){o+=i?`${r[c]}\r
|
|
489
|
+
`:`[${r[c]}\r
|
|
490
|
+
]`;continue}o+=r[c],r[c]==="\\"?s=!0:i&&r[c]==="]"?i=!1:!i&&r[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var Cg,gn,sz,ol=v(()=>{jr();gn={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:()=>(Cg===void 0&&(Cg=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Cg),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-_]*$/};sz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function sl(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??je(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=rl(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=tl(t.keyType._def,e);return{...n,propertyNames:o}}}return n}var il=v(()=>{Gi();Je();ol();nl();an()});function Fw(t,e){if(e.mapStrategy==="record")return sl(t,e);let n=X(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||je(e),r=X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||je(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var Ig=v(()=>{Je();il();an()});function Hw(t){let e=t.values,r=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}var Ag=v(()=>{});function Uw(t){return t.target==="openAi"?void 0:{not:je({...t,currentPath:[...t.currentPath,"not"]})}}var Ng=v(()=>{an()});function Bw(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Dg=v(()=>{});function qw(t,e){if(e.target==="openApi3")return Zw(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Sa&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,s)=>{let i=Sa[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(r.length===n.length){let o=r.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:n.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return Zw(t,e)}var Sa,Zw,al=v(()=>{Je();Sa={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Zw=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>X(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function Vw(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Sa[t.innerType._def.typeName],nullable:!0}:{type:[Sa[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var Mg=v(()=>{Je();al()});function Ww(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",_g(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?de(n,"minimum",r.value,r.message,e):de(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),de(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?de(n,"maximum",r.value,r.message,e):de(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),de(n,"maximum",r.value,r.message,e));break;case"multipleOf":de(n,"multipleOf",r.value,r.message,e);break}return n}var jg=v(()=>{jr()});function Kw(t,e){let n=e.target==="openAi",r={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=cz(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=X(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(r.properties[a]=l,u||o.push(a))}o.length&&(r.required=o);let i=az(t,e);return i!==void 0&&(r.additionalProperties=i),r}function az(t,e){if(t.catchall._def.typeName!=="ZodNever")return X(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function cz(t){try{return t.isOptional()}catch{return!0}}var Lg=v(()=>{Je()});var Gw,zg=v(()=>{Je();an();Gw=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return X(t.innerType._def,e);let n=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:je(e)},n]}:je(e)}});var Jw,Fg=v(()=>{Je();Jw=(t,e)=>{if(e.pipeStrategy==="input")return X(t.in._def,e);if(e.pipeStrategy==="output")return X(t.out._def,e);let n=X(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=X(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}}});function Xw(t,e){return X(t.type._def,e)}var Hg=v(()=>{Je()});function Yw(t,e){let r={type:"array",uniqueItems:!0,items:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var Ug=v(()=>{jr();Je()});function Qw(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>X(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:X(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>X(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var Bg=v(()=>{Je()});function eE(t){return{not:je(t)}}var Zg=v(()=>{an()});function tE(t){return je(t)}var qg=v(()=>{an()});var nE,Vg=v(()=>{Je();nE=(t,e)=>X(t.innerType._def,e)});var rE,Wg=v(()=>{Gi();an();xg();bg();Sg();nl();vg();wg();Eg();Tg();$g();Pg();Rg();Ig();Ag();Ng();Dg();Mg();jg();Lg();zg();Fg();Hg();il();Ug();ol();Bg();Zg();al();qg();Vg();rE=(t,e,n)=>{switch(e){case D.ZodString:return rl(t,n);case D.ZodNumber:return Ww(t,n);case D.ZodObject:return Kw(t,n);case D.ZodBigInt:return Ow(t,n);case D.ZodBoolean:return Iw();case D.ZodDate:return kg(t,n);case D.ZodUndefined:return eE(n);case D.ZodNull:return Bw(n);case D.ZodArray:return Cw(t,n);case D.ZodUnion:case D.ZodDiscriminatedUnion:return qw(t,n);case D.ZodIntersection:return jw(t,n);case D.ZodTuple:return Qw(t,n);case D.ZodRecord:return sl(t,n);case D.ZodLiteral:return Lw(t,n);case D.ZodEnum:return Mw(t);case D.ZodNativeEnum:return Hw(t);case D.ZodNullable:return Vw(t,n);case D.ZodOptional:return Gw(t,n);case D.ZodMap:return Fw(t,n);case D.ZodSet:return Yw(t,n);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return Xw(t,n);case D.ZodNaN:case D.ZodNever:return Uw(n);case D.ZodEffects:return Dw(t,n);case D.ZodAny:return je(n);case D.ZodUnknown:return tE(n);case D.ZodDefault:return Nw(t,n);case D.ZodBranded:return tl(t,n);case D.ZodReadonly:return nE(t,n);case D.ZodCatch:return Aw(t,n);case D.ZodPipeline:return Jw(t,n);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(r=>{})(e)}}});function X(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==$w)return a}if(r&&!n){let a=uz(r,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=rE(t,t.typeName,e),i=typeof s=="function"?X(s(),e):s;if(i&&lz(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var uz,lz,Je=v(()=>{Yu();Wg();el();an();uz=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Qu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),je(e)):e.$refStrategy==="seen"?je(e):void 0}},lz=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var oE=v(()=>{});var Kg,Gg=v(()=>{Je();yg();an();Kg=(t,e)=>{let n=Rw(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:X(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??je(n)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=X(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??je(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=o===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:s}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var sE=v(()=>{Yu();yg();jr();el();Je();oE();an();xg();bg();Sg();nl();vg();wg();Eg();Tg();$g();Pg();Rg();Ig();Ag();Ng();Dg();Mg();jg();Lg();zg();Fg();Hg();Vg();il();Ug();ol();Bg();Zg();al();qg();Wg();Gg();Gg()});function dz(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Jg(t,e){return rn(t)?jh(t,{target:dz(e?.target),io:e?.pipeStrategy??"input"}):Kg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Xg(t){let n=Nr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Iu(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function Yg(t,e){let n=Ar(t,e);if(!n.success)throw n.error;return n.data}var Qg=v(()=>{Fh();ca();sE()});function iE(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function aE(t,e){let n={...t};for(let r in e){let o=r,s=e[o];if(s===void 0)continue;let i=n[o];iE(i)&&iE(s)?n[o]={...i,...s}:n[o]=s}return n}var pz,cl,cE=v(()=>{ca();zo();Ew();Qg();pz=6e4,cl=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(zu,n=>{this._oncancel(n)}),this.setNotificationHandler(Hu,n=>{this._onprogress(n)}),this.setRequestHandler(Fu,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Uu,async(n,r)=>{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new Z(K.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Zu,async(n,r)=>{let o=async()=>{let s=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,r.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new Z(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(s,r.sessionId);if(!i)throw new Z(K.InvalidParams,`Task not found: ${s}`);if(!Mr(i.status))return await this._waitForTaskUpdate(s,r.signal),await o();if(Mr(i.status)){let a=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Dr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(qu,async(n,r)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new Z(K.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Wu,async(n,r)=>{try{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new Z(K.InvalidParams,`Task not found: ${n.params.taskId}`);if(Mr(o.status))throw new Z(K.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new Z(K.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof Z?o:new Z(K.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,r,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),Z.fromError(K.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),pa(s)||fw(s)?this._onresponse(s):rg(s)?this._onrequest(s,i):mw(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=Z.fromError(K.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Dr]?.taskId;if(r===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:K.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=lw(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new Z(K.ConnectionClosed,"Request was cancelled");let h={...p,relatedRequestId:e.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});let m=h.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,h)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:K.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...r}=e.params,o=Number(n),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),pa(e))r(e);else{let i=new Z(e.error.code,e.error.message,e.error.data);r(i)}return}let o=this._responseHandlers.get(n);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let s=!1;if(pa(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,n))}}if(s||this._progressHandlers.delete(n),pa(e))o(e);else{let i=Z.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(K.InternalError,String(i))}}return}let s;try{let i=await this.request(e,js,r);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Z(K.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:a},Mr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)}:a.status==="failed"?yield{type:"error",error:new Z(K.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Z(K.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(K.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=r??{};return new Promise((u,l)=>{let d=_=>{l(_)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(_){d(_);return}r?.signal?.throwIfAborted();let p=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:p};r?.onprogress&&(this._progressHandlers.set(p,r.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Dr]:c}});let m=_=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let x=_ instanceof Z?_:new Z(K.RequestTimeout,String(_));l(x)};this._responseHandlers.set(p,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return l(_);try{let x=Ar(n,_.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),r?.signal?.addEventListener("abort",()=>{m(r?.signal?.reason)});let f=r?.timeout??pz,g=()=>m(Z.fromError(K.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(p,f,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=x=>{let S=this._responseHandlers.get(p);S?S(x):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(y,{type:"request",message:h,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(p),l(x)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),l(_)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Bu,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Vu,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},yw,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Dr]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Dr]:n.relatedTask}}}),this._transport?.send(a,n).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Dr]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=Xg(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{let i=Yg(e,o);return Promise.resolve(n(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let r=Xg(e);this._notificationHandlers.set(r,o=>{let s=Yg(e,o);return Promise.resolve(n(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,r,o)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let o of r)if(o.type==="request"&&rg(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new Z(K.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,s)=>{if(n.aborted){s(new Z(K.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(i),s(new Z(K.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},n)},getTask:async o=>{let s=await r.getTask(o,n);if(!s)throw new Z(K.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await r.storeTaskResult(o,s,i,n);let a=await r.getTask(o,n);if(a){let c=ya.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Mr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>r.getTaskResult(o,n),updateTaskStatus:async(o,s,i)=>{let a=await r.getTask(o,n);if(!a)throw new Z(K.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Mr(a.status))throw new Z(K.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,s,i,n);let c=await r.getTask(o,n);if(c){let u=ya.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Mr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}}});var wa=L(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var va=class{};he._CodeOrName=va;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Fo=class extends va{constructor(e){if(super(),!he.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};he.Name=Fo;var cn=class extends va{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Fo&&(n[r.str]=(n[r.str]||0)+1),n),{})}};he._Code=cn;he.nil=new cn("");function uE(t,...e){let n=[t[0]],r=0;for(;r<e.length;)ty(n,e[r]),n.push(t[++r]);return new cn(n)}he._=uE;var ey=new cn("+");function lE(t,...e){let n=[ka(t[0])],r=0;for(;r<e.length;)n.push(ey),ty(n,e[r]),n.push(ey,ka(t[++r]));return mz(n),new cn(n)}he.str=lE;function ty(t,e){e instanceof cn?t.push(...e._items):e instanceof Fo?t.push(e):t.push(gz(e))}he.addCodeArg=ty;function mz(t){let e=1;for(;e<t.length-1;){if(t[e]===ey){let n=fz(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function fz(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Fo||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Fo))return`"${t}${e.slice(1)}`}function hz(t,e){return e.emptyStr()?t:t.emptyStr()?e:lE`${t}${e}`}he.strConcat=hz;function gz(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ka(Array.isArray(t)?t.join(","):t)}function yz(t){return new cn(ka(t))}he.stringify=yz;function ka(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=ka;function _z(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new cn(`.${t}`):uE`[${t}]`}he.getProperty=_z;function xz(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new cn(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=xz;function bz(t){return new cn(t.toString())}he.regexpCode=bz});var oy=L(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.ValueScope=Nt.ValueScopeName=Nt.Scope=Nt.varKinds=Nt.UsedValueState=void 0;var At=wa(),ny=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ul;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ul||(Nt.UsedValueState=ul={}));Nt.varKinds={const:new At.Name("const"),let:new At.Name("let"),var:new At.Name("var")};var ll=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof At.Name?e:this.name(e)}name(e){return new At.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Nt.Scope=ll;var dl=class extends At.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,At._)`.${new At.Name(n)}[${r}]`}};Nt.ValueScopeName=dl;var Sz=(0,At._)`\n`,ry=class extends ll{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Sz:At.nil}}get(){return this._scope}name(e){return new dl(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(r=n.key)!==null&&r!==void 0?r:n.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=n.ref,o.setValue(n,{property:s,itemIndex:u}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,At._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let s=At.nil;for(let i in e){let a=e[i];if(!a)continue;let c=r[i]=r[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,ul.Started);let l=n(u);if(l){let d=this.opts.es5?Nt.varKinds.var:Nt.varKinds.const;s=(0,At._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,At._)`${s}${l}${this.opts._n}`;else throw new ny(u);c.set(u,ul.Completed)})}return s}};Nt.ValueScope=ry});var oe=L(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.or=se.and=se.not=se.CodeGen=se.operators=se.varKinds=se.ValueScopeName=se.ValueScope=se.Scope=se.Name=se.regexpCode=se.stringify=se.getProperty=se.nil=se.strConcat=se.str=se._=void 0;var pe=wa(),_n=oy(),Lr=wa();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Lr._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Lr.str}});Object.defineProperty(se,"strConcat",{enumerable:!0,get:function(){return Lr.strConcat}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Lr.nil}});Object.defineProperty(se,"getProperty",{enumerable:!0,get:function(){return Lr.getProperty}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Lr.stringify}});Object.defineProperty(se,"regexpCode",{enumerable:!0,get:function(){return Lr.regexpCode}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Lr.Name}});var hl=oy();Object.defineProperty(se,"Scope",{enumerable:!0,get:function(){return hl.Scope}});Object.defineProperty(se,"ValueScope",{enumerable:!0,get:function(){return hl.ValueScope}});Object.defineProperty(se,"ValueScopeName",{enumerable:!0,get:function(){return hl.ValueScopeName}});Object.defineProperty(se,"varKinds",{enumerable:!0,get:function(){return hl.varKinds}});se.operators={GT:new pe._Code(">"),GTE:new pe._Code(">="),LT:new pe._Code("<"),LTE:new pe._Code("<="),EQ:new pe._Code("==="),NEQ:new pe._Code("!=="),NOT:new pe._Code("!"),OR:new pe._Code("||"),AND:new pe._Code("&&"),ADD:new pe._Code("+")};var or=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},sy=class extends or{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?_n.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=qs(this.rhs,e,n)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},pl=class extends or{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=qs(this.rhs,e,n),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return fl(e,this.rhs)}},iy=class extends pl{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},ay=class extends or{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},cy=class extends or{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},uy=class extends or{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ly=class extends or{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=qs(this.code,e,n),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},Ea=class extends or{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let s=r[o];s.optimizeNames(e,n)||(vz(e,s.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Bo(e,n.names),{})}},sr=class extends Ea{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},dy=class extends Ea{},Zs=class extends sr{};Zs.kind="else";var Ho=class t extends sr{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new Zs(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(dE(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=qs(this.condition,e,n),this}get names(){let e=super.names;return fl(e,this.condition),this.else&&Bo(e,this.else.names),e}};Ho.kind="if";var Uo=class extends sr{};Uo.kind="for";var py=class extends Uo{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=qs(this.iteration,e,n),this}get names(){return Bo(super.names,this.iteration.names)}},my=class extends Uo{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?_n.varKinds.var:this.varKind,{name:r,from:o,to:s}=this;return`for(${n} ${r}=${o}; ${r}<${s}; ${r}++)`+super.render(e)}get names(){let e=fl(super.names,this.from);return fl(e,this.to)}},ml=class extends Uo{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=qs(this.iterable,e,n),this}get names(){return Bo(super.names,this.iterable.names)}},Ta=class extends sr{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ta.kind="func";var $a=class extends Ea{render(e){return"return "+super.render(e)}};$a.kind="return";var fy=class extends sr{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Bo(e,this.catch.names),this.finally&&Bo(e,this.finally.names),e}},Pa=class extends sr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Pa.kind="catch";var Ra=class extends sr{render(e){return"finally"+super.render(e)}};Ra.kind="finally";var hy=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
491
|
+
`:""},this._extScope=e,this._scope=new _n.Scope({parent:e}),this._nodes=[new dy]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let s=this._scope.toName(n);return r!==void 0&&o&&(this._constants[s.str]=r),this._leafNode(new sy(e,s,r)),s}const(e,n,r){return this._def(_n.varKinds.const,e,n,r)}let(e,n,r){return this._def(_n.varKinds.let,e,n,r)}var(e,n,r){return this._def(_n.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new pl(e,n,r))}add(e,n){return this._leafNode(new iy(e,se.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new ly(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,pe.addCodeArg)(n,o));return n.push("}"),new pe._Code(n)}if(e,n,r){if(this._blockNode(new Ho(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Ho(e))}else(){return this._elseNode(new Zs)}endIf(){return this._endBlockNode(Ho,Zs)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new py(e),n)}forRange(e,n,r,o,s=this.opts.es5?_n.varKinds.var:_n.varKinds.let){let i=this._scope.toName(e);return this._for(new my(s,i,n,r),()=>o(i))}forOf(e,n,r,o=_n.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=n instanceof pe.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(s,(0,pe._)`${i}[${a}]`),r(s)})}return this._for(new ml("of",o,s,n),()=>r(s))}forIn(e,n,r,o=this.opts.es5?_n.varKinds.var:_n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${n})`,r);let s=this._scope.toName(e);return this._for(new ml("in",o,s,n),()=>r(s))}endFor(){return this._endBlockNode(Uo)}label(e){return this._leafNode(new ay(e))}break(e){return this._leafNode(new cy(e))}return(e){let n=new $a;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode($a)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new fy;if(this._blockNode(o),this.code(e),n){let s=this.name("e");this._currNode=o.catch=new Pa(s),n(s)}return r&&(this._currNode=o.finally=new Ra,this.code(r)),this._endBlockNode(Pa,Ra)}throw(e){return this._leafNode(new uy(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=pe.nil,r,o){return this._blockNode(new Ta(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Ta)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Ho))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};se.CodeGen=hy;function Bo(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function fl(t,e){return e instanceof pe._CodeOrName?Bo(t,e.names):t}function qs(t,e,n){if(t instanceof pe.Name)return r(t);if(!o(t))return t;return new pe._Code(t._items.reduce((s,i)=>(i instanceof pe.Name&&(i=r(i)),i instanceof pe._Code?s.push(...i._items):s.push(i),s),[]));function r(s){let i=n[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof pe._Code&&s._items.some(i=>i instanceof pe.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function vz(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function dE(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${gy(t)}`}se.not=dE;var kz=pE(se.operators.AND);function wz(...t){return t.reduce(kz)}se.and=wz;var Ez=pE(se.operators.OR);function Tz(...t){return t.reduce(Ez)}se.or=Tz;function pE(t){return(e,n)=>e===pe.nil?n:n===pe.nil?e:(0,pe._)`${gy(e)} ${t} ${gy(n)}`}function gy(t){return t instanceof pe.Name?t:(0,pe._)`(${t})`}});var me=L(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.checkStrictMode=ae.getErrorPath=ae.Type=ae.useFunc=ae.setEvaluated=ae.evaluatedPropsToName=ae.mergeEvaluated=ae.eachItem=ae.unescapeJsonPointer=ae.escapeJsonPointer=ae.escapeFragment=ae.unescapeFragment=ae.schemaRefOrVal=ae.schemaHasRulesButRef=ae.schemaHasRules=ae.checkUnknownRules=ae.alwaysValidSchema=ae.toHash=void 0;var we=oe(),$z=wa();function Pz(t){let e={};for(let n of t)e[n]=!0;return e}ae.toHash=Pz;function Rz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(hE(t,e),!gE(e,t.self.RULES.all))}ae.alwaysValidSchema=Rz;function hE(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let s in e)o[s]||xE(t,`unknown keyword: "${s}"`)}ae.checkUnknownRules=hE;function gE(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}ae.schemaHasRules=gE;function Cz(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}ae.schemaHasRulesButRef=Cz;function Oz({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,we._)`${n}`}return(0,we._)`${t}${e}${(0,we.getProperty)(r)}`}ae.schemaRefOrVal=Oz;function Iz(t){return yE(decodeURIComponent(t))}ae.unescapeFragment=Iz;function Az(t){return encodeURIComponent(_y(t))}ae.escapeFragment=Az;function _y(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ae.escapeJsonPointer=_y;function yE(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ae.unescapeJsonPointer=yE;function Nz(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}ae.eachItem=Nz;function mE({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof we.Name?(s instanceof we.Name?t(o,s,i):e(o,s,i),i):s instanceof we.Name?(e(o,i,s),s):n(s,i);return a===we.Name&&!(c instanceof we.Name)?r(o,c):c}}ae.mergeEvaluated={props:mE({mergeNames:(t,e,n)=>t.if((0,we._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,we._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,we._)`${n} || {}`).code((0,we._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,we._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,we._)`${n} || {}`),xy(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:_E}),items:mE({mergeNames:(t,e,n)=>t.if((0,we._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,we._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,we._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,we._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function _E(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,we._)`{}`);return e!==void 0&&xy(t,n,e),n}ae.evaluatedPropsToName=_E;function xy(t,e,n){Object.keys(n).forEach(r=>t.assign((0,we._)`${e}${(0,we.getProperty)(r)}`,!0))}ae.setEvaluated=xy;var fE={};function Dz(t,e){return t.scopeValue("func",{ref:e,code:fE[e.code]||(fE[e.code]=new $z._Code(e.code))})}ae.useFunc=Dz;var yy;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(yy||(ae.Type=yy={}));function Mz(t,e,n){if(t instanceof we.Name){let r=e===yy.Num;return n?r?(0,we._)`"[" + ${t} + "]"`:(0,we._)`"['" + ${t} + "']"`:r?(0,we._)`"/" + ${t}`:(0,we._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,we.getProperty)(t).toString():"/"+_y(t)}ae.getErrorPath=Mz;function xE(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}ae.checkStrictMode=xE});var ir=L(by=>{"use strict";Object.defineProperty(by,"__esModule",{value:!0});var yt=oe(),jz={data:new yt.Name("data"),valCxt:new yt.Name("valCxt"),instancePath:new yt.Name("instancePath"),parentData:new yt.Name("parentData"),parentDataProperty:new yt.Name("parentDataProperty"),rootData:new yt.Name("rootData"),dynamicAnchors:new yt.Name("dynamicAnchors"),vErrors:new yt.Name("vErrors"),errors:new yt.Name("errors"),this:new yt.Name("this"),self:new yt.Name("self"),scope:new yt.Name("scope"),json:new yt.Name("json"),jsonPos:new yt.Name("jsonPos"),jsonLen:new yt.Name("jsonLen"),jsonPart:new yt.Name("jsonPart")};by.default=jz});var Ca=L(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.extendErrors=_t.resetErrorsCount=_t.reportExtraError=_t.reportError=_t.keyword$DataError=_t.keywordError=void 0;var fe=oe(),gl=me(),Tt=ir();_t.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};_t.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,fe.str)`"${t}" keyword must be ${e} ($data)`:(0,fe.str)`"${t}" keyword is invalid ($data)`};function Lz(t,e=_t.keywordError,n,r){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=vE(t,e,n);r??(i||a)?bE(s,c):SE(o,(0,fe._)`[${c}]`)}_t.reportError=Lz;function zz(t,e=_t.keywordError,n){let{it:r}=t,{gen:o,compositeRule:s,allErrors:i}=r,a=vE(t,e,n);bE(o,a),s||i||SE(r,Tt.default.vErrors)}_t.reportExtraError=zz;function Fz(t,e){t.assign(Tt.default.errors,e),t.if((0,fe._)`${Tt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${Tt.default.vErrors}.length`,e),()=>t.assign(Tt.default.vErrors,null)))}_t.resetErrorsCount=Fz;function Hz({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Tt.default.errors,a=>{t.const(i,(0,fe._)`${Tt.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)(Tt.default.instancePath,s.errorPath))),t.assign((0,fe._)`${i}.schemaPath`,(0,fe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,fe._)`${i}.schema`,n),t.assign((0,fe._)`${i}.data`,r))})}_t.extendErrors=Hz;function bE(t,e){let n=t.const("err",e);t.if((0,fe._)`${Tt.default.vErrors} === null`,()=>t.assign(Tt.default.vErrors,(0,fe._)`[${n}]`),(0,fe._)`${Tt.default.vErrors}.push(${n})`),t.code((0,fe._)`${Tt.default.errors}++`)}function SE(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,fe._)`new ${t.ValidationError}(${e})`):(n.assign((0,fe._)`${r}.errors`,e),n.return(!1))}var Zo={keyword:new fe.Name("keyword"),schemaPath:new fe.Name("schemaPath"),params:new fe.Name("params"),propertyName:new fe.Name("propertyName"),message:new fe.Name("message"),schema:new fe.Name("schema"),parentSchema:new fe.Name("parentSchema")};function vE(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,fe._)`{}`:Uz(t,e,n)}function Uz(t,e,n={}){let{gen:r,it:o}=t,s=[Bz(o,n),Zz(t,n)];return qz(t,e,s),r.object(...s)}function Bz({errorPath:t},{instancePath:e}){let n=e?(0,fe.str)`${t}${(0,gl.getErrorPath)(e,gl.Type.Str)}`:t;return[Tt.default.instancePath,(0,fe.strConcat)(Tt.default.instancePath,n)]}function Zz({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,fe.str)`${e}/${t}`;return n&&(o=(0,fe.str)`${o}${(0,gl.getErrorPath)(n,gl.Type.Str)}`),[Zo.schemaPath,o]}function qz(t,{params:e,message:n},r){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;r.push([Zo.keyword,o],[Zo.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&r.push([Zo.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Zo.schema,i],[Zo.parentSchema,(0,fe._)`${l}${d}`],[Tt.default.data,s]),u&&r.push([Zo.propertyName,u])}});var wE=L(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.boolOrEmptySchema=Vs.topBoolOrEmptySchema=void 0;var Vz=Ca(),Wz=oe(),Kz=ir(),Gz={message:"boolean schema is false"};function Jz(t){let{gen:e,schema:n,validateName:r}=t;n===!1?kE(t,!1):typeof n=="object"&&n.$async===!0?e.return(Kz.default.data):(e.assign((0,Wz._)`${r}.errors`,null),e.return(!0))}Vs.topBoolOrEmptySchema=Jz;function Xz(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),kE(t)):n.var(e,!0)}Vs.boolOrEmptySchema=Xz;function kE(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Vz.reportError)(o,Gz,void 0,e)}});var Sy=L(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.getRules=Ws.isJSONType=void 0;var Yz=["string","number","integer","boolean","null","object","array"],Qz=new Set(Yz);function eF(t){return typeof t=="string"&&Qz.has(t)}Ws.isJSONType=eF;function tF(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Ws.getRules=tF});var vy=L(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.shouldUseRule=zr.shouldUseGroup=zr.schemaHasRulesForType=void 0;function nF({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&EE(t,r)}zr.schemaHasRulesForType=nF;function EE(t,e){return e.rules.some(n=>TE(t,n))}zr.shouldUseGroup=EE;function TE(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}zr.shouldUseRule=TE});var Oa=L(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.reportTypeError=xt.checkDataTypes=xt.checkDataType=xt.coerceAndCheckDataType=xt.getJSONTypes=xt.getSchemaTypes=xt.DataType=void 0;var rF=Sy(),oF=vy(),sF=Ca(),ne=oe(),$E=me(),Ks;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Ks||(xt.DataType=Ks={}));function iF(t){let e=PE(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}xt.getSchemaTypes=iF;function PE(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(rF.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}xt.getJSONTypes=PE;function aF(t,e){let{gen:n,data:r,opts:o}=t,s=cF(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,oF.schemaHasRulesForType)(t,e[0]));if(i){let a=wy(e,r,o.strictNumbers,Ks.Wrong);n.if(a,()=>{s.length?uF(t,e,s):Ey(t)})}return i}xt.coerceAndCheckDataType=aF;var RE=new Set(["string","number","integer","boolean","null"]);function cF(t,e){return e?t.filter(n=>RE.has(n)||e==="array"&&n==="array"):[]}function uF(t,e,n){let{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,ne._)`typeof ${o}`),a=r.let("coerced",(0,ne._)`undefined`);s.coerceTypes==="array"&&r.if((0,ne._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,ne._)`${o}[0]`).assign(i,(0,ne._)`typeof ${o}`).if(wy(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,ne._)`${a} !== undefined`);for(let u of n)(RE.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Ey(t),r.endIf(),r.if((0,ne._)`${a} !== undefined`,()=>{r.assign(o,a),lF(t,a)});function c(u){switch(u){case"string":r.elseIf((0,ne._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ne._)`"" + ${o}`).elseIf((0,ne._)`${o} === null`).assign(a,(0,ne._)`""`);return;case"number":r.elseIf((0,ne._)`${i} == "boolean" || ${o} === null
|
|
492
|
+
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ne._)`+${o}`);return;case"integer":r.elseIf((0,ne._)`${i} === "boolean" || ${o} === null
|
|
493
|
+
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ne._)`+${o}`);return;case"boolean":r.elseIf((0,ne._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ne._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,ne._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,ne._)`${i} === "string" || ${i} === "number"
|
|
494
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,ne._)`[${o}]`)}}}function lF({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,ne._)`${e} !== undefined`,()=>t.assign((0,ne._)`${e}[${n}]`,r))}function ky(t,e,n,r=Ks.Correct){let o=r===Ks.Correct?ne.operators.EQ:ne.operators.NEQ,s;switch(t){case"null":return(0,ne._)`${e} ${o} null`;case"array":s=(0,ne._)`Array.isArray(${e})`;break;case"object":s=(0,ne._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ne._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ne._)`typeof ${e} ${o} ${t}`}return r===Ks.Correct?s:(0,ne.not)(s);function i(a=ne.nil){return(0,ne.and)((0,ne._)`typeof ${e} == "number"`,a,n?(0,ne._)`isFinite(${e})`:ne.nil)}}xt.checkDataType=ky;function wy(t,e,n,r){if(t.length===1)return ky(t[0],e,n,r);let o,s=(0,$E.toHash)(t);if(s.array&&s.object){let i=(0,ne._)`typeof ${e} != "object"`;o=s.null?i:(0,ne._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ne.nil;s.number&&delete s.integer;for(let i in s)o=(0,ne.and)(o,ky(i,e,n,r));return o}xt.checkDataTypes=wy;var dF={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ne._)`{type: ${t}}`:(0,ne._)`{type: ${e}}`};function Ey(t){let e=pF(t);(0,sF.reportError)(e,dF)}xt.reportTypeError=Ey;function pF(t){let{gen:e,data:n,schema:r}=t,o=(0,$E.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var OE=L(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});yl.assignDefaults=void 0;var Gs=oe(),mF=me();function fF(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)CE(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>CE(t,s,o.default))}yl.assignDefaults=fF;function CE(t,e,n){let{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;let a=(0,Gs._)`${s}${(0,Gs.getProperty)(e)}`;if(o){(0,mF.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Gs._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Gs._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Gs._)`${a} = ${(0,Gs.stringify)(n)}`)}});var un=L(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.validateUnion=ke.validateArray=ke.usePattern=ke.callValidateCode=ke.schemaProperties=ke.allSchemaProperties=ke.noPropertyInData=ke.propertyInData=ke.isOwnProperty=ke.hasPropFunc=ke.reportMissingProp=ke.checkMissingProp=ke.checkReportMissingProp=void 0;var Oe=oe(),Ty=me(),Fr=ir(),hF=me();function gF(t,e){let{gen:n,data:r,it:o}=t;n.if(Py(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Oe._)`${e}`},!0),t.error()})}ke.checkReportMissingProp=gF;function yF({gen:t,data:e,it:{opts:n}},r,o){return(0,Oe.or)(...r.map(s=>(0,Oe.and)(Py(t,e,s,n.ownProperties),(0,Oe._)`${o} = ${s}`)))}ke.checkMissingProp=yF;function _F(t,e){t.setParams({missingProperty:e},!0),t.error()}ke.reportMissingProp=_F;function IE(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Oe._)`Object.prototype.hasOwnProperty`})}ke.hasPropFunc=IE;function $y(t,e,n){return(0,Oe._)`${IE(t)}.call(${e}, ${n})`}ke.isOwnProperty=$y;function xF(t,e,n,r){let o=(0,Oe._)`${e}${(0,Oe.getProperty)(n)} !== undefined`;return r?(0,Oe._)`${o} && ${$y(t,e,n)}`:o}ke.propertyInData=xF;function Py(t,e,n,r){let o=(0,Oe._)`${e}${(0,Oe.getProperty)(n)} === undefined`;return r?(0,Oe.or)(o,(0,Oe.not)($y(t,e,n))):o}ke.noPropertyInData=Py;function AE(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ke.allSchemaProperties=AE;function bF(t,e){return AE(e).filter(n=>!(0,Ty.alwaysValidSchema)(t,e[n]))}ke.schemaProperties=bF;function SF({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Oe._)`${t}, ${e}, ${r}${o}`:e,d=[[Fr.default.instancePath,(0,Oe.strConcat)(Fr.default.instancePath,s)],[Fr.default.parentData,i.parentData],[Fr.default.parentDataProperty,i.parentDataProperty],[Fr.default.rootData,Fr.default.rootData]];i.opts.dynamicRef&&d.push([Fr.default.dynamicAnchors,Fr.default.dynamicAnchors]);let p=(0,Oe._)`${l}, ${n.object(...d)}`;return c!==Oe.nil?(0,Oe._)`${a}.call(${c}, ${p})`:(0,Oe._)`${a}(${p})`}ke.callValidateCode=SF;var vF=(0,Oe._)`new RegExp`;function kF({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Oe._)`${o.code==="new RegExp"?vF:(0,hF.useFunc)(t,o)}(${n}, ${r})`})}ke.usePattern=kF;function wF(t){let{gen:e,data:n,keyword:r,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Oe._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:Ty.Type.Num},s),e.if((0,Oe.not)(s),a)})}}ke.validateArray=wF;function EF(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Ty.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,u)=>{let l=t.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Oe._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Oe.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ke.validateUnion=EF});var ME=L(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.validateKeywordUsage=Ln.validSchemaType=Ln.funcKeywordCode=Ln.macroKeywordCode=void 0;var $t=oe(),qo=ir(),TF=un(),$F=Ca();function PF(t,e){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=DE(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:$t.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ln.macroKeywordCode=PF;function RF(t,e){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;OF(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=DE(r,o,u),d=r.let("valid");t.block$data(d,p),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function p(){if(e.errors===!1)f(),e.modifying&&NE(t),g(()=>t.error());else{let y=e.async?h():m();e.modifying&&NE(t),g(()=>CF(t,y))}}function h(){let y=r.let("ruleErrs",null);return r.try(()=>f((0,$t._)`await `),_=>r.assign(d,!1).if((0,$t._)`${_} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,$t._)`${_}.errors`),()=>r.throw(_))),y}function m(){let y=(0,$t._)`${l}.errors`;return r.assign(y,null),f($t.nil),y}function f(y=e.async?(0,$t._)`await `:$t.nil){let _=c.opts.passContext?qo.default.this:qo.default.self,x=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,$t._)`${y}${(0,TF.callValidateCode)(t,l,_,x)}`,e.modifying)}function g(y){var _;r.if((0,$t.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}Ln.funcKeywordCode=RF;function NE(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,$t._)`${r.parentData}[${r.parentDataProperty}]`))}function CF(t,e){let{gen:n}=t;n.if((0,$t._)`Array.isArray(${e})`,()=>{n.assign(qo.default.vErrors,(0,$t._)`${qo.default.vErrors} === null ? ${e} : ${qo.default.vErrors}.concat(${e})`).assign(qo.default.errors,(0,$t._)`${qo.default.vErrors}.length`),(0,$F.extendErrors)(t)},()=>t.error())}function OF({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function DE(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,$t.stringify)(n)})}function IF(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Ln.validSchemaType=IF;function AF({schema:t,opts:e,self:n,errSchemaPath:r},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}Ln.validateKeywordUsage=AF});var LE=L(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.extendSubschemaMode=Hr.extendSubschemaData=Hr.getSubschema=void 0;var zn=oe(),jE=me();function NF(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,zn._)`${t.schemaPath}${(0,zn.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,zn._)`${t.schemaPath}${(0,zn.getProperty)(e)}${(0,zn.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,jE.escapeFragment)(n)}`}}if(r!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Hr.getSubschema=NF;function DF(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,zn._)`${e.data}${(0,zn.getProperty)(n)}`,!0);c(p),t.errorPath=(0,zn.str)`${u}${(0,jE.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,zn._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof zn.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Hr.extendSubschemaData=DF;function MF(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}Hr.extendSubschemaMode=MF});var Ry=L((D8,zE)=>{"use strict";zE.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var HE=L((M8,FE)=>{"use strict";var Ur=FE.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};_l(e,r,o,t,"",t)};Ur.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ur.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ur.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ur.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function _l(t,e,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in Ur.arrayKeywords)for(var p=0;p<d.length;p++)_l(t,e,n,d[p],o+"/"+l+"/"+p,s,o,l,r,p)}else if(l in Ur.propsKeywords){if(d&&typeof d=="object")for(var h in d)_l(t,e,n,d[h],o+"/"+l+"/"+jF(h),s,o,l,r,h)}else(l in Ur.keywords||t.allKeys&&!(l in Ur.skipKeywords))&&_l(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function jF(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ia=L(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.getSchemaRefs=Dt.resolveUrl=Dt.normalizeId=Dt._getFullPath=Dt.getFullPath=Dt.inlineRef=void 0;var LF=me(),zF=Ry(),FF=HE(),HF=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function UF(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Cy(t):e?UE(t)<=e:!1}Dt.inlineRef=UF;var BF=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Cy(t){for(let e in t){if(BF.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Cy)||typeof n=="object"&&Cy(n))return!0}return!1}function UE(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!HF.has(n)&&(typeof t[n]=="object"&&(0,LF.eachItem)(t[n],r=>e+=UE(r)),e===1/0))return 1/0}return e}function BE(t,e="",n){n!==!1&&(e=Js(e));let r=t.parse(e);return ZE(t,r)}Dt.getFullPath=BE;function ZE(t,e){return t.serialize(e).split("#")[0]+"#"}Dt._getFullPath=ZE;var ZF=/#\/?$/;function Js(t){return t?t.replace(ZF,""):""}Dt.normalizeId=Js;function qF(t,e,n){return n=Js(n),t.resolve(e,n)}Dt.resolveUrl=qF;var VF=/^[a-z_][-a-z0-9._]*$/i;function WF(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Js(t[n]||e),s={"":o},i=BE(r,o,!1),a={},c=new Set;return FF(t,{allKeys:!0},(d,p,h,m)=>{if(m===void 0)return;let f=i+p,g=s[m];typeof d[n]=="string"&&(g=y.call(this,d[n])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[p]=g;function y(x){let S=this.opts.uriResolver.resolve;if(x=Js(g?S(g,x):x),c.has(x))throw l(x);c.add(x);let E=this.refs[x];return typeof E=="string"&&(E=this.refs[E]),typeof E=="object"?u(d,E.schema,x):x!==Js(f)&&(x[0]==="#"?(u(d,a[x],x),a[x]=d):this.refs[x]=f),x}function _(x){if(typeof x=="string"){if(!VF.test(x))throw new Error(`invalid anchor "${x}"`);y.call(this,`#${x}`)}}}),a;function u(d,p,h){if(p!==void 0&&!zF(d,p))throw l(h)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Dt.getSchemaRefs=WF});var Da=L(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.getData=Br.KeywordCxt=Br.validateFunctionCode=void 0;var GE=wE(),qE=Oa(),Iy=vy(),xl=Oa(),KF=OE(),Na=ME(),Oy=LE(),V=oe(),ee=ir(),GF=Ia(),ar=me(),Aa=Ca();function JF(t){if(YE(t)&&(QE(t),XE(t))){QF(t);return}JE(t,()=>(0,GE.topBoolOrEmptySchema)(t))}Br.validateFunctionCode=JF;function JE({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,V._)`${ee.default.data}, ${ee.default.valCxt}`,r.$async,()=>{t.code((0,V._)`"use strict"; ${VE(n,o)}`),YF(t,o),t.code(s)}):t.func(e,(0,V._)`${ee.default.data}, ${XF(o)}`,r.$async,()=>t.code(VE(n,o)).code(s))}function XF(t){return(0,V._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,V._)`, ${ee.default.dynamicAnchors}={}`:V.nil}}={}`}function YF(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,V._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,V._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,V._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,V._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,V._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,V._)`""`),t.var(ee.default.parentData,(0,V._)`undefined`),t.var(ee.default.parentDataProperty,(0,V._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,V._)`{}`)})}function QF(t){let{schema:e,opts:n,gen:r}=t;JE(t,()=>{n.$comment&&e.$comment&&tT(t),oH(t),r.let(ee.default.vErrors,null),r.let(ee.default.errors,0),n.unevaluated&&eH(t),eT(t),aH(t)})}function eH(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,V._)`${n}.evaluated`),e.if((0,V._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,V._)`${t.evaluated}.props`,(0,V._)`undefined`)),e.if((0,V._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,V._)`${t.evaluated}.items`,(0,V._)`undefined`))}function VE(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,V._)`/*# sourceURL=${n} */`:V.nil}function tH(t,e){if(YE(t)&&(QE(t),XE(t))){nH(t,e);return}(0,GE.boolOrEmptySchema)(t,e)}function XE({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function YE(t){return typeof t.schema!="boolean"}function nH(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&tT(t),sH(t),iH(t);let s=r.const("_errs",ee.default.errors);eT(t,s),r.var(e,(0,V._)`${s} === ${ee.default.errors}`)}function QE(t){(0,ar.checkUnknownRules)(t),rH(t)}function eT(t,e){if(t.opts.jtd)return WE(t,[],!1,e);let n=(0,qE.getSchemaTypes)(t.schema),r=(0,qE.coerceAndCheckDataType)(t,n);WE(t,n,!r,e)}function rH(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,ar.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function oH(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,ar.checkStrictMode)(t,"default is ignored in the schema root")}function sH(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,GF.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function iH(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function tT({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let s=n.$comment;if(o.$comment===!0)t.code((0,V._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,V.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,V._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function aH(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$async?e.if((0,V._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,V._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,V._)`${r}.errors`,ee.default.vErrors),s.unevaluated&&cH(t),e.return((0,V._)`${ee.default.errors} === 0`))}function cH({gen:t,evaluated:e,props:n,items:r}){n instanceof V.Name&&t.assign((0,V._)`${e}.props`,n),r instanceof V.Name&&t.assign((0,V._)`${e}.items`,r)}function WE(t,e,n,r){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ar.schemaHasRulesButRef)(s,l))){o.block(()=>rT(t,"$ref",l.all.$ref.definition));return}c.jtd||uH(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Iy.shouldUseGroup)(s,p)&&(p.type?(o.if((0,xl.checkDataType)(p.type,i,c.strictNumbers)),KE(t,p),e.length===1&&e[0]===p.type&&n&&(o.else(),(0,xl.reportTypeError)(t)),o.endIf()):KE(t,p),a||o.if((0,V._)`${ee.default.errors} === ${r||0}`))}}function KE(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,KF.assignDefaults)(t,e.type),n.block(()=>{for(let s of e.rules)(0,Iy.shouldUseRule)(r,s)&&rT(t,s.keyword,s.definition,e.type)})}function uH(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(lH(t,e),t.opts.allowUnionTypes||dH(t,e),pH(t,t.dataTypes))}function lH(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{nT(t.dataTypes,n)||Ay(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),fH(t,e)}}function dH(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ay(t,"use allowUnionTypes to allow union type keyword")}function pH(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Iy.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>mH(e,i))&&Ay(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function mH(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function nT(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function fH(t,e){let n=[];for(let r of t.dataTypes)nT(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Ay(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,ar.checkStrictMode)(t,e,t.opts.strictTypes)}var bl=class{constructor(e,n,r){if((0,Na.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ar.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",oT(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Na.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ee.default.errors))}result(e,n,r){this.failResult((0,V.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,V.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,V._)`${n} !== undefined && (${(0,V.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?Aa.reportExtraError:Aa.reportError)(this,this.def.error,n)}$dataError(){(0,Aa.reportError)(this,this.def.$dataError||Aa.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Aa.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=V.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=V.nil,n=V.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,V.or)((0,V._)`${o} === undefined`,n)),e!==V.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==V.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,V.or)(i(),a());function i(){if(r.length){if(!(n instanceof V.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,V._)`${(0,xl.checkDataTypes)(c,n,s.opts.strictNumbers,xl.DataType.Wrong)}`}return V.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,V._)`!${c}(${n})`}return V.nil}}subschema(e,n){let r=(0,Oy.getSubschema)(this.it,e);(0,Oy.extendSubschemaData)(r,this.it,e),(0,Oy.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return tH(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=ar.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=ar.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,V.Name)),!0}};Br.KeywordCxt=bl;function rT(t,e,n,r){let o=new bl(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,Na.funcKeywordCode)(o,n):"macro"in n?(0,Na.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,Na.funcKeywordCode)(o,n)}var hH=/^\/(?:[^~]|~0|~1)*$/,gH=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function oT(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!hH.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=gH.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,V._)`${s}${(0,V.getProperty)((0,ar.unescapeJsonPointer)(u))}`,i=(0,V._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Br.getData=oT});var Sl=L(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var Ny=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Dy.default=Ny});var Ma=L(Ly=>{"use strict";Object.defineProperty(Ly,"__esModule",{value:!0});var My=Ia(),jy=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,My.resolveUrl)(e,n,r),this.missingSchema=(0,My.normalizeId)((0,My.getFullPath)(e,this.missingRef))}};Ly.default=jy});var kl=L(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.resolveSchema=ln.getCompilingSchema=ln.resolveRef=ln.compileSchema=ln.SchemaEnv=void 0;var xn=oe(),yH=Sl(),Vo=ir(),bn=Ia(),sT=me(),_H=Da(),Xs=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,bn.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};ln.SchemaEnv=Xs;function Fy(t){let e=iT.call(this,t);if(e)return e;let n=(0,bn.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new xn.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:yH.default,code:(0,xn._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Vo.default.data,parentData:Vo.default.parentData,parentDataProperty:Vo.default.parentDataProperty,dataNames:[Vo.default.data],dataPathArr:[xn.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,xn.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:xn.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,xn._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,_H.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Vo.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let h=new Function(`${Vo.default.self}`,`${Vo.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:f}=u;h.evaluated={props:m instanceof xn.Name?void 0:m,items:f instanceof xn.Name?void 0:f,dynamicProps:m instanceof xn.Name,dynamicItems:f instanceof xn.Name},h.source&&(h.source.evaluated=(0,xn.stringify)(h.evaluated))}return t.validate=h,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}ln.compileSchema=Fy;function xH(t,e,n){var r;n=(0,bn.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let s=vH.call(this,t,n);if(s===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Xs({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=bH.call(this,s)}ln.resolveRef=xH;function bH(t){return(0,bn.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Fy.call(this,t)}function iT(t){for(let e of this._compilations)if(SH(e,t))return e}ln.getCompilingSchema=iT;function SH(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function vH(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||vl.call(this,t,e)}function vl(t,e){let n=this.opts.uriResolver.parse(e),r=(0,bn._getFullPath)(this.opts.uriResolver,n),o=(0,bn.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return zy.call(this,n,t);let s=(0,bn.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=vl.call(this,t,i);return typeof a?.schema!="object"?void 0:zy.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||Fy.call(this,i),s===(0,bn.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,bn.resolveUrl)(this.opts.uriResolver,o,u)),new Xs({schema:a,schemaId:c,root:t,baseId:o})}return zy.call(this,n,i)}}ln.resolveSchema=vl;var kH=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function zy(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let c=n[(0,sT.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!kH.has(a)&&u&&(e=(0,bn.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,sT.schemaHasRulesButRef)(n,this.RULES)){let a=(0,bn.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=vl.call(this,r,a)}let{schemaId:i}=this.opts;if(s=s||new Xs({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}});var aT=L((U8,wH)=>{wH.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Uy=L((B8,dT)=>{"use strict";var EH=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),uT=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Hy(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var TH=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function cT(t){return t.length=0,!0}function $H(t,e,n){if(t.length){let r=Hy(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function PH(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],s=!1,i=!1,a=$H;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=cT}else{o.push(u);continue}}return o.length&&(a===cT?n.zone=o.join(""):i?r.push(o.join("")):r.push(Hy(o))),n.address=r.join(""),n}function lT(t){if(RH(t,":")<2)return{host:t,isIPV6:!1};let e=PH(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function RH(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function CH(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}function OH(t,e){let n=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=n(t.scheme)),t.userinfo!==void 0&&(t.userinfo=n(t.userinfo)),t.host!==void 0&&(t.host=n(t.host)),t.path!==void 0&&(t.path=n(t.path)),t.query!==void 0&&(t.query=n(t.query)),t.fragment!==void 0&&(t.fragment=n(t.fragment)),t}function IH(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!uT(n)){let r=lT(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=t.host}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}dT.exports={nonSimpleDomain:TH,recomposeAuthority:IH,normalizeComponentEncoding:OH,removeDotSegments:CH,isIPv4:uT,isUUID:EH,normalizeIPv6:lT,stringArrayToHexStripped:Hy}});var gT=L((Z8,hT)=>{"use strict";var{isUUID:AH}=Uy(),NH=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,DH=["http","https","ws","wss","urn","urn:uuid"];function MH(t){return DH.indexOf(t)!==-1}function By(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function pT(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function mT(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function jH(t){return t.secure=By(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function LH(t){if((t.port===(By(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function zH(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(NH);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,s=Zy(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function FH(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=Zy(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function HH(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!AH(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function UH(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var fT={scheme:"http",domainHost:!0,parse:pT,serialize:mT},BH={scheme:"https",domainHost:fT.domainHost,parse:pT,serialize:mT},wl={scheme:"ws",domainHost:!0,parse:jH,serialize:LH},ZH={scheme:"wss",domainHost:wl.domainHost,parse:wl.parse,serialize:wl.serialize},qH={scheme:"urn",parse:zH,serialize:FH,skipNormalize:!0},VH={scheme:"urn:uuid",parse:HH,serialize:UH,skipNormalize:!0},El={http:fT,https:BH,ws:wl,wss:ZH,urn:qH,"urn:uuid":VH};Object.setPrototypeOf(El,null);function Zy(t){return t&&(El[t]||El[t.toLowerCase()])||void 0}hT.exports={wsIsSecure:By,SCHEMES:El,isValidSchemeName:MH,getSchemeHandler:Zy}});var xT=L((q8,$l)=>{"use strict";var{normalizeIPv6:WH,removeDotSegments:ja,recomposeAuthority:KH,normalizeComponentEncoding:Tl,isIPv4:GH,nonSimpleDomain:JH}=Uy(),{SCHEMES:XH,getSchemeHandler:yT}=gT();function YH(t,e){return typeof t=="string"?t=Fn(cr(t,e),e):typeof t=="object"&&(t=cr(Fn(t,e),e)),t}function QH(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=_T(cr(t,r),cr(e,r),r,!0);return r.skipEscape=!0,Fn(o,r)}function _T(t,e,n,r){let o={};return r||(t=cr(Fn(t,n),n),e=cr(Fn(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ja(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ja(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ja(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=ja(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function eU(t,e,n){return typeof t=="string"?(t=unescape(t),t=Fn(Tl(cr(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=Fn(Tl(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Fn(Tl(cr(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=Fn(Tl(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Fn(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],s=yT(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let i=KH(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=ja(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var tU=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function cr(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let s=t.match(tU);if(s){if(r.scheme=s[1],r.userinfo=s[3],r.host=s[4],r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=s[7],r.fragment=s[8],isNaN(r.port)&&(r.port=s[5]),r.host)if(GH(r.host)===!1){let c=WH(r.host);r.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let i=yT(n.scheme||r.scheme);if(!n.unicodeSupport&&(!i||!i.unicodeSupport)&&r.host&&(n.domainHost||i&&i.domainHost)&&o===!1&&JH(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(a){r.error=r.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),i&&i.parse&&i.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}var qy={SCHEMES:XH,normalize:YH,resolve:QH,resolveComponent:_T,equal:eU,serialize:Fn,parse:cr};$l.exports=qy;$l.exports.default=qy;$l.exports.fastUri=qy});var ST=L(Vy=>{"use strict";Object.defineProperty(Vy,"__esModule",{value:!0});var bT=xT();bT.code='require("ajv/dist/runtime/uri").default';Vy.default=bT});var RT=L(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.CodeGen=dt.Name=dt.nil=dt.stringify=dt.str=dt._=dt.KeywordCxt=void 0;var nU=Da();Object.defineProperty(dt,"KeywordCxt",{enumerable:!0,get:function(){return nU.KeywordCxt}});var Ys=oe();Object.defineProperty(dt,"_",{enumerable:!0,get:function(){return Ys._}});Object.defineProperty(dt,"str",{enumerable:!0,get:function(){return Ys.str}});Object.defineProperty(dt,"stringify",{enumerable:!0,get:function(){return Ys.stringify}});Object.defineProperty(dt,"nil",{enumerable:!0,get:function(){return Ys.nil}});Object.defineProperty(dt,"Name",{enumerable:!0,get:function(){return Ys.Name}});Object.defineProperty(dt,"CodeGen",{enumerable:!0,get:function(){return Ys.CodeGen}});var rU=Sl(),TT=Ma(),oU=Sy(),La=kl(),sU=oe(),za=Ia(),Pl=Oa(),Ky=me(),vT=aT(),iU=ST(),$T=(t,e)=>new RegExp(t,e);$T.code="new RegExp";var aU=["removeAdditional","useDefaults","coerceTypes"],cU=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),uU={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},lU={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},kT=200;function dU(t){var e,n,r,o,s,i,a,c,u,l,d,p,h,m,f,g,y,_,x,S,E,A,b,T,P;let N=t.strict,R=(e=t.code)===null||e===void 0?void 0:e.optimize,C=R===!0||R===void 0?1:R||0,F=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:$T,W=(o=t.uriResolver)!==null&&o!==void 0?o:iU.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:N)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:N)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:N)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:N)!==null&&p!==void 0?p:"log",strictRequired:(m=(h=t.strictRequired)!==null&&h!==void 0?h:N)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:C,regExp:F}:{optimize:C,regExp:F},loopRequired:(f=t.loopRequired)!==null&&f!==void 0?f:kT,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:kT,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(S=t.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(E=t.addUsedSchema)!==null&&E!==void 0?E:!0,validateSchema:(A=t.validateSchema)!==null&&A!==void 0?A:!0,validateFormats:(b=t.validateFormats)!==null&&b!==void 0?b:!0,unicodeRegExp:(T=t.unicodeRegExp)!==null&&T!==void 0?T:!0,int32range:(P=t.int32range)!==null&&P!==void 0?P:!0,uriResolver:W}}var Fa=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...dU(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new sU.ValueScope({scope:{},prefixes:cU,es5:n,lines:r}),this.logger=yU(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,oU.getRules)(),wT.call(this,uU,e,"NOT SUPPORTED"),wT.call(this,lU,e,"DEPRECATED","warn"),this._metaOpts=hU.call(this),e.formats&&mU.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&fU.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),pU.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=vT;r==="id"&&(o={...vT},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof TT.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,n)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=r(l))}finally{delete this._loading[l]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return n=(0,za.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let n;for(;typeof(n=ET.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new La.SchemaEnv({schema:{},schemaId:r});if(n=La.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=ET.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,za.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(xU.call(this,r,n),!n)return(0,Ky.eachItem)(r,s=>Wy.call(this,s)),this;SU.call(this,n);let o={...n,type:(0,Pl.getJSONTypes)(n.type),schemaType:(0,Pl.getJSONTypes)(n.schemaType)};return(0,Ky.eachItem)(r,o.type.length===0?s=>Wy.call(this,s,o):s=>o.type.forEach(i=>Wy.call(this,s,o,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(s=>s.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,s)=>o+n+s)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=PT(l))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;r=(0,za.normalizeId)(i||r);let u=za.getSchemaRefs.call(this,e,r);return c=new La.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),this._cache.set(c.schema,c),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):La.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{La.compileSchema.call(this,e)}finally{this.opts=n}}};Fa.ValidationError=rU.default;Fa.MissingRefError=TT.default;dt.default=Fa;function wT(t,e,n,r="error"){for(let o in t){let s=o;s in e&&this.logger[r](`${n}: option ${o}. ${t[s]}`)}}function ET(t){return t=(0,za.normalizeId)(t),this.schemas[t]||this.refs[t]}function pU(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function mU(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function fU(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function hU(){let t={...this.opts};for(let e of aU)delete t[e];return t}var gU={log(){},warn(){},error(){}};function yU(t){if(t===!1)return gU;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var _U=/^[a-z_$][a-z0-9_$:-]*$/i;function xU(t,e){let{RULES:n}=this;if((0,Ky.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!_U.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Wy(t,e,n){var r;let o=e?.post;if(n&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===n);if(i||(i={type:n,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Pl.getJSONTypes)(e.type),schemaType:(0,Pl.getJSONTypes)(e.schemaType)}};e.before?bU.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function bU(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function SU(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=PT(e)),t.validateSchema=this.compile(e,!0))}var vU={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function PT(t){return{anyOf:[t,vU]}}});var CT=L(Gy=>{"use strict";Object.defineProperty(Gy,"__esModule",{value:!0});var kU={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Gy.default=kU});var NT=L(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.callRef=Wo.getValidate=void 0;var wU=Ma(),OT=un(),Mt=oe(),Qs=ir(),IT=kl(),Rl=me(),EU={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();let l=IT.resolveRef.call(c,u,o,n);if(l===void 0)throw new wU.default(r.opts.uriResolver,o,n);if(l instanceof IT.SchemaEnv)return p(l);return h(l);function d(){if(s===u)return Cl(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Cl(t,(0,Mt._)`${m}.validate`,u,u.$async)}function p(m){let f=AT(t,m);Cl(t,f,m,m.$async)}function h(m){let f=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Mt.stringify)(m)}:{ref:m}),g=e.name("valid"),y=t.subschema({schema:m,dataTypes:[],schemaPath:Mt.nil,topSchemaRef:f,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function AT(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Mt._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Wo.getValidate=AT;function Cl(t,e,n,r){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Qs.default.this:Mt.nil;r?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Mt._)`await ${(0,OT.callValidateCode)(t,e,u)}`),h(e),i||o.assign(m,!0)},f=>{o.if((0,Mt._)`!(${f} instanceof ${s.ValidationError})`,()=>o.throw(f)),p(f),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,OT.callValidateCode)(t,e,u),()=>h(e),()=>p(e))}function p(m){let f=(0,Mt._)`${m}.errors`;o.assign(Qs.default.vErrors,(0,Mt._)`${Qs.default.vErrors} === null ? ${f} : ${Qs.default.vErrors}.concat(${f})`),o.assign(Qs.default.errors,(0,Mt._)`${Qs.default.vErrors}.length`)}function h(m){var f;if(!s.opts.unevaluated)return;let g=(f=n?.validate)===null||f===void 0?void 0:f.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Rl.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,Mt._)`${m}.evaluated.props`);s.props=Rl.mergeEvaluated.props(o,y,s.props,Mt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Rl.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,Mt._)`${m}.evaluated.items`);s.items=Rl.mergeEvaluated.items(o,y,s.items,Mt.Name)}}}Wo.callRef=Cl;Wo.default=EU});var DT=L(Jy=>{"use strict";Object.defineProperty(Jy,"__esModule",{value:!0});var TU=CT(),$U=NT(),PU=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",TU.default,$U.default];Jy.default=PU});var MT=L(Xy=>{"use strict";Object.defineProperty(Xy,"__esModule",{value:!0});var Ol=oe(),Zr=Ol.operators,Il={maximum:{okStr:"<=",ok:Zr.LTE,fail:Zr.GT},minimum:{okStr:">=",ok:Zr.GTE,fail:Zr.LT},exclusiveMaximum:{okStr:"<",ok:Zr.LT,fail:Zr.GTE},exclusiveMinimum:{okStr:">",ok:Zr.GT,fail:Zr.LTE}},RU={message:({keyword:t,schemaCode:e})=>(0,Ol.str)`must be ${Il[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ol._)`{comparison: ${Il[t].okStr}, limit: ${e}}`},CU={keyword:Object.keys(Il),type:"number",schemaType:"number",$data:!0,error:RU,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Ol._)`${n} ${Il[e].fail} ${r} || isNaN(${n})`)}};Xy.default=CU});var jT=L(Yy=>{"use strict";Object.defineProperty(Yy,"__esModule",{value:!0});var Ha=oe(),OU={message:({schemaCode:t})=>(0,Ha.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ha._)`{multipleOf: ${t}}`},IU={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:OU,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Ha._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Ha._)`${i} !== parseInt(${i})`;t.fail$data((0,Ha._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Yy.default=IU});var zT=L(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});function LT(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}Qy.default=LT;LT.code='require("ajv/dist/runtime/ucs2length").default'});var FT=L(e_=>{"use strict";Object.defineProperty(e_,"__esModule",{value:!0});var Ko=oe(),AU=me(),NU=zT(),DU={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Ko.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Ko._)`{limit: ${t}}`},MU={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:DU,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?Ko.operators.GT:Ko.operators.LT,i=o.opts.unicode===!1?(0,Ko._)`${n}.length`:(0,Ko._)`${(0,AU.useFunc)(t.gen,NU.default)}(${n})`;t.fail$data((0,Ko._)`${i} ${s} ${r}`)}};e_.default=MU});var HT=L(t_=>{"use strict";Object.defineProperty(t_,"__esModule",{value:!0});var jU=un(),LU=me(),ei=oe(),zU={message:({schemaCode:t})=>(0,ei.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ei._)`{pattern: ${t}}`},FU={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:zU,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,ei._)`new RegExp`:(0,LU.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ei._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,ei._)`!${l}`)}else{let c=(0,jU.usePattern)(t,o);t.fail$data((0,ei._)`!${c}.test(${n})`)}}};t_.default=FU});var UT=L(n_=>{"use strict";Object.defineProperty(n_,"__esModule",{value:!0});var Ua=oe(),HU={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Ua.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Ua._)`{limit: ${t}}`},UU={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:HU,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Ua.operators.GT:Ua.operators.LT;t.fail$data((0,Ua._)`Object.keys(${n}).length ${o} ${r}`)}};n_.default=UU});var BT=L(r_=>{"use strict";Object.defineProperty(r_,"__esModule",{value:!0});var Ba=un(),Za=oe(),BU=me(),ZU={message:({params:{missingProperty:t}})=>(0,Za.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Za._)`{missingProperty: ${t}}`},qU={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ZU,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;let c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let h=t.parentSchema.properties,{definedProperties:m}=t.it;for(let f of n)if(h?.[f]===void 0&&!m.has(f)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${f}" is not defined at "${g}" (strictRequired)`;(0,BU.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Za.nil,d);else for(let h of n)(0,Ba.checkReportMissingProp)(t,h)}function l(){let h=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(h,m)),t.ok(m)}else e.if((0,Ba.checkMissingProp)(t,n,h)),(0,Ba.reportMissingProp)(t,h),e.else()}function d(){e.forOf("prop",r,h=>{t.setParams({missingProperty:h}),e.if((0,Ba.noPropertyInData)(e,o,h,a.ownProperties),()=>t.error())})}function p(h,m){t.setParams({missingProperty:h}),e.forOf(h,r,()=>{e.assign(m,(0,Ba.propertyInData)(e,o,h,a.ownProperties)),e.if((0,Za.not)(m),()=>{t.error(),e.break()})},Za.nil)}}};r_.default=qU});var ZT=L(o_=>{"use strict";Object.defineProperty(o_,"__esModule",{value:!0});var qa=oe(),VU={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,qa.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,qa._)`{limit: ${t}}`},WU={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:VU,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?qa.operators.GT:qa.operators.LT;t.fail$data((0,qa._)`${n}.length ${o} ${r}`)}};o_.default=WU});var Al=L(s_=>{"use strict";Object.defineProperty(s_,"__esModule",{value:!0});var qT=Ry();qT.code='require("ajv/dist/runtime/equal").default';s_.default=qT});var VT=L(a_=>{"use strict";Object.defineProperty(a_,"__esModule",{value:!0});var i_=Oa(),pt=oe(),KU=me(),GU=Al(),JU={message:({params:{i:t,j:e}})=>(0,pt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,pt._)`{i: ${t}, j: ${e}}`},XU={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:JU,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),u=s.items?(0,i_.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,pt._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,pt._)`${n}.length`),f=e.let("j");t.setParams({i:m,j:f}),e.assign(c,!0),e.if((0,pt._)`${m} > 1`,()=>(d()?p:h)(m,f))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,f){let g=e.name("item"),y=(0,i_.checkDataTypes)(u,g,a.opts.strictNumbers,i_.DataType.Wrong),_=e.const("indices",(0,pt._)`{}`);e.for((0,pt._)`;${m}--;`,()=>{e.let(g,(0,pt._)`${n}[${m}]`),e.if(y,(0,pt._)`continue`),u.length>1&&e.if((0,pt._)`typeof ${g} == "string"`,(0,pt._)`${g} += "_"`),e.if((0,pt._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(f,(0,pt._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,pt._)`${_}[${g}] = ${m}`)})}function h(m,f){let g=(0,KU.useFunc)(e,GU.default),y=e.name("outer");e.label(y).for((0,pt._)`;${m}--;`,()=>e.for((0,pt._)`${f} = ${m}; ${f}--;`,()=>e.if((0,pt._)`${g}(${n}[${m}], ${n}[${f}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};a_.default=XU});var WT=L(u_=>{"use strict";Object.defineProperty(u_,"__esModule",{value:!0});var c_=oe(),YU=me(),QU=Al(),e2={message:"must be equal to constant",params:({schemaCode:t})=>(0,c_._)`{allowedValue: ${t}}`},t2={keyword:"const",$data:!0,error:e2,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,c_._)`!${(0,YU.useFunc)(e,QU.default)}(${n}, ${o})`):t.fail((0,c_._)`${s} !== ${n}`)}};u_.default=t2});var KT=L(l_=>{"use strict";Object.defineProperty(l_,"__esModule",{value:!0});var Va=oe(),n2=me(),r2=Al(),o2={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Va._)`{allowedValues: ${t}}`},s2={keyword:"enum",schemaType:"array",$data:!0,error:o2,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,n2.useFunc)(e,r2.default)),l;if(a||r)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let h=e.const("vSchema",s);l=(0,Va.or)(...o.map((m,f)=>p(h,f)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,h=>e.if((0,Va._)`${u()}(${n}, ${h})`,()=>e.assign(l,!0).break()))}function p(h,m){let f=o[m];return typeof f=="object"&&f!==null?(0,Va._)`${u()}(${n}, ${h}[${m}])`:(0,Va._)`${n} === ${f}`}}};l_.default=s2});var GT=L(d_=>{"use strict";Object.defineProperty(d_,"__esModule",{value:!0});var i2=MT(),a2=jT(),c2=FT(),u2=HT(),l2=UT(),d2=BT(),p2=ZT(),m2=VT(),f2=WT(),h2=KT(),g2=[i2.default,a2.default,c2.default,u2.default,l2.default,d2.default,p2.default,m2.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},f2.default,h2.default];d_.default=g2});var m_=L(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.validateAdditionalItems=void 0;var Go=oe(),p_=me(),y2={message:({params:{len:t}})=>(0,Go.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Go._)`{limit: ${t}}`},_2={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:y2,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,p_.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}JT(t,r)}};function JT(t,e){let{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;let a=n.const("len",(0,Go._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Go._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,p_.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,Go._)`${a} <= ${e.length}`);n.if((0,Go.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:p_.Type.Num},u),i.allErrors||n.if((0,Go.not)(u),()=>n.break())})}}Wa.validateAdditionalItems=JT;Wa.default=_2});var f_=L(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.validateTuple=void 0;var XT=oe(),Nl=me(),x2=un(),b2={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return YT(t,"additionalItems",e);n.items=!0,!(0,Nl.alwaysValidSchema)(n,e)&&t.ok((0,x2.validateArray)(t))}};function YT(t,e,n=t.schema){let{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Nl.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,XT._)`${s}.length`);n.forEach((d,p)=>{(0,Nl.alwaysValidSchema)(a,d)||(r.if((0,XT._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:h}=a,m=n.length,f=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!f){let g=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,Nl.checkStrictMode)(a,g,p.strictTuples)}}}Ka.validateTuple=YT;Ka.default=b2});var QT=L(h_=>{"use strict";Object.defineProperty(h_,"__esModule",{value:!0});var S2=f_(),v2={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,S2.validateTuple)(t,"items")};h_.default=v2});var t$=L(g_=>{"use strict";Object.defineProperty(g_,"__esModule",{value:!0});var e$=oe(),k2=me(),w2=un(),E2=m_(),T2={message:({params:{len:t}})=>(0,e$.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,e$._)`{limit: ${t}}`},$2={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:T2,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,k2.alwaysValidSchema)(r,e)&&(o?(0,E2.validateAdditionalItems)(t,o):t.ok((0,w2.validateArray)(t)))}};g_.default=$2});var n$=L(y_=>{"use strict";Object.defineProperty(y_,"__esModule",{value:!0});var dn=oe(),Dl=me(),P2={message:({params:{min:t,max:e}})=>e===void 0?(0,dn.str)`must contain at least ${t} valid item(s)`:(0,dn.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,dn._)`{minContains: ${t}}`:(0,dn._)`{minContains: ${t}, maxContains: ${e}}`},R2={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:P2,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,dn._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Dl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Dl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Dl.alwaysValidSchema)(s,n)){let f=(0,dn._)`${l} >= ${i}`;a!==void 0&&(f=(0,dn._)`${f} && ${l} <= ${a}`),t.pass(f);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?h(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,dn._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let f=e.name("_valid"),g=e.let("count",0);h(f,()=>e.if(f,()=>m(g)))}function h(f,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Dl.Type.Num,compositeRule:!0},f),g()})}function m(f){e.code((0,dn._)`${f}++`),a===void 0?e.if((0,dn._)`${f} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,dn._)`${f} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,dn._)`${f} >= ${i}`,()=>e.assign(d,!0)))}}};y_.default=R2});var s$=L(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.validateSchemaDeps=Hn.validatePropertyDeps=Hn.error=void 0;var __=oe(),C2=me(),Ga=un();Hn.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,__.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,__._)`{property: ${t},
|
|
495
|
+
missingProperty: ${r},
|
|
485
496
|
depsCount: ${e},
|
|
486
|
-
deps: ${r}}`};var lU={keyword:"dependencies",type:"object",schemaType:"object",error:Ur.error,code(t){let[e,r]=dU(t);m$(t,e),f$(t,r)}};function dU({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function m$(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,qa.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,qa.checkReportMissingProp)(t,u)}):(r.if((0,Vy._)`${c} && (${(0,qa.checkMissingProp)(t,a,s)})`),(0,qa.reportMissingProp)(t,s),r.else())}}Ur.validatePropertyDeps=m$;function f$(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,uU.alwaysValidSchema)(s,e[a])||(r.if((0,qa.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Ur.validateSchemaDeps=f$;Ur.default=lU});var y$=L(Wy=>{"use strict";Object.defineProperty(Wy,"__esModule",{value:!0});var g$=oe(),pU=me(),mU={message:"property name must be valid",params:({params:t})=>(0,g$._)`{propertyName: ${t.propertyName}}`},fU={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:mU,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,pU.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,g$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Wy.default=fU});var Gy=L(Ky=>{"use strict";Object.defineProperty(Ky,"__esModule",{value:!0});var wl=cr(),Sr=oe(),hU=un(),El=me(),gU={message:"must NOT have additional properties",params:({params:t})=>(0,Sr._)`{additionalProperty: ${t.additionalProperty}}`},yU={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:gU,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,El.alwaysValidSchema)(i,r))return;let u=(0,wl.allSchemaProperties)(n.properties),l=(0,wl.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Sr._)`${s} === ${hU.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?m(g):e.if(p(g),()=>m(g))})}function p(g){let y;if(u.length>8){let _=(0,El.schemaRefOrVal)(i,n.properties,"properties");y=(0,wl.isOwnProperty)(e,_,g)}else u.length?y=(0,Sr.or)(...u.map(_=>(0,Sr._)`${g} === ${_}`)):y=Sr.nil;return l.length&&(y=(0,Sr.or)(y,...l.map(_=>(0,Sr._)`${(0,wl.usePattern)(t,_)}.test(${g})`))),(0,Sr.not)(y)}function h(g){e.code((0,Sr._)`delete ${o}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,El.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(f(g,y,!1),e.if((0,Sr.not)(y),()=>{t.reset(),h(g)})):(f(g,y),a||e.if((0,Sr.not)(y),()=>e.break()))}}function f(g,y,_){let x={keyword:"additionalProperties",dataProp:g,dataPropType:El.Type.Str};_===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,y)}}};Ky.default=yU});var b$=L(Xy=>{"use strict";Object.defineProperty(Xy,"__esModule",{value:!0});var _U=Oa(),_$=cr(),Jy=me(),x$=Gy(),xU={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&x$.default.code(new _U.KeywordCxt(s,x$.default,"additionalProperties"));let i=(0,_$.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Jy.mergeEvaluated.props(e,(0,Jy.toHash)(i),s.props));let a=i.filter(d=>!(0,Jy.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,_$.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Xy.default=xU});var w$=L(Yy=>{"use strict";Object.defineProperty(Yy,"__esModule",{value:!0});var v$=cr(),$l=oe(),S$=me(),k$=me(),bU={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,v$.allSchemaProperties)(r),c=a.filter(f=>(0,S$.alwaysValidSchema)(s,r[f]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof $l.Name)&&(s.props=(0,k$.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let f of a)u&&h(f),s.allErrors?m(f):(e.var(l,!0),m(f),e.if(l))}function h(f){for(let g in u)new RegExp(f).test(g)&&(0,S$.checkStrictMode)(s,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function m(f){e.forIn("key",n,g=>{e.if((0,$l._)`${(0,v$.usePattern)(t,f)}.test(${g})`,()=>{let y=c.includes(f);y||t.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:k$.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,$l._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,$l.not)(l),()=>e.break())})})}}};Yy.default=bU});var E$=L(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});var vU=me(),SU={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,vU.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Qy.default=SU});var $$=L(e_=>{"use strict";Object.defineProperty(e_,"__esModule",{value:!0});var kU=cr(),wU={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:kU.validateUnion,error:{message:"must match a schema in anyOf"}};e_.default=wU});var T$=L(t_=>{"use strict";Object.defineProperty(t_,"__esModule",{value:!0});var Tl=oe(),EU=me(),$U={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Tl._)`{passingSchemas: ${t.passing}}`},TU={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:$U,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,EU.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Tl._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Tl._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Tl.Name)})})}}};t_.default=TU});var P$=L(r_=>{"use strict";Object.defineProperty(r_,"__esModule",{value:!0});var PU=me(),RU={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,PU.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};r_.default=RU});var O$=L(n_=>{"use strict";Object.defineProperty(n_,"__esModule",{value:!0});var Pl=oe(),C$=me(),CU={message:({params:t})=>(0,Pl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Pl._)`{failingKeyword: ${t.ifClause}}`},OU={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:CU,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,C$.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=R$(n,"then"),s=R$(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Pl.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Pl._)`${l}`):t.setParams({ifClause:l})}}}};function R$(t,e){let r=t.schema[e];return r!==void 0&&!(0,C$.alwaysValidSchema)(t,r)}n_.default=OU});var I$=L(o_=>{"use strict";Object.defineProperty(o_,"__esModule",{value:!0});var IU=me(),AU={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,IU.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};o_.default=AU});var A$=L(s_=>{"use strict";Object.defineProperty(s_,"__esModule",{value:!0});var NU=Hy(),DU=u$(),MU=Uy(),jU=d$(),LU=p$(),zU=h$(),FU=y$(),HU=Gy(),UU=b$(),BU=w$(),ZU=E$(),qU=$$(),VU=T$(),WU=P$(),KU=O$(),GU=I$();function JU(t=!1){let e=[ZU.default,qU.default,VU.default,WU.default,KU.default,GU.default,FU.default,HU.default,zU.default,UU.default,BU.default];return t?e.push(DU.default,jU.default):e.push(NU.default,MU.default),e.push(LU.default),e}s_.default=JU});var N$=L(i_=>{"use strict";Object.defineProperty(i_,"__esModule",{value:!0});var Ke=oe(),XU={message:({schemaCode:t})=>(0,Ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ke._)`{format: ${t}}`},YU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:XU,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():h();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),f=r.const("fDef",(0,Ke._)`${m}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Ke._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>r.assign(g,(0,Ke._)`${f}.type || "string"`).assign(y,(0,Ke._)`${f}.validate`),()=>r.assign(g,(0,Ke._)`"string"`).assign(y,f)),t.fail$data((0,Ke.or)(_(),x()));function _(){return c.strictSchema===!1?Ke.nil:(0,Ke._)`${i} && !${y}`}function x(){let v=l.$async?(0,Ke._)`(${f}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Ke._)`${y}(${n})`,E=(0,Ke._)`(typeof ${y} == "function" ? ${v} : ${y}.test(${n}))`;return(0,Ke._)`${y} && ${y} !== true && ${g} === ${e} && !${E}`}}function h(){let m=d.formats[s];if(!m){_();return}if(m===!0)return;let[f,g,y]=x(m);f===e&&t.pass(v());function _(){if(c.strictSchema===!1){d.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function x(E){let C=E instanceof RegExp?(0,Ke.regexpCode)(E):c.code.formats?(0,Ke._)`${c.code.formats}${(0,Ke.getProperty)(s)}`:void 0,b=r.scopeValue("formats",{key:s,ref:E,code:C});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,Ke._)`${b}.validate`]:["string",E,b]}function v(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ke._)`await ${y}(${n})`}return typeof g=="function"?(0,Ke._)`${y}(${n})`:(0,Ke._)`${y}.test(${n})`}}}};i_.default=YU});var D$=L(a_=>{"use strict";Object.defineProperty(a_,"__esModule",{value:!0});var QU=N$(),e2=[QU.default];a_.default=e2});var M$=L(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.contentVocabulary=ri.metadataVocabulary=void 0;ri.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ri.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var L$=L(c_=>{"use strict";Object.defineProperty(c_,"__esModule",{value:!0});var t2=qE(),r2=s$(),n2=A$(),o2=D$(),j$=M$(),s2=[t2.default,r2.default,(0,n2.default)(),o2.default,j$.metadataVocabulary,j$.contentVocabulary];c_.default=s2});var F$=L(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.DiscrError=void 0;var z$;(function(t){t.Tag="tag",t.Mapping="mapping"})(z$||(Rl.DiscrError=z$={}))});var U$=L(l_=>{"use strict";Object.defineProperty(l_,"__esModule",{value:!0});var ni=oe(),u_=F$(),H$=dl(),i2=Ia(),a2=me(),c2={message:({params:{discrError:t,tagName:e}})=>t===u_.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,ni._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},u2={keyword:"discriminator",type:"object",schemaType:"object",error:c2,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,ni._)`${r}${(0,ni.getProperty)(a)}`);e.if((0,ni._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:u_.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let h=p();e.if(!1);for(let m in h)e.elseIf((0,ni._)`${u} === ${m}`),e.assign(c,d(h[m]));e.else(),t.error(!1,{discrError:u_.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(h){let m=e.name("valid"),f=t.subschema({keyword:"oneOf",schemaProp:h},m);return t.mergeEvaluated(f,ni.Name),m}function p(){var h;let m={},f=y(o),g=!0;for(let v=0;v<i.length;v++){let E=i[v];if(E?.$ref&&!(0,a2.schemaHasRulesButRef)(E,s.self.RULES)){let b=E.$ref;if(E=H$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,b),E instanceof H$.SchemaEnv&&(E=E.schema),E===void 0)throw new i2.default(s.opts.uriResolver,s.baseId,b)}let C=(h=E?.properties)===null||h===void 0?void 0:h[a];if(typeof C!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||y(E)),_(C,v)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return m;function y({required:v}){return Array.isArray(v)&&v.includes(a)}function _(v,E){if(v.const)x(v.const,E);else if(v.enum)for(let C of v.enum)x(C,E);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(v,E){if(typeof v!="string"||v in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[v]=E}}}};l_.default=u2});var B$=L((qJ,l2)=>{l2.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var p_=L((Ne,d_)=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.MissingRefError=Ne.ValidationError=Ne.CodeGen=Ne.Name=Ne.nil=Ne.stringify=Ne.str=Ne._=Ne.KeywordCxt=Ne.Ajv=void 0;var d2=zE(),p2=L$(),m2=U$(),Z$=B$(),f2=["/properties"],Cl="http://json-schema.org/draft-07/schema",oi=class extends d2.default{_addVocabularies(){super._addVocabularies(),p2.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(m2.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Z$,f2):Z$;this.addMetaSchema(e,Cl,!1),this.refs["http://json-schema.org/schema"]=Cl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Cl)?Cl:void 0)}};Ne.Ajv=oi;d_.exports=Ne=oi;d_.exports.Ajv=oi;Object.defineProperty(Ne,"__esModule",{value:!0});Ne.default=oi;var h2=Oa();Object.defineProperty(Ne,"KeywordCxt",{enumerable:!0,get:function(){return h2.KeywordCxt}});var si=oe();Object.defineProperty(Ne,"_",{enumerable:!0,get:function(){return si._}});Object.defineProperty(Ne,"str",{enumerable:!0,get:function(){return si.str}});Object.defineProperty(Ne,"stringify",{enumerable:!0,get:function(){return si.stringify}});Object.defineProperty(Ne,"nil",{enumerable:!0,get:function(){return si.nil}});Object.defineProperty(Ne,"Name",{enumerable:!0,get:function(){return si.Name}});Object.defineProperty(Ne,"CodeGen",{enumerable:!0,get:function(){return si.CodeGen}});var g2=ul();Object.defineProperty(Ne,"ValidationError",{enumerable:!0,get:function(){return g2.default}});var y2=Ia();Object.defineProperty(Ne,"MissingRefError",{enumerable:!0,get:function(){return y2.default}})});var Y$=L(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.formatNames=Zr.fastFormats=Zr.fullFormats=void 0;function Br(t,e){return{validate:t,compare:e}}Zr.fullFormats={date:Br(K$,g_),time:Br(f_(!0),y_),"date-time":Br(q$(!0),J$),"iso-time":Br(f_(),G$),"iso-date-time":Br(q$(),X$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:k2,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:C2,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:w2,int32:{type:"number",validate:T2},int64:{type:"number",validate:P2},float:{type:"number",validate:W$},double:{type:"number",validate:W$},password:!0,binary:!0};Zr.fastFormats={...Zr.fullFormats,date:Br(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,g_),time:Br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,y_),"date-time":Br(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,J$),"iso-time":Br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,G$),"iso-date-time":Br(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,X$),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Zr.formatNames=Object.keys(Zr.fullFormats);function _2(t){return t%4===0&&(t%100!==0||t%400===0)}var x2=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,b2=[0,31,28,31,30,31,30,31,31,30,31,30,31];function K$(t){let e=x2.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&_2(r)?29:b2[n])}function g_(t,e){if(t&&e)return t>e?1:t<e?-1:0}var m_=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function f_(t){return function(r){let n=m_.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function y_(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function G$(t,e){if(!(t&&e))return;let r=m_.exec(t),n=m_.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var h_=/t|\s/i;function q$(t){let e=f_(t);return function(n){let o=n.split(h_);return o.length===2&&K$(o[0])&&e(o[1])}}function J$(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function X$(t,e){if(!(t&&e))return;let[r,n]=t.split(h_),[o,s]=e.split(h_),i=g_(r,o);if(i!==void 0)return i||y_(n,s)}var v2=/\/|:/,S2=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function k2(t){return v2.test(t)&&S2.test(t)}var V$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function w2(t){return V$.lastIndex=0,V$.test(t)}var E2=-(2**31),$2=2**31-1;function T2(t){return Number.isInteger(t)&&t<=$2&&t>=E2}function P2(t){return Number.isInteger(t)}function W$(){return!0}var R2=/[^\\]\\Z/;function C2(t){if(R2.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Q$=L(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.formatLimitDefinition=void 0;var O2=p_(),kr=oe(),Vn=kr.operators,Ol={formatMaximum:{okStr:"<=",ok:Vn.LTE,fail:Vn.GT},formatMinimum:{okStr:">=",ok:Vn.GTE,fail:Vn.LT},formatExclusiveMaximum:{okStr:"<",ok:Vn.LT,fail:Vn.GTE},formatExclusiveMinimum:{okStr:">",ok:Vn.GT,fail:Vn.LTE}},I2={message:({keyword:t,schemaCode:e})=>(0,kr.str)`should be ${Ol[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,kr._)`{comparison: ${Ol[t].okStr}, limit: ${e}}`};ii.formatLimitDefinition={keyword:Object.keys(Ol),type:"string",schemaType:"string",$data:!0,error:I2,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new O2.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,kr._)`${p}[${c.schemaCode}]`);t.fail$data((0,kr.or)((0,kr._)`typeof ${h} != "object"`,(0,kr._)`${h} instanceof RegExp`,(0,kr._)`typeof ${h}.compare != "function"`,d(h)))}function l(){let p=c.schema,h=a.formats[p];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:h,code:i.code.formats?(0,kr._)`${i.code.formats}${(0,kr.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,kr._)`${p}.compare(${r}, ${n}) ${Ol[o].fail} 0`}},dependencies:["format"]};var A2=t=>(t.addKeyword(ii.formatLimitDefinition),t);ii.default=A2});var nT=L((Va,rT)=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});var ai=Y$(),N2=Q$(),__=oe(),eT=new __.Name("fullFormats"),D2=new __.Name("fastFormats"),x_=(t,e={keywords:!0})=>{if(Array.isArray(e))return tT(t,e,ai.fullFormats,eT),t;let[r,n]=e.mode==="fast"?[ai.fastFormats,D2]:[ai.fullFormats,eT],o=e.formats||ai.formatNames;return tT(t,o,r,n),e.keywords&&(0,N2.default)(t),t};x_.get=(t,e="full")=>{let n=(e==="fast"?ai.fastFormats:ai.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function tT(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,__._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}rT.exports=Va=x_;Object.defineProperty(Va,"__esModule",{value:!0});Va.default=x_});function M2(){let t=new oT.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,sT.default)(t),t}var oT,sT,Il,iT=S(()=>{oT=xi(p_(),1),sT=xi(nT(),1);Il=class{constructor(e){this._ajv=e??M2()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var Al,aT=S(()=>{jo();Al=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},ga,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Zs,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function cT(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function uT(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var lT=S(()=>{});var Nl,dT=S(()=>{_w();jo();iT();oa();aT();lT();Nl=class extends Ju{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ha.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Il,this.setRequestHandler(Nh,n=>this._oninitialize(n)),this.setNotificationHandler(Dh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Uh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ha.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Al(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=yw(this._capabilities,e)}setRequestHandler(e,r){let o=Dn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(nr(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Nn(Bs,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new Z(G.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=Nn(js,p);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new Z(G.InvalidParams,`Invalid task creation result: ${f}`)}return m.data}let h=Nn(Lu,p);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new Z(G.InvalidParams,`Invalid tools/call result: ${m}`)}return h.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){uT(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&cT(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:y0.includes(r)?r:Rh,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},$u)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Bh,r):this.request({method:"sampling/createMessage",params:e},ga,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Zs,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Zs,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new Z(G.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof Z?i:new Z(G.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Zh,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function b_(t){return!!t&&typeof t=="object"&&mT in t}function fT(t){return t[mT]?.complete}var mT,pT,hT=S(()=>{mT=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(pT||(pT={}))});var gT=S(()=>{});function L2(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!j2.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function z2(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function v_(t){let e=L2(t);return z2(t,e.warnings),e.isValid}var j2,yT=S(()=>{j2=/^[A-Za-z0-9._-]{1,128}$/});var Dl,_T=S(()=>{Dl=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});var Ml=S(()=>{Jc();Jc()});function vT(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function ST(t){return"_def"in t||"_zod"in t||vT(t)}function S_(t){return typeof t!="object"||t===null||ST(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(vT)}function xT(t){if(t){if(S_(t))return Mo(t);if(!ST(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function H2(t){let e=Dn(t);return e?Object.entries(e).map(([r,n])=>{let o=Uk(n),s=Bk(n);return{name:r,description:o,required:!s}}):[]}function Wn(t){let r=Dn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bu(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function bT(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var jl,F2,Wa,kT=S(()=>{dT();oa();Tg();jo();hT();gT();yT();_T();Ml();jl=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Nl(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Dl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Wn(Us)),this.server.assertCanSetRequestHandler(Wn(Bs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Us,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Ds(r.inputSchema);return o?wg(o,{strictUnions:!0,pipeStrategy:"input"}):F2})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Ds(r.outputSchema);o&&(n.outputSchema=wg(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Bs,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Z(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Z(G.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new Z(G.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new Z(G.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof Z&&n.code===G.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Ds(e.inputSchema)??e.inputSchema,i=await _u(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=xu(a);throw new Z(G.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Z(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Ds(e.outputSchema),s=await _u(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=xu(i);throw new Z(G.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,l));let d=await n.taskStore.getTask(c);if(!d)throw new Z(G.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Wn(zu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(zu,async e=>{switch(e.params.ref.type){case"ref/prompt":return A0(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return N0(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new Z(G.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Z(G.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Wa;let s=Dn(n.argsSchema)?.[e.params.argument.name];if(!b_(s))return Wa;let i=fT(s);if(!i)return Wa;let a=await i(e.params.argument.value,e.params.context);return bT(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Wa;throw new Z(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Wa;let s=await o(e.params.argument.value,e.params.context);return bT(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Wn(zs)),this.server.assertCanSetRequestHandler(Wn(Fs)),this.server.assertCanSetRequestHandler(Wn(Mu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(zs,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Fs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Mu,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Z(G.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new Z(G.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Wn(Hs)),this.server.assertCanSetRequestHandler(Wn(ju)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Hs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?H2(r.argsSchema):void 0}))})),this.server.setRequestHandler(ju,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Z(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Z(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Ds(n.argsSchema),s=await _u(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=xu(c);throw new Z(G.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Mo(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Mo(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof Ot?c._def?.innerType:c;return b_(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){v_(e);let l={title:r,description:n,inputSchema:xT(o),outputSchema:xT(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&v_(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Mo(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Mo(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(S_(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!S_(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},F2={type:"object",properties:{}};Wa={completion:{values:[],hasMore:!1}}});function U2(t){return E0.parse(JSON.parse(t))}function wT(t){return JSON.stringify(t)+`
|
|
487
|
-
`}var
|
|
488
|
-
`);if(e===-1)return null;let
|
|
489
|
-
${t}`}function
|
|
497
|
+
deps: ${n}}`};var O2={keyword:"dependencies",type:"object",schemaType:"object",error:Hn.error,code(t){let[e,n]=I2(t);r$(t,e),o$(t,n)}};function I2({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function r$(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let s=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Ga.propertyInData)(n,r,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let u of a)(0,Ga.checkReportMissingProp)(t,u)}):(n.if((0,__._)`${c} && (${(0,Ga.checkMissingProp)(t,a,s)})`),(0,Ga.reportMissingProp)(t,s),n.else())}}Hn.validatePropertyDeps=r$;function o$(t,e=t.schema){let{gen:n,data:r,keyword:o,it:s}=t,i=n.name("valid");for(let a in e)(0,C2.alwaysValidSchema)(s,e[a])||(n.if((0,Ga.propertyInData)(n,r,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>n.var(i,!0)),t.ok(i))}Hn.validateSchemaDeps=o$;Hn.default=O2});var a$=L(x_=>{"use strict";Object.defineProperty(x_,"__esModule",{value:!0});var i$=oe(),A2=me(),N2={message:"property name must be valid",params:({params:t})=>(0,i$._)`{propertyName: ${t.propertyName}}`},D2={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:N2,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,A2.alwaysValidSchema)(o,n))return;let s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,i$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};x_.default=D2});var S_=L(b_=>{"use strict";Object.defineProperty(b_,"__esModule",{value:!0});var Ml=un(),Sn=oe(),M2=ir(),jl=me(),j2={message:"must NOT have additional properties",params:({params:t})=>(0,Sn._)`{additionalProperty: ${t.additionalProperty}}`},L2={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:j2,code(t){let{gen:e,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,jl.alwaysValidSchema)(i,n))return;let u=(0,Ml.allSchemaProperties)(r.properties),l=(0,Ml.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Sn._)`${s} === ${M2.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?m(g):e.if(p(g),()=>m(g))})}function p(g){let y;if(u.length>8){let _=(0,jl.schemaRefOrVal)(i,r.properties,"properties");y=(0,Ml.isOwnProperty)(e,_,g)}else u.length?y=(0,Sn.or)(...u.map(_=>(0,Sn._)`${g} === ${_}`)):y=Sn.nil;return l.length&&(y=(0,Sn.or)(y,...l.map(_=>(0,Sn._)`${(0,Ml.usePattern)(t,_)}.test(${g})`))),(0,Sn.not)(y)}function h(g){e.code((0,Sn._)`delete ${o}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){h(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,jl.alwaysValidSchema)(i,n)){let y=e.name("valid");c.removeAdditional==="failing"?(f(g,y,!1),e.if((0,Sn.not)(y),()=>{t.reset(),h(g)})):(f(g,y),a||e.if((0,Sn.not)(y),()=>e.break()))}}function f(g,y,_){let x={keyword:"additionalProperties",dataProp:g,dataPropType:jl.Type.Str};_===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,y)}}};b_.default=L2});var l$=L(k_=>{"use strict";Object.defineProperty(k_,"__esModule",{value:!0});var z2=Da(),c$=un(),v_=me(),u$=S_(),F2={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&u$.default.code(new z2.KeywordCxt(s,u$.default,"additionalProperties"));let i=(0,c$.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=v_.mergeEvaluated.props(e,(0,v_.toHash)(i),s.props));let a=i.filter(d=>!(0,v_.alwaysValidSchema)(s,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,c$.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};k_.default=F2});var f$=L(w_=>{"use strict";Object.defineProperty(w_,"__esModule",{value:!0});var d$=un(),Ll=oe(),p$=me(),m$=me(),H2={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,d$.allSchemaProperties)(n),c=a.filter(f=>(0,p$.alwaysValidSchema)(s,n[f]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Ll.Name)&&(s.props=(0,m$.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let f of a)u&&h(f),s.allErrors?m(f):(e.var(l,!0),m(f),e.if(l))}function h(f){for(let g in u)new RegExp(f).test(g)&&(0,p$.checkStrictMode)(s,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function m(f){e.forIn("key",r,g=>{e.if((0,Ll._)`${(0,d$.usePattern)(t,f)}.test(${g})`,()=>{let y=c.includes(f);y||t.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:m$.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Ll._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,Ll.not)(l),()=>e.break())})})}}};w_.default=H2});var h$=L(E_=>{"use strict";Object.defineProperty(E_,"__esModule",{value:!0});var U2=me(),B2={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,U2.alwaysValidSchema)(r,n)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};E_.default=B2});var g$=L(T_=>{"use strict";Object.defineProperty(T_,"__esModule",{value:!0});var Z2=un(),q2={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Z2.validateUnion,error:{message:"must match a schema in anyOf"}};T_.default=q2});var y$=L($_=>{"use strict";Object.defineProperty($_,"__esModule",{value:!0});var zl=oe(),V2=me(),W2={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,zl._)`{passingSchemas: ${t.passing}}`},K2={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:W2,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let s=n,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,V2.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,zl._)`${c} && ${i}`).assign(i,!1).assign(a,(0,zl._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,zl.Name)})})}}};$_.default=K2});var _$=L(P_=>{"use strict";Object.defineProperty(P_,"__esModule",{value:!0});var G2=me(),J2={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((s,i)=>{if((0,G2.alwaysValidSchema)(r,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};P_.default=J2});var S$=L(R_=>{"use strict";Object.defineProperty(R_,"__esModule",{value:!0});var Fl=oe(),b$=me(),X2={message:({params:t})=>(0,Fl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Fl._)`{failingKeyword: ${t.ifClause}}`},Y2={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:X2,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,b$.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=x$(r,"then"),s=x$(r,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Fl.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Fl._)`${l}`):t.setParams({ifClause:l})}}}};function x$(t,e){let n=t.schema[e];return n!==void 0&&!(0,b$.alwaysValidSchema)(t,n)}R_.default=Y2});var v$=L(C_=>{"use strict";Object.defineProperty(C_,"__esModule",{value:!0});var Q2=me(),eB={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,Q2.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};C_.default=eB});var k$=L(O_=>{"use strict";Object.defineProperty(O_,"__esModule",{value:!0});var tB=m_(),nB=QT(),rB=f_(),oB=t$(),sB=n$(),iB=s$(),aB=a$(),cB=S_(),uB=l$(),lB=f$(),dB=h$(),pB=g$(),mB=y$(),fB=_$(),hB=S$(),gB=v$();function yB(t=!1){let e=[dB.default,pB.default,mB.default,fB.default,hB.default,gB.default,aB.default,cB.default,iB.default,uB.default,lB.default];return t?e.push(nB.default,oB.default):e.push(tB.default,rB.default),e.push(sB.default),e}O_.default=yB});var w$=L(I_=>{"use strict";Object.defineProperty(I_,"__esModule",{value:!0});var qe=oe(),_B={message:({schemaCode:t})=>(0,qe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,qe._)`{format: ${t}}`},xB={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:_B,code(t,e){let{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():h();function p(){let m=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),f=n.const("fDef",(0,qe._)`${m}[${i}]`),g=n.let("fType"),y=n.let("format");n.if((0,qe._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>n.assign(g,(0,qe._)`${f}.type || "string"`).assign(y,(0,qe._)`${f}.validate`),()=>n.assign(g,(0,qe._)`"string"`).assign(y,f)),t.fail$data((0,qe.or)(_(),x()));function _(){return c.strictSchema===!1?qe.nil:(0,qe._)`${i} && !${y}`}function x(){let S=l.$async?(0,qe._)`(${f}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,qe._)`${y}(${r})`,E=(0,qe._)`(typeof ${y} == "function" ? ${S} : ${y}.test(${r}))`;return(0,qe._)`${y} && ${y} !== true && ${g} === ${e} && !${E}`}}function h(){let m=d.formats[s];if(!m){_();return}if(m===!0)return;let[f,g,y]=x(m);f===e&&t.pass(S());function _(){if(c.strictSchema===!1){d.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function x(E){let A=E instanceof RegExp?(0,qe.regexpCode)(E):c.code.formats?(0,qe._)`${c.code.formats}${(0,qe.getProperty)(s)}`:void 0,b=n.scopeValue("formats",{key:s,ref:E,code:A});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,qe._)`${b}.validate`]:["string",E,b]}function S(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,qe._)`await ${y}(${r})`}return typeof g=="function"?(0,qe._)`${y}(${r})`:(0,qe._)`${y}.test(${r})`}}}};I_.default=xB});var E$=L(A_=>{"use strict";Object.defineProperty(A_,"__esModule",{value:!0});var bB=w$(),SB=[bB.default];A_.default=SB});var T$=L(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.contentVocabulary=ti.metadataVocabulary=void 0;ti.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ti.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var P$=L(N_=>{"use strict";Object.defineProperty(N_,"__esModule",{value:!0});var vB=DT(),kB=GT(),wB=k$(),EB=E$(),$$=T$(),TB=[vB.default,kB.default,(0,wB.default)(),EB.default,$$.metadataVocabulary,$$.contentVocabulary];N_.default=TB});var C$=L(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});Hl.DiscrError=void 0;var R$;(function(t){t.Tag="tag",t.Mapping="mapping"})(R$||(Hl.DiscrError=R$={}))});var I$=L(M_=>{"use strict";Object.defineProperty(M_,"__esModule",{value:!0});var ni=oe(),D_=C$(),O$=kl(),$B=Ma(),PB=me(),RB={message:({params:{discrError:t,tagName:e}})=>t===D_.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,ni._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},CB={keyword:"discriminator",type:"object",schemaType:"object",error:RB,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,ni._)`${n}${(0,ni.getProperty)(a)}`);e.if((0,ni._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:D_.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let h=p();e.if(!1);for(let m in h)e.elseIf((0,ni._)`${u} === ${m}`),e.assign(c,d(h[m]));e.else(),t.error(!1,{discrError:D_.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(h){let m=e.name("valid"),f=t.subschema({keyword:"oneOf",schemaProp:h},m);return t.mergeEvaluated(f,ni.Name),m}function p(){var h;let m={},f=y(o),g=!0;for(let S=0;S<i.length;S++){let E=i[S];if(E?.$ref&&!(0,PB.schemaHasRulesButRef)(E,s.self.RULES)){let b=E.$ref;if(E=O$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,b),E instanceof O$.SchemaEnv&&(E=E.schema),E===void 0)throw new $B.default(s.opts.uriResolver,s.baseId,b)}let A=(h=E?.properties)===null||h===void 0?void 0:h[a];if(typeof A!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||y(E)),_(A,S)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return m;function y({required:S}){return Array.isArray(S)&&S.includes(a)}function _(S,E){if(S.const)x(S.const,E);else if(S.enum)for(let A of S.enum)x(A,E);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(S,E){if(typeof S!="string"||S in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[S]=E}}}};M_.default=CB});var A$=L((AX,OB)=>{OB.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var L_=L((Ie,j_)=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.MissingRefError=Ie.ValidationError=Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=Ie.Ajv=void 0;var IB=RT(),AB=P$(),NB=I$(),N$=A$(),DB=["/properties"],Ul="http://json-schema.org/draft-07/schema",ri=class extends IB.default{_addVocabularies(){super._addVocabularies(),AB.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(NB.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(N$,DB):N$;this.addMetaSchema(e,Ul,!1),this.refs["http://json-schema.org/schema"]=Ul}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ul)?Ul:void 0)}};Ie.Ajv=ri;j_.exports=Ie=ri;j_.exports.Ajv=ri;Object.defineProperty(Ie,"__esModule",{value:!0});Ie.default=ri;var MB=Da();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return MB.KeywordCxt}});var oi=oe();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return oi._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return oi.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return oi.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return oi.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return oi.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return oi.CodeGen}});var jB=Sl();Object.defineProperty(Ie,"ValidationError",{enumerable:!0,get:function(){return jB.default}});var LB=Ma();Object.defineProperty(Ie,"MissingRefError",{enumerable:!0,get:function(){return LB.default}})});var U$=L(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.formatNames=Bn.fastFormats=Bn.fullFormats=void 0;function Un(t,e){return{validate:t,compare:e}}Bn.fullFormats={date:Un(L$,U_),time:Un(F_(!0),B_),"date-time":Un(D$(!0),F$),"iso-time":Un(F_(),z$),"iso-date-time":Un(D$(),H$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:ZB,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:XB,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:qB,int32:{type:"number",validate:KB},int64:{type:"number",validate:GB},float:{type:"number",validate:j$},double:{type:"number",validate:j$},password:!0,binary:!0};Bn.fastFormats={...Bn.fullFormats,date:Un(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,U_),time:Un(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,B_),"date-time":Un(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,F$),"iso-time":Un(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,z$),"iso-date-time":Un(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,H$),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Bn.formatNames=Object.keys(Bn.fullFormats);function zB(t){return t%4===0&&(t%100!==0||t%400===0)}var FB=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,HB=[0,31,28,31,30,31,30,31,31,30,31,30,31];function L$(t){let e=FB.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&zB(n)?29:HB[r])}function U_(t,e){if(t&&e)return t>e?1:t<e?-1:0}var z_=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function F_(t){return function(n){let r=z_.exec(n);if(!r)return!1;let o=+r[1],s=+r[2],i=+r[3],a=r[4],c=r[5]==="-"?-1:1,u=+(r[6]||0),l=+(r[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function B_(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function z$(t,e){if(!(t&&e))return;let n=z_.exec(t),r=z_.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var H_=/t|\s/i;function D$(t){let e=F_(t);return function(r){let o=r.split(H_);return o.length===2&&L$(o[0])&&e(o[1])}}function F$(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function H$(t,e){if(!(t&&e))return;let[n,r]=t.split(H_),[o,s]=e.split(H_),i=U_(n,o);if(i!==void 0)return i||B_(r,s)}var UB=/\/|:/,BB=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function ZB(t){return UB.test(t)&&BB.test(t)}var M$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function qB(t){return M$.lastIndex=0,M$.test(t)}var VB=-(2**31),WB=2**31-1;function KB(t){return Number.isInteger(t)&&t<=WB&&t>=VB}function GB(t){return Number.isInteger(t)}function j$(){return!0}var JB=/[^\\]\\Z/;function XB(t){if(JB.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var B$=L(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.formatLimitDefinition=void 0;var YB=L_(),vn=oe(),qr=vn.operators,Bl={formatMaximum:{okStr:"<=",ok:qr.LTE,fail:qr.GT},formatMinimum:{okStr:">=",ok:qr.GTE,fail:qr.LT},formatExclusiveMaximum:{okStr:"<",ok:qr.LT,fail:qr.GTE},formatExclusiveMinimum:{okStr:">",ok:qr.GT,fail:qr.LTE}},QB={message:({keyword:t,schemaCode:e})=>(0,vn.str)`should be ${Bl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,vn._)`{comparison: ${Bl[t].okStr}, limit: ${e}}`};si.formatLimitDefinition={keyword:Object.keys(Bl),type:"string",schemaType:"string",$data:!0,error:QB,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new YB.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,vn._)`${p}[${c.schemaCode}]`);t.fail$data((0,vn.or)((0,vn._)`typeof ${h} != "object"`,(0,vn._)`${h} instanceof RegExp`,(0,vn._)`typeof ${h}.compare != "function"`,d(h)))}function l(){let p=c.schema,h=a.formats[p];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:h,code:i.code.formats?(0,vn._)`${i.code.formats}${(0,vn.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,vn._)`${p}.compare(${n}, ${r}) ${Bl[o].fail} 0`}},dependencies:["format"]};var eZ=t=>(t.addKeyword(si.formatLimitDefinition),t);si.default=eZ});var W$=L((Ja,V$)=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var ii=U$(),tZ=B$(),Z_=oe(),Z$=new Z_.Name("fullFormats"),nZ=new Z_.Name("fastFormats"),q_=(t,e={keywords:!0})=>{if(Array.isArray(e))return q$(t,e,ii.fullFormats,Z$),t;let[n,r]=e.mode==="fast"?[ii.fastFormats,nZ]:[ii.fullFormats,Z$],o=e.formats||ii.formatNames;return q$(t,o,n,r),e.keywords&&(0,tZ.default)(t),t};q_.get=(t,e="full")=>{let r=(e==="fast"?ii.fastFormats:ii.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function q$(t,e,n,r){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Z_._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}V$.exports=Ja=q_;Object.defineProperty(Ja,"__esModule",{value:!0});Ja.default=q_});function rZ(){let t=new K$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,G$.default)(t),t}var K$,G$,Zl,J$=v(()=>{K$=xi(L_(),1),G$=xi(W$(),1);Zl=class{constructor(e){this._ajv=e??rZ()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}});var ql,X$=v(()=>{zo();ql=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},ba,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Bs,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}}});function Y$(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Q$(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var eP=v(()=>{});var Vl,tP=v(()=>{cE();zo();J$();ca();X$();eP();Vl=class extends cl{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(xa.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new Zl,this.setRequestHandler(ig,r=>this._oninitialize(r)),this.setNotificationHandler(ag,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(fg,async(r,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=xa.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ql(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=aE(this._capabilities,e)}setRequestHandler(e,n){let o=Nr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(rn(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Ar(Us,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new Z(K.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(n(c,u));if(d.task){let m=Ar(js,p);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new Z(K.InvalidParams,`Invalid task creation result: ${f}`)}return m.data}let h=Ar(Ju,p);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new Z(K.InvalidParams,`Invalid tools/call result: ${m}`)}return h.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Q$(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Y$(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:aw.includes(n)?n:tg,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Lu)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},hg,n):this.request({method:"sampling/createMessage",params:e},ba,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Bs,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Bs,n);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new Z(K.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof Z?i:new Z(K.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},gg,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function V_(t){return!!t&&typeof t=="object"&&rP in t}function oP(t){return t[rP]?.complete}var rP,nP,sP=v(()=>{rP=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(nP||(nP={}))});var iP=v(()=>{});function sZ(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!oZ.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,s)=>s.indexOf(r)===o);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function iZ(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function W_(t){let e=sZ(t);return iZ(t,e.warnings),e.isValid}var oZ,aP=v(()=>{oZ=/^[A-Za-z0-9._-]{1,128}$/});var Wl,cP=v(()=>{Wl=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let o={taskSupport:"required",...n.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,o,n._meta,r)}}});var Kl=v(()=>{cu();cu()});function dP(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function pP(t){return"_def"in t||"_zod"in t||dP(t)}function K_(t){return typeof t!="object"||t===null||pP(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(dP)}function uP(t){if(t){if(K_(t))return jo(t);if(!pP(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function cZ(t){let e=Nr(t);return e?Object.entries(e).map(([n,r])=>{let o=I0(r),s=A0(r);return{name:n,description:o,required:!s}}):[]}function Vr(t){let n=Nr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Iu(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function lP(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Gl,aZ,Xa,mP=v(()=>{tP();ca();Qg();zo();sP();iP();aP();cP();Kl();Gl=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Vl(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Wl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Vr(Lo)),this.server.assertCanSetRequestHandler(Vr(Us)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Lo,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let o=Ds(n.inputSchema);return o?Jg(o,{strictUnions:!0,pipeStrategy:"input"}):aZ})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let o=Ds(n.outputSchema);o&&(r.outputSchema=Jg(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Us,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Z(K.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Z(K.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=r.execution?.taskSupport,i="createTask"in r.handler;if((s==="required"||s==="optional")&&!i)throw new Z(K.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new Z(K.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,a,n);return o||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof Z&&r.code===K.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let s=Ds(e.inputSchema)??e.inputSchema,i=await Cu(s,n);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ou(a);throw new Z(K.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new Z(K.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=Ds(e.outputSchema),s=await Cu(o,n.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ou(i);throw new Z(K.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(n,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(n,r))}else{let i=o;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,n.params.arguments,n.params.name),s=e.handler,i={...r,taskStore:r.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,l));let d=await r.taskStore.getTask(c);if(!d)throw new Z(K.InternalError,`Task ${c} not found during polling`);u=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Vr(Xu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Xu,async e=>{switch(e.params.ref.type){case"ref/prompt":return kw(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return ww(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(K.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new Z(K.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new Z(K.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return Xa;let s=Nr(r.argsSchema)?.[e.params.argument.name];if(!V_(s))return Xa;let i=oP(s);if(!i)return Xa;let a=await i(e.params.argument.value,e.params.context);return lP(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return Xa;throw new Z(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Xa;let s=await o(e.params.argument.value,e.params.context);return lP(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Vr(zs)),this.server.assertCanSetRequestHandler(Vr(Fs)),this.server.assertCanSetRequestHandler(Vr(Ku)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(zs,async(e,n)=>{let r=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(n);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...r,...o]}}),this.server.setRequestHandler(Fs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Ku,async(e,n)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new Z(K.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,n)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(r.toString());if(i)return s.readCallback(r,i,n)}throw new Z(K.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Vr(Hs)),this.server.assertCanSetRequestHandler(Vr(Gu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Hs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?cZ(n.argsSchema):void 0}))})),this.server.setRequestHandler(Gu,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Z(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Z(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=Ds(r.argsSchema),s=await Cu(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Ou(c);throw new Z(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let o=r.callback;return await Promise.resolve(o(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let o;typeof r[0]=="object"&&(o=r.shift());let s=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,o){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let s=this._createRegisteredResource(e,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,n,r,o,s){let i={name:e,title:n,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==r&&(delete this._registeredResources[r],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,n,r,o,s){let i={resourceTemplate:r,title:n,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,o,s){let i={title:n,description:r,argsSchema:o===void 0?void 0:jo(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=jo(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof Ct?c._def?.innerType:c;return V_(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,o,s,i,a,c,u){W_(e);let l={title:n,description:r,inputSchema:uP(o),outputSchema:uP(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&W_(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=jo(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=jo(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,o,s,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let c=n[0];if(K_(c))o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!K_(n[0])&&(i=n.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=n;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let o;n.length>1&&(o=n.shift());let s=n[0],i=this._createRegisteredPrompt(e,void 0,r,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=n,a=this._createRegisteredPrompt(e,o,s,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},aZ={type:"object",properties:{}};Xa={completion:{values:[],hasMore:!1}}});function uZ(t){return hw.parse(JSON.parse(t))}function fP(t){return JSON.stringify(t)+`
|
|
498
|
+
`}var Jl,hP=v(()=>{zo();Jl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
499
|
+
`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),uZ(n)}clear(){this._buffer=void 0}}});import gP from"node:process";var Xl,yP=v(()=>{hP();Xl=class{constructor(e=gP.stdin,n=gP.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Jl,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{this.onerror?.(r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(n=>{let r=fP(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}}});var RP={};_e(RP,{PolyglotExecutor:()=>ai,buildPowerShellScriptContent:()=>$P,buildScriptFilename:()=>wP,buildShellScriptContent:()=>TP,buildSpawnOptions:()=>EP,rewriteWindowsBuildTools:()=>PP});import{spawn as _P,execSync as lZ,execFileSync as vP}from"node:child_process";import{mkdtempSync as dZ,writeFileSync as xP,rmSync as pZ,existsSync as bP}from"node:fs";import{join as Yl,resolve as kP}from"node:path";import{tmpdir as mZ}from"node:os";function wP(t,e,n){if(e==="win32"&&t==="shell"){let r=n?.toLowerCase()??"";if(r.includes("powershell")||r.includes("pwsh"))return"script.ps1";let o=r.split(/[\\/]/).pop()??r;return o==="cmd"||o==="cmd.exe"?"script.cmd":"script"}return`script.${fZ[t]}`}function EP(t){return{windowsHide:t==="win32"}}function hZ(t){return`'${t.replace(/'/g,"'\\''")}'`}function TP(t,e,n){return n==="win32"||!e?t:`export PATH=${hZ(e)}
|
|
500
|
+
${t}`}function gZ(t){let e=t?.toLowerCase()??"";return e.includes("powershell")||e.includes("pwsh")}function $P(t){return["\uFEFF[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()","[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()","$OutputEncoding = [System.Text.UTF8Encoding]::new()",t].join(`
|
|
501
|
+
`)}function PP(t,e){if(e!=="win32")return t;let n=new Set([";","&","|","(",`
|
|
502
|
+
`]),r="",o=!0,s=0;for(;s<t.length;){let i=t[s];if(o&&(i===" "||i===" ")){r+=i,s++;continue}if(o&&t.startsWith("mvn",s)){let a=t[s+3];if(a===void 0||a===" "||a===" "||a===`
|
|
503
|
+
`){r+="mvn.cmd",s+=3,o=!1;continue}}r+=i,o=n.has(i),s++}return r}function SP(t){try{pZ(t,{recursive:!0,force:!0,maxRetries:jt?8:2,retryDelay:100})}catch{}}function G_(t){if(jt&&t.pid)try{lZ(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var jt,fZ,yZ,ai,J_=v(()=>{"use strict";Yo();jt=process.platform==="win32",fZ={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};yZ=(()=>{if(jt)return process.env.TEMP??process.env.TMP??mZ();try{let t=vP(process.platform==="darwin"?"getconf":"mktemp",process.platform==="darwin"?["DARWIN_USER_TEMP_DIR"]:["-u","-d"],{env:{...process.env,TMPDIR:void 0},encoding:"utf-8"}).trim(),e=process.platform==="darwin"?t:kP(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();ai=class{#e;#t;#n;#o=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let n=e?.projectRoot;typeof n=="function"?this.#t=n:typeof n=="string"?this.#t=()=>n:this.#t=()=>process.cwd(),this.#n=e?.runtimes??Xr()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(jt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:n,code:r,timeout:o,background:s=!1,cwd:i}=e,a=dZ(Yl(yZ,".ctx-mode-"));try{let c=this.#a(a,r,n),u=tp(this.#n,n,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,o);let l=i??this.#s,d=await this.#i(u,l,a,o,s);return d.backgrounded||SP(a),d}catch(c){throw SP(a),c}}async executeFile(e){let{path:n,language:r,code:o,timeout:s}=e,i=kP(this.#s,n),a=this.#l(i,r,o);return this.execute({language:r,code:a,timeout:s})}#a(e,n,r){r==="go"&&!n.includes("package ")&&(n=`package main
|
|
490
504
|
|
|
491
505
|
import "fmt"
|
|
492
506
|
|
|
493
507
|
func main() {
|
|
494
|
-
${
|
|
508
|
+
${n}
|
|
495
509
|
}
|
|
496
|
-
`),
|
|
497
|
-
${
|
|
510
|
+
`),r==="php"&&!n.trimStart().startsWith("<?")&&(n=`<?php
|
|
511
|
+
${n}`),r==="elixir"&&bP(Yl(this.#s,"mix.exs"))&&(n=`Path.wildcard(Path.join(${JSON.stringify(Yl(this.#s,"_build/dev/lib"))}, "*/ebin"))
|
|
498
512
|
|> Enum.each(&Code.prepend_path/1)
|
|
499
513
|
|
|
500
|
-
${
|
|
501
|
-
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],
|
|
502
|
-
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:
|
|
514
|
+
${n}`);let o=Yl(e,wP(r,process.platform,r==="shell"?this.#n.shell:null));if(r==="shell"){let s=this.#n.shell,i=PP(n,process.platform),a=jt&&gZ(s)?$P(i):i;xP(o,TP(a,process.env.PATH,process.platform),{encoding:"utf-8",mode:448})}else xP(o,n,"utf-8");return o}async#c(e,n,r){let o=jt?".exe":"",s=e.replace(/\.rs$/,"")+o;try{vP("rustc",[e,"-o",s],{cwd:n,timeout:r===void 0?6e4:Math.min(r,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
|
|
515
|
+
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],n,n,r)}async#i(e,n,r,o,s=!1){return new Promise(i=>{let a=jt&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;jt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=jt?e.slice(1).map(x=>x.replace(/\\/g,"/")):e.slice(1);let l={cwd:n,stdio:["ignore","pipe","pipe"],env:this.#u(r),detached:!jt,...EP(process.platform)},d;if(a){let x=[c,...u].map(S=>/\s/.test(S)?JSON.stringify(S):S).join(" ");d=_P(x,[],{...l,shell:!0})}else d=_P(c,u,{...l,shell:!1});let p=!1,h=!1,m=o===void 0?void 0:setTimeout(()=>{if(p=!0,s){h=!0,d.pid&&this.#o.add(d.pid),d.unref(),d.stdout&&(d.stdout.removeAllListeners("data"),d.stdout.on("data",()=>{})),d.stderr&&(d.stderr.removeAllListeners("data"),d.stderr.on("data",()=>{}));let x=Buffer.concat(f).toString("utf-8"),S=Buffer.concat(g).toString("utf-8");i({stdout:x,stderr:S,exitCode:0,timedOut:!0,backgrounded:!0})}else G_(d)},o),f=[],g=[],y=0,_=!1;d.stdout.on("data",x=>{y+=x.length,y<=this.#e?f.push(x):_||(_=!0,G_(d))}),d.stderr.on("data",x=>{y+=x.length,y<=this.#e?g.push(x):_||(_=!0,G_(d))}),d.on("close",x=>{if(clearTimeout(m),h)return;let S=Buffer.concat(f).toString("utf-8"),E=Buffer.concat(g).toString("utf-8");_&&(E+=`
|
|
516
|
+
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:S,stderr:E,exitCode:p?1:x??1,timedOut:p})}),d.on("error",x=>{clearTimeout(m),!h&&i({stdout:"",stderr:x.message,exitCode:1,timedOut:!1})})})}#u(e){let n=process.env.HOME??process.env.USERPROFILE??e,r=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","DOTNET_STARTUP_HOOKS","DOTNET_ADDITIONAL_DEPS","DOTNET_SHARED_STORE","DOTNET_ROOT","DOTNET_ROOT(x86)","DOTNET_HOST_PATH","CORECLR_PROFILER","CORECLR_PROFILER_PATH","CORECLR_PROFILER_PATH_32","CORECLR_PROFILER_PATH_64","CORECLR_PROFILER_PATH_ARM32","CORECLR_PROFILER_PATH_ARM64","CORECLR_ENABLE_PROFILING","DOTNET_PROFILER_PATH","DOTNET_PROFILER_PATH_32","DOTNET_PROFILER_PATH_64","DOTNET_PROFILER_PATH_ARM32","DOTNET_PROFILER_PATH_ARM64","DOTNET_DiagnosticPorts","DOTNET_BUNDLE_EXTRACT_BASE_DIR","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),o={};for(let[s,i]of Object.entries(process.env))i!==void 0&&!r.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=n,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",jt&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=jt?"":"/usr/local/bin:/usr/bin:/bin"),jt){for(let a of Object.keys(o)){let c=a.toUpperCase();(c==="MSYS_NO_PATHCONV"||c==="MSYS2_ARG_CONV_EXCL")&&delete o[a]}let s="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";o.PATH.includes(s)||(o.PATH=`${s};${i};${o.PATH}`)}if(!o.SSL_CERT_FILE){let s=jt?[]:["/etc/ssl/cert.pem","/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"];for(let i of s)if(bP(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,n,r){let o=JSON.stringify(e);switch(n){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
|
|
503
517
|
const file_path = FILE_CONTENT_PATH;
|
|
504
518
|
const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
|
|
505
|
-
${
|
|
519
|
+
${r}`;case"python":return`FILE_CONTENT_PATH = ${o}
|
|
506
520
|
file_path = FILE_CONTENT_PATH
|
|
507
521
|
with open(FILE_CONTENT_PATH, "r", encoding="utf-8") as _f:
|
|
508
522
|
FILE_CONTENT = _f.read()
|
|
509
|
-
${
|
|
523
|
+
${r}`;case"shell":{let s="'"+e.replace(/'/g,"'\\''")+"'";return`FILE_CONTENT_PATH=${s}
|
|
510
524
|
file_path=${s}
|
|
511
525
|
FILE_CONTENT=$(cat ${s})
|
|
512
|
-
${
|
|
526
|
+
${r}`}case"ruby":return`FILE_CONTENT_PATH = ${o}
|
|
513
527
|
file_path = FILE_CONTENT_PATH
|
|
514
528
|
FILE_CONTENT = File.read(FILE_CONTENT_PATH, encoding: "utf-8")
|
|
515
|
-
${
|
|
529
|
+
${r}`;case"go":return`package main
|
|
516
530
|
|
|
517
531
|
import (
|
|
518
532
|
"fmt"
|
|
@@ -527,7 +541,7 @@ func main() {
|
|
|
527
541
|
FILE_CONTENT := string(b)
|
|
528
542
|
_ = FILE_CONTENT
|
|
529
543
|
_ = fmt.Sprint()
|
|
530
|
-
${
|
|
544
|
+
${r}
|
|
531
545
|
}
|
|
532
546
|
`;case"rust":return`#![allow(unused_variables)]
|
|
533
547
|
use std::fs;
|
|
@@ -536,48 +550,48 @@ fn main() {
|
|
|
536
550
|
let file_content_path = ${o};
|
|
537
551
|
let file_path = file_content_path;
|
|
538
552
|
let file_content = fs::read_to_string(file_content_path).unwrap();
|
|
539
|
-
${
|
|
553
|
+
${r}
|
|
540
554
|
}
|
|
541
555
|
`;case"php":return`<?php
|
|
542
556
|
$FILE_CONTENT_PATH = ${o};
|
|
543
557
|
$file_path = $FILE_CONTENT_PATH;
|
|
544
558
|
$FILE_CONTENT = file_get_contents($FILE_CONTENT_PATH);
|
|
545
|
-
${
|
|
559
|
+
${r}`;case"perl":return`my $FILE_CONTENT_PATH = ${o};
|
|
546
560
|
my $file_path = $FILE_CONTENT_PATH;
|
|
547
561
|
open(my $fh, '<:encoding(UTF-8)', $FILE_CONTENT_PATH) or die "Cannot open: $!";
|
|
548
562
|
my $FILE_CONTENT = do { local $/; <$fh> };
|
|
549
563
|
close($fh);
|
|
550
|
-
${
|
|
564
|
+
${r}`;case"r":return`FILE_CONTENT_PATH <- ${o}
|
|
551
565
|
file_path <- FILE_CONTENT_PATH
|
|
552
566
|
FILE_CONTENT <- readLines(FILE_CONTENT_PATH, warn=FALSE, encoding="UTF-8")
|
|
553
567
|
FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
|
|
554
|
-
${
|
|
568
|
+
${r}`;case"elixir":return`file_content_path = ${o}
|
|
555
569
|
file_path = file_content_path
|
|
556
570
|
file_content = File.read!(file_content_path)
|
|
557
|
-
${
|
|
571
|
+
${r}`;case"csharp":return`var FILE_CONTENT_PATH = ${o};
|
|
558
572
|
var file_path = FILE_CONTENT_PATH;
|
|
559
573
|
var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
|
|
560
|
-
${
|
|
574
|
+
${r}`}}}});import{cpus as _Z}from"node:os";async function X_(t,e){let{concurrency:n,capByCpuCount:r=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,n),i=r?Math.max(1,_Z().length):s,a=Math.min(s,i,t.length),c=a<s,u=new Array(t.length),l=0;async function d(){for(;;){let h=l++;if(h>=t.length)return;try{let m=await t[h].run();u[h]={status:"fulfilled",value:m}}catch(m){u[h]={status:"rejected",reason:m}}o?.(h,u[h])}}let p=[];for(let h=0;h<a;h++)p.push(d());return await Promise.allSettled(p),{settled:u,effectiveConcurrency:a,capped:c}}var CP=v(()=>{"use strict"});function Y_(t,e){return t===void 0?e:`${t}::${e}`}var OP=v(()=>{"use strict"});function Q_(t){let{language:e,exitCode:n,stdout:r,stderr:o}=t,s=e==="shell"&&n===1&&r.trim().length>0;return{isError:!s,output:s?r:`Exit code: ${n}
|
|
561
575
|
|
|
562
576
|
stdout:
|
|
563
|
-
${
|
|
577
|
+
${r}
|
|
564
578
|
|
|
565
579
|
stderr:
|
|
566
|
-
${o}`}}var
|
|
567
|
-
`)}for(let f of m){if(s.length>=e)break;try{let g;try{if(g=
|
|
568
|
-
|
|
569
|
-
`,
|
|
570
|
-
|
|
571
|
-
`,P);N>=0&&(
|
|
572
|
-
`)}}return s.slice(0,e)}function
|
|
573
|
-
`)}try{let f=
|
|
574
|
-
`)}if(o==="timeline"){try{if(a){let f=a.searchEvents(e,
|
|
575
|
-
`)}try{let f=
|
|
576
|
-
`)}}for(let f of p)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return o==="timeline"&&p.sort((f,g)=>(f.timestamp||"").localeCompare(g.timestamp||"")),p.slice(0,
|
|
577
|
-
`).slice(0,10))if(a.trim())try{let c=JSON.parse(a);if(typeof c.cwd=="string"&&c.cwd.length>0)return c.cwd}catch{}}finally{
|
|
578
|
-
`).slice(0,10))if(h.trim())try{let m=JSON.parse(h),f=m?.meta?.cwd??(m?.type==="session_meta"?m?.payload?.cwd:void 0);if(typeof f!="string"||f.length===0)continue;return
|
|
579
|
-
FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function
|
|
580
|
-
FROM chunks`).get();return Number(o?.bytes??0)}finally{
|
|
580
|
+
${o}`}}var IP=v(()=>{"use strict"});import{execFileSync as xZ}from"node:child_process";function bZ(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=xZ("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),n=parseInt(e,10);return Number.isFinite(n)?n:NaN}catch{return NaN}}function SZ(t={}){let e=t.getPpid??(()=>process.ppid),n=t.readGrandparentPpid??bZ,r=e(),o=n();return()=>{let s=e();return!(s!==r||s===0||s===1||!Number.isNaN(o)&&o>1&&n()===1)}}function kZ(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<=0?3e4:1e3}function AP(t){let e=t.checkIntervalMs??kZ(),n=t.isParentAlive??vZ,r=!1,o=()=>{r||(r=!0,t.onShutdown())},s=setInterval(()=>{n()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,o);let a=()=>{n()||o()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{r=!0,clearInterval(s);for(let c of i)process.removeListener(c,o);process.stdin.removeListener("end",a)}}var vZ,NP=v(()=>{"use strict";vZ=SZ()});function DP(t,e){if(e<=0)return"";if(t.length<=e)return t;let n=e,r=t.charCodeAt(n-1);return r>=55296&&r<=56319&&(n-=1),t.slice(0,n)}var MP=v(()=>{"use strict"});import{existsSync as ex,unlinkSync as wZ}from"node:fs";import{join as Ya}from"node:path";function tx(t,e){try{return wZ(t),e.push(t),!0}catch{return!1}}function Ql(t,e){let n=!1;for(let r of EZ)tx(`${t}${r}`,e)&&r===""&&(n=!0);return n}function jP(t){let{projectDir:e,sessionsDir:n,storePath:r,contentDir:o,legacyContentDir:s,contentHash:i,sessionId:a,scope:c}=t,u=[],l=[],d=c??(a?"session":"project");if(d==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(d==="session"&&a){let x=Ci(e),S=rt(e),E=On(e),A=S===E?[S]:[S,E],b=!1;for(let N of A){let R=Ya(n,`${N}${x}.db`);if(!ex(R))continue;let C=null;try{C=new Gt({dbPath:R});let F=C.getEvents(a).length;C.deleteSession(a),F>0&&(b=!0)}catch{}finally{try{C?.close()}catch{}}}b&&u.push(`session rows for ${a}`);let T=[];if(r&&ex(r)&&T.push(r),o){let N=rt(e),R=On(e),C=N===R?[N]:[N,R];for(let F of C){let W=Ya(o,`${F}.db`);ex(W)&&!T.includes(W)&&T.push(W)}}let P=!1;for(let N of T)try{let R=nt(),C=new R(N,{timeout:3e4});try{let F=C.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;C.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),C.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),F>0&&(P=!0)}finally{try{C.close()}catch{}}}catch{}return P&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let p=!1;if(r&&Ql(r,l)&&(p=!0),o){let x=rt(e),S=On(e),E=x===S?[x]:[x,S];for(let A of E){let b=Ya(o,`${A}.db`);Ql(b,l)&&(p=!0)}}if(p&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let x=Ya(s,`${i}.db`);Ql(x,l)}let h=Ci(e),m=rt(e),f=On(e),g=m===f?[m]:[m,f],y=!1,_=!1;for(let x of g){let S=Ya(n,`${x}${h}`);Ql(`${S}.db`,l)&&(y=!0),tx(`${S}-events.md`,l)&&(_=!0),tx(`${S}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}var EZ,LP=v(()=>{"use strict";yr();Jt();EZ=["","-wal","-shm"]});import{existsSync as TZ}from"node:fs";function nx(t,e){try{if(!TZ(t))return;let n=new Gt({dbPath:t});try{let r=n.getLatestSessionId();if(!r)return;e(n,r)}finally{try{n.close()}catch{}}}catch{}}function zP(t){nx(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function FP(t){nx(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function HP(t){nx(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}var UP=v(()=>{"use strict";Jt()});import{existsSync as BP}from"node:fs";function ZP(t,e,n){try{if(!BP(t))return;let r=new Gt({dbPath:t});try{let o=r.getLatestSessionId();if(!o)return;r.incrementToolCall(o,e,n)}finally{r.close()}}catch{}}function qP(t){try{if(!BP(t))return null;let e=new Gt({dbPath:t});try{let n=e.getLatestSessionId();if(!n)return null;let r=e.getToolCallStats(n),o={},s={};for(let[a,c]of Object.entries(r.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(n);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(o).length===0&&Object.keys(s).length===0?{calls:o,bytesReturned:s,sessionStart:i}:{calls:o,bytesReturned:s,sessionStart:i}}finally{e.close()}}catch{return null}}var VP=v(()=>{"use strict";Jt()});import{existsSync as rx,readFileSync as $Z,readdirSync as PZ,statSync as RZ}from"node:fs";import{join as ci,isAbsolute as CZ}from"node:path";function GP(t,e=5,n,r,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?KP(n,a):null)??r??Be(),l=o?.getMemoryDir(n),d=ci(u,"memory"),p=n?ci(d,rt(n)):d,h=l?KP(n,l):p,m=[];if(n)for(let f of i){let g=ci(n,f);rx(g)&&m.push({path:g,label:`project/${f}`})}if(u&&u!==n)for(let f of i){let g=ci(u,f);rx(g)&&m.push({path:g,label:`user/${f}`})}if(h&&rx(h))try{let f=PZ(h).filter(g=>g.endsWith(".md"));for(let g of f)m.push({path:ci(h,g),label:`memory/${g}`})}catch(f){WP&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${f}
|
|
581
|
+
`)}for(let f of m){if(s.length>=e)break;try{let g;try{if(g=RZ(f.path),g.size>1e6)continue}catch{continue}let y=$Z(f.path,"utf-8"),_=y.toLowerCase();for(let x of t){if(s.length>=e)break;let E=x.toLowerCase().split(/\s+/).filter(b=>b.length>=3);if(E.some(b=>{try{return new RegExp(`\\b${b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return _.includes(b)}})){let b=E.reduce((F,W)=>{let ge=_.indexOf(W);return ge>=0&&(F<0||ge<F)?ge:F},-1),T=Math.max(0,b-200),P=Math.min(y.length,b+500),N=y.lastIndexOf(`
|
|
582
|
+
|
|
583
|
+
`,T),R=y.indexOf(`
|
|
584
|
+
|
|
585
|
+
`,P);N>=0&&(T=N+2),R>=0&&(P=R);let C=y.slice(T,P).trim();s.push({title:`[auto-memory] ${f.label}`,content:C,source:f.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){WP&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
|
|
586
|
+
`)}}return s.slice(0,e)}function KP(t,e){return e?CZ(e)||!t?e:ci(t,e):t??""}var WP,JP=v(()=>{"use strict";kr();Jt();WP=process.env.DEBUG?.includes("context-mode")});function XP(t){let{query:e,limit:n,store:r,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l,projectScope:d}=t,p=[],h=new Date().toISOString(),m;if(typeof d=="string"&&a)try{m=new Set(a.getSessionIdsForProject(d))}catch(f){ed&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${f}
|
|
587
|
+
`)}try{let f=r.searchWithFallback(e,n,s,i,"like",m);p.push(...f.map(g=>({title:g.title,content:g.content,source:g.source,origin:"current-session",timestamp:g.timestamp||h,rank:g.rank,matchLayer:g.matchLayer,highlighted:g.highlighted,contentType:g.contentType})))}catch(f){ed&&process.stderr.write(`[ctx] ContentStore search failed: ${f}
|
|
588
|
+
`)}if(o==="timeline"){try{if(a){let f=a.searchEvents(e,n,c||"",s);p.push(...f.map(g=>({title:`[${g.category}] ${g.type}`,content:g.data,source:"prior-session",origin:"prior-session",timestamp:g.created_at})))}}catch(f){ed&&process.stderr.write(`[ctx] SessionDB search failed: ${f}
|
|
589
|
+
`)}try{let f=GP([e],n,c,u,l);p.push(...f)}catch(f){ed&&process.stderr.write(`[ctx] auto-memory search failed: ${f}
|
|
590
|
+
`)}}for(let f of p)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return o==="timeline"&&p.sort((f,g)=>(f.timestamp||"").localeCompare(g.timestamp||"")),p.slice(0,n)}var ed,YP=v(()=>{"use strict";JP();ed=process.env.DEBUG?.includes("context-mode")});function OZ(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function QP(t){let e=t?{project:j.string().optional().describe("Project scope. Default (omit): this session's project \u2014 auto-resolved from the host adapter. 'global': span every project in the shared store (cross-project recall). <absolute-path>: scope to that specific project directory.")}:{};return j.object({queries:j.preprocess(OZ,j.array(j.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:j.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:j.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:j.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:j.enum(["relevance","timeline"]).optional().default("relevance").describe("Sort mode. 'relevance' (default): BM25 ranked, current session only. 'timeline': chronological across current session, prior sessions, and auto-memory."),...e})}function eR(t,e,n){if(e)return t===void 0?n():t==="global"?null:t}var ox,tR=v(()=>{"use strict";Kl();ox=!!process.env.CONTEXT_MODE_PROJECT_DIR});var td,nR=v(()=>{"use strict";td=class{#e;#t=new Map;#n;constructor(e,n=4096){this.#e=e,this.#n=Math.max(1,n)}record(e,n=Date.now()){let r=this.#t.get(e);return(!r||n-r.windowStart>this.#e.windowMs)&&(r={count:0,windowStart:n},this.#t.set(e,r),this.#o()),r.count++,{count:r.count,windowStart:r.windowStart,blocked:r.count>this.#e.blockAfter,softCapped:r.count>this.#e.softCapAfter}}size(){return this.#t.size}#o(){if(this.#t.size<=this.#n)return;let e,n=1/0;for(let[r,o]of this.#t)o.windowStart<n&&(n=o.windowStart,e=r);e!==void 0&&this.#t.delete(e)}}});import*as Xe from"node:fs";import*as rR from"node:os";import*as ui from"node:path";function nd(t){return t?/[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function NZ(t){if(!Xe.existsSync(t.projectsRoot))return;let e,n=0;try{for(let r of Xe.readdirSync(t.projectsRoot)){let o=ui.join(t.projectsRoot,r),s;try{s=Xe.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=Xe.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=ui.join(o,a);try{let u=Xe.statSync(c).mtimeMs;u>n&&(n=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-n>t.maxAgeMs))try{let r=Xe.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Xe.readSync(r,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
|
|
591
|
+
`).slice(0,10))if(a.trim())try{let c=JSON.parse(a);if(typeof c.cwd=="string"&&c.cwd.length>0)return c.cwd}catch{}}finally{Xe.closeSync(r)}}catch{}}function DZ(t){let e=t?.codexHome??process.env.CODEX_HOME??ui.join(rR.homedir(),".codex"),n=ui.join(e,"sessions");if(!Xe.existsSync(n))return null;let r=4,o=1e4,s=0,i,a=0,c=(u,l)=>{if(s>=o)return;let d;try{d=Xe.readdirSync(u)}catch{return}d.sort().reverse();for(let p of d){if(s>=o)return;s++;let h=ui.join(u,p),m;try{m=Xe.statSync(h)}catch{continue}if(m.isDirectory()){l<r&&c(h,l+1);continue}if(!m.isFile()||!p.endsWith(".jsonl"))continue;let f=m.mtimeMs;f>a&&(a=f,i=h)}};try{c(n,0)}catch{return null}if(!i||typeof t?.transcriptMaxAgeMs=="number"&&(t.now??Date.now())-a>t.transcriptMaxAgeMs)return null;try{let u=Xe.openSync(i,"r");try{let l=Buffer.alloc(1048576),d=Xe.readSync(u,l,0,l.length,0),p=l.subarray(0,d).toString("utf-8");for(let h of p.split(`
|
|
592
|
+
`).slice(0,10))if(h.trim())try{let m=JSON.parse(h),f=m?.meta?.cwd??(m?.type==="session_meta"?m?.payload?.cwd:void 0);if(typeof f!="string"||f.length===0)continue;return nd(f)?null:f}catch{return null}}finally{Xe.closeSync(u)}}catch{return null}return null}function oR(t){let{env:e,cwd:n,pwd:r,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...fm(a),...IZ]:AZ;for(let l of u){let d=e[l];if(d&&!nd(d))return d}if(o){let l=NZ({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!nd(l))return l}if(a==="codex"){let l=DZ({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return r&&!nd(r)?r:n}var IZ,AZ,sR=v(()=>{"use strict";lo();IZ=["CONTEXT_MODE_PROJECT_DIR"],AZ=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"]});import{execFileSync as MZ}from"node:child_process";import{existsSync as ur,readdirSync as li,statSync as jZ}from"node:fs";import{homedir as ad}from"node:os";import{join as qt,sep as LZ}from"node:path";function mR(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function FZ(t){let e=t?.home??ad();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["antigravity-cli",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["copilot-cli",[".copilot"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([r,o])=>{let s=qt(e,...o,"context-mode");return{name:r,sessionsDir:qt(s,"sessions"),contentDir:qt(s,"content")}})}function HZ(t){let n=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return n?n[1].toLowerCase():"other"}function Qa(t){let e=Be(),n=t?.sessionsDir??qt(e,"context-mode","sessions"),r=t?.memoryRoot??qt(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(ur(n)){let h=[];try{h=li(n).filter(m=>m.endsWith(".db"))}catch{}if(h.length>0){let m=null;try{m=t?.loadDatabase?t.loadDatabase():nt()}catch{}if(m)for(let f of h){let g=qt(n,f);try{let y=new m(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),x=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=_?.cnt??0,s+=x?.cnt??0;try{let S=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let E of S)E.category&&(u[E.category]=(u[E.category]??0)+(E.cnt??0))}catch{}try{let S=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();S?.bytes&&(i+=S.bytes)}catch{}try{let S=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(S?.t){let E=S.t.endsWith("Z")?S.t:S.t+"Z",A=Date.parse(E);Number.isFinite(A)&&A<a&&(a=A)}}catch{}try{let S=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let E of S)E.p&&c.add(E.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,p={};if(ur(r)){let h=[];try{h=li(r).filter(m=>{try{return jZ(qt(r,m)).isDirectory()}catch{return!1}})}catch{}for(let m of h){let f=qt(r,m,"memory");if(!ur(f))continue;let g=[];try{g=li(f).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=HZ(y);p[_]=(p[_]??0)+1}}}}return{totalEvents:o,totalSessions:s,autoMemoryCount:l,autoMemoryProjects:d,autoMemoryByPrefix:p,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function fR(t){let e=t.sessionsDir??qt(ad(),".claude","context-mode","sessions"),n=t.sessionId,r={sessionId:n,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!n||!ur(e))return r;let o=[];try{o=li(e).filter(x=>!(!x.endsWith(".db")||t.worktreeHash&&!x.startsWith(t.worktreeHash)))}catch{return r}if(o.length===0)return r;let s=null;try{s=t.loadDatabase?t.loadDatabase():nt()}catch{return r}if(!s)return r;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,p=0,h=0,m=new Map,f=x=>Math.floor(x/864e5)*864e5;for(let x of o){let S=qt(e,x),E=!1;try{let A=new s(S,{readonly:!0});try{let b=A.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(n);for(let P of b)P.category&&(i[P.category]=(i[P.category]??0)+(P.cnt??0),a+=P.cnt??0,E=!0);let T=A.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(n);if(T?.mn){let P=Date.parse(T.mn+(T.mn.endsWith("Z")?"":"Z"));Number.isFinite(P)&&P<d&&(d=P)}if(T?.mx){let P=Date.parse(T.mx+(T.mx.endsWith("Z")?"":"Z"));Number.isFinite(P)&&P>p&&(p=P)}try{let P=A.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(n);for(let N of P){if(!N.sec)continue;let R=parseInt(N.sec,10)*1e3;if(!Number.isFinite(R))continue;let C=f(R),F=m.get(C)??{count:0,rescueBytes:0};F.count+=N.cnt??0,m.set(C,F)}}catch{}try{let P=A.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(n);if(P?.bytes&&(u+=P.bytes),P?.n&&(l+=P.n),P?.lastSec){let N=parseInt(P.lastSec,10)*1e3;if(Number.isFinite(N)&&N>h&&(h=N),Number.isFinite(N)&&(P?.bytes??0)>0){let R=f(N),C=m.get(R)??{count:0,rescueBytes:0};C.rescueBytes=Math.max(C.rescueBytes,P.bytes),m.set(R,C)}}}catch{}}finally{A.close()}}catch{}E&&c++}let g=d<p?(p-d)/864e5:0,y=Object.entries(i).filter(([,x])=>x>0).map(([x,S])=>({category:x,count:S,label:od[x]||x})).sort((x,S)=>S.count-x.count),_=[...m.entries()].sort((x,S)=>x[0]-S[0]).map(([x,S])=>({ms:x,count:S.count,...S.rescueBytes>0?{rescueBytes:S.rescueBytes}:{}}));return{sessionId:n,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:p>0?p:0,lastRescueMs:h>0?h:void 0,byDay:_}}function UZ(t,e,n){if(!t||!e||!ur(e))return 0;let r=null;try{r=n?.loadDatabase?n.loadDatabase():nt()}catch{return 0}if(!r)return 0;try{let o=new r(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
593
|
+
FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function hR(t,e){if(!t||!ur(t))return 0;let n=null;try{n=e?.loadDatabase?e.loadDatabase():nt()}catch{return 0}if(!n)return 0;try{let r=new n(t,{readonly:!0});try{let o=r.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
594
|
+
FROM chunks`).get();return Number(o?.bytes??0)}finally{r.close()}}catch{return 0}}function ec(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},n=t.sessionsDir??qt(ad(),".claude","context-mode","sessions");if(!ur(n))return e;let r=[];try{r=li(n).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(r.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():nt()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of r){let p=qt(n,d);up(p,o);try{let h=new o(p,{readonly:!0});try{if(t.sessionId){let m=h.prepare(`SELECT
|
|
581
595
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
582
596
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
583
597
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
@@ -596,53 +610,51 @@ ${o}`}}var FT=S(()=>{"use strict"});import{execFileSync as J2}from"node:child_pr
|
|
|
596
610
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
597
611
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
598
612
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
599
|
-
FROM session_events`).get();m&&(s+=Number(m.data_bytes??0),i+=Number(m.bytes_avoided??0),a+=Number(m.bytes_returned??0));try{let f=h.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();f?.bytes&&(c+=Number(f.bytes))}catch{}}}finally{h.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=xB(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let l=Math.floor((s+i+c)/4);return{eventDataBytes:s,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:l}}function vB(t,e,r){let n={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!pn(t.sessionsDir))return n;let o=[];try{o=di(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return n}if(o.length===0)return n;let s=null;try{s=e()}catch{return n}if(!s)return n;let i=new Set,a=new Set;for(let l of o){let d=Bt(t.sessionsDir,l);try{let p=new s(d,{readonly:!0});try{let h=p.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();h&&(n.eventCount+=Number(h.cnt??0),n.dataBytes+=Number(h.bytes??0));try{let m=p.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(m?.cnt??0)}catch{}try{let m=p.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();m?.bytes&&(n.rescueBytes+=Number(m.bytes))}catch{}try{let m=p.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(m?.mn){let f=Date.parse(m.mn+(m.mn.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f<n.firstMs&&(n.firstMs=f)}if(m?.mx){let f=Date.parse(m.mx+(m.mx.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f>n.lastMs&&(n.lastMs=f)}}catch{}try{let m=p.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let f of m)f.p&&i.add(f.p)}catch{}try{let m=p.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let f of m)f.s&&a.add(f.s)}catch{}}finally{p.close()}}catch{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function Gl(t){let e=yB({home:t?.home}),r=t?.loadDatabase??rt,n={...bB,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!pn(c.sessionsDir))continue;let u=vB(c,r,n);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}function Vl(t){return SB[t]??t}function dt(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let r=e/1024;if(r<1024)return r<100?`${r.toFixed(1)} MB`:`${Math.round(r)} MB`;let n=r/1024;return n<100?`${n.toFixed(2)} GB`:`${n.toFixed(1)} GB`}function kB(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let r=Math.floor(e/60),n=Math.round(e%60);return n>0?`${r}h ${n}m`:`${r}h`}function Zl(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function wB(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!Zl(e)&&(e=""),!e){if(process.platform==="darwin"){try{let n=mB("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}e&&!Zl(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-")),e&&!Zl(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return Zl(e)||(e="en-US"),{locale:e,tz:r||"UTC"}}function mP(t){let e=Kl();return e?t===e?"~":t.startsWith(e+hB)?"~"+t.slice(e.length):t:t}function EB(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*Xa(),o=(y,_=2)=>y.toFixed(_),s=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),p=(e*1.25/1e6).toFixed(2),h=(e*1/1e6).toFixed(2),m=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,f=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return m&&f?g.push(` $${o(n)} of ${f} tokens your team didn't burn.`):m?g.push(` $${o(n)} of tokens your team didn't burn.`):g.push(` $${o(n)} of Opus 4.7 tokens your team didn't burn.`),g.push(` context-mode kept ${dt(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(g.push(""),g.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),m||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function $B(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],p=e.events*_P,h=Math.round((e.snapshotBytes??0)/4),m=p+h,f=o?.conversation?.totalSavedTokens??0,g=Math.max(m,f),y=(r?.totalEvents??0)*_P,_=Math.round((r?.rescueBytes??0)/4),x=y+_,v=o?.lifetime?.totalSavedTokens??0,E=Math.max(x,v),C=o?.lifetime?.bytesReturned??0,b=o?.lifetime?.bytesAvoided??0,k=C+b>0?Math.max(1,Math.floor(C/4)):Math.max(1,Math.round(E*.02)),P=n?.totalBytes&&n.totalBytes>0?n.totalBytes:E*4,N=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,R=e.daysAlive>=1?`${e.daysAlive.toFixed(1)} days alive \xB7 still going`:`${Math.max(1,Math.round(e.daysAlive*24))} hr alive \xB7 still going`,O=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,F=O>0?Math.max(1,Math.round((c-O)/864e5)):0,K=n?.totalSessions??r?.totalSessions??1,ge=n?.perAdapter.filter(Ze=>Ze.isReal).length??0,We;if(n&&ge>=2)We=`across ${ge} AI tools`;else if(n&&ge===1){let Ze=n.perAdapter.find(pr=>pr.isReal);We=`in ${Ze?Vl(Ze.name):"Claude Code"}`}else We="in Claude Code";F>0?d.push(` Across ${F} days you ran ${wr(K)} conversations ${We}.`):d.push(` You ran ${wr(K)} conversations ${We}.`);let _t=F>0?P/F:0;d.push(` context-mode kept ${dt(P)} out of your context window \u2014 about ${dt(_t)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let Pr=e.firstEventMs&&e.firstEventMs>0?fP(e.firstEventMs,i,a):"";if(Pr?d.push(` This conversation started ${Pr} in ${mP(s)}.`):d.push(` This conversation lives in ${mP(s)}.`),d.push(` ${R}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ze=e.lastRescueMs&&e.lastRescueMs>0?fP(e.lastRescueMs,i,a):"",pr=Math.round(e.snapshotBytes/1024);Ze?d.push(` On ${Ze}, /compact fired \u2014 ${pr} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${pr} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let ic=o?.conversation,ac=ic?.bytesAvoided??0,gd=ic?.bytesReturned??0;if(ac+gd===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Ze=ac+gd,pr=Math.max(1,gd),mr=Math.max(1,Math.floor(Ze/4)),Gr=Math.max(1,Math.floor(pr/4)),yd=Kn(mr,mr,32),jR=Kn(Gr,mr,32),LR=(1-Gr/mr)*100,zR=Math.max(1,Math.round(mr/Gr));d.push(` Without context-mode ${dt(Ze).padStart(8)} ${yd} ${wr(mr).padStart(7)} tokens`),d.push(` With context-mode ${dt(pr).padStart(8)} ${jR} ${wr(Gr).padStart(7)} tokens`),d.push(` ${LR.toFixed(0)}% kept out of context \xB7 your AI ran ${zR}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Ze=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${dt(N)} built up \u2014 ${Ze} days, ${e.byDay.length} active:`),d.push(""),d.push(...PB(e.byDay,i,a))}d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),d.push("");let AR=e.byCategory.reduce((Ze,pr)=>Ze+pr.count,0).toLocaleString(i);d.push(` ${AR} things \u2014 files, errors, decisions, agent runs:`),d.push("");let NR=e.byCategory[0]?.count??1;for(let Ze of e.byCategory)d.push(` ${Ze.label.padEnd(26)} ${String(Ze.count).padStart(5)} ${Kn(Ze.count,NR,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let sx=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",ix=O>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(O)):"",ax=r?.distinctProjects??0,DR=r?.totalEvents??n?.totalEvents??0;if(d.push(` This chat: ${dt(N)} kept out \xB7 ${e.events.toLocaleString(i)} captures${sx?` \xB7 started ${sx}`:""}.`),d.push(` All your work: ${dt(P)} kept out \xB7 ${DR.toLocaleString(i)} captures across ${ax} project${ax===1?"":"s"}${ix?` \xB7 since ${ix}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...EB(P,E,F)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),r&&r.autoMemoryCount>0){d.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let Ze=Object.entries(r.autoMemoryByPrefix).sort((mr,Gr)=>Gr[1]-mr[1]),pr=Ze.length>0?Ze[0][1]:1;for(let[mr,Gr]of Ze){let yd=kP[mr]??mr;d.push(` ${yd.padEnd(26)} ${String(Gr).padStart(2)} ${Kn(Gr,pr,20)}`)}}else d.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");d.push(""),d.push(""),d.push(" Your AI talks less, remembers more, costs less."),d.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),d.push("");let MR=u?`v${u}`:"context-mode";return d.push(` ${MR}`),u&&l&&l!=="unknown"&&bP(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),TB(d)}function TB(t){let e=[],r=0;for(let n of t)n===""?(r++,r<=2&&e.push(n)):(r=0,e.push(n));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function PB(t,e,r){if(t.length===0)return[];let n=[...t].sort((p,h)=>p.ms-h.ms),o=n[0],s=n[n.length-1],i=Math.max(1,s.ms-o.ms),a=n[0];for(let p of n)p.count>a.count&&(a=p);let c=56,u=Array.from({length:c},()=>"\u2500");for(let p of n){let h=Math.round((p.ms-o.ms)/i*(c-1)),m="\u25CF";p===a&&(m="\u2588"),(p.rescueBytes??0)>0&&(m="\u25C6"),u[h]=m}let l=p=>{let h=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(p)),m=(h.find(g=>g.type==="month")?.value??"").toLowerCase(),f=h.find(g=>g.type==="day")?.value??"";return`${m} ${f}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let p of n){let h=l(p.ms).padEnd(7),m=`${p.count} captures`,f=p===a?" \u2190 peak":"",g=(p.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((p.rescueBytes??0)/1024)} KB`:"";d.push(` ${h} ${m}${f}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function fP(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),s=d=>o.find(p=>p.type===d)?.value??"",i=s("day"),a=s("month"),c=s("year"),u=s("hour"),l=s("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${l} (${r})`}function wr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Xa(){let t=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN;if(t!==void 0&&t!==""){let e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 5/1e6}function Wl(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Xa()).toFixed(2)}`}function Kn(t,e,r=40){if(e<=0)return"\u2591".repeat(r);let n=Math.max(1,Math.round(t/e*r));return"\u2588".repeat(Math.min(n,r))+"\u2591".repeat(Math.max(0,r-n))}function hP(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(f=>f.isReal).length??0,a=s?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=s?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let f=i>=2?" everywhere":"";o.push(` All your work${f} \xB7 ${wr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${wr(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let f=c===0&&r>0?1:c,g=f===1?"1 session":`${wr(f)} sessions`,y=a*256+r;o.push(` ${wr(a)} events \xB7 ${g} \xB7 ~${Wl(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,f])=>f>0).map(([f,g])=>({category:f,count:g,label:ql[f]||f})).sort((f,g)=>g.count-f.count):d=(t.by_category??[]).filter(f=>f&&f.count>0);let p=d.slice(0,n),h=p.length>0?p[0].count:1;for(let f of p)o.push(` ${f.label.padEnd(26)} ${String(f.count).padStart(5)} ${Kn(f.count,h,30)}`);let m=Math.max(0,d.length-n);return m>0&&o.push(` ... ${m} more categor${m===1?"y":"ies"}`),o}function gP(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[o,s]of r){let i=kP[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${Kn(s,n,20)}`)}return e}function yP(t,e){let r=[],n=Wl(t),o=(e?.totalEvents??0)*256+t,s=Wl(o);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${s} lifetime`),r.push("\u2500".repeat(65)),r}function xP(t){if(!t)return[];let e=[],r=[];for(let o of t.perAdapter)(o.isReal?e:r).push(o);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let o=16,s=10,i=10,a=16;n.push(` ${"Tool".padEnd(o)}${"Captures".padStart(s)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,l)=>l.dataBytes+l.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let l=u.dataBytes+u.rescueBytes,d=u.eventCount>0?wr(u.eventCount):"\u2014",p=dt(u.dataBytes),h=dt(l);n.push(` ${Vl(u.name).padEnd(o)}${d.padStart(s)}${p.padStart(i)}${h.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let o=r.map(s=>Vl(s.name)).join(", ");n.push(` Skipped (${r.length}): ${o}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function Jl(t,e,r,n){let o=[],s=kB(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,l=n?.multiAdapter,d=l?.perAdapter.filter(C=>C.isReal).length??0;if(l&&d>0){let C=l.totalSessions||i?.totalSessions||0,b=i?.firstEventMs??0,k=b>0?Math.max(1,Math.round((Date.now()-b)/864e5)):0,P=k>0?`Across ${k} day${k===1?"":"s"} `:"",N=C>0?`you ran ${wr(C)} conversation${C===1?"":"s"} `:"you ran ",R;if(d>=2)R=`across ${d} AI tools`;else{let O=l.perAdapter.find(F=>F.isReal);R=`in ${O?Vl(O.name):"Claude Code"}`}o.push(`${P}${N}${R}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let C=wB(),b=n?.cwd??process.cwd(),k=n?.now??Date.now(),P=n?.locale??C.locale,N=n?.tz??C.tz;return o.push(...$B({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:b,locale:P,tz:N,now:k,version:e,latestVersion:r})),o.join(`
|
|
600
|
-
`)}let p=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),h=t.savings.total_bytes_returned,m=t.savings.total_calls,f=p+h,g=f>0?p/f*100:0,y=Math.round(p/4),_=h>0?Math.max(1,Math.round(f/Math.max(h,1))):0;if(p===0){o.push(`context-mode ${s} ${m} calls`),o.push(""),m===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${
|
|
601
|
-
`)}o.push(`${
|
|
602
|
-
`)}var
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
`)}function GP(t,e,r,n=80*1024,o="batch"){let s=[],i=0,a=o==="global"?void 0:r;for(let c of e){if(i>n){s.push(`## ${c}
|
|
613
|
+
FROM session_events`).get();m&&(s+=Number(m.data_bytes??0),i+=Number(m.bytes_avoided??0),a+=Number(m.bytes_returned??0));try{let f=h.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();f?.bytes&&(c+=Number(f.bytes))}catch{}}}finally{h.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=UZ(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let l=Math.floor((s+i+c)/4);return{eventDataBytes:s,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:l}}function ZZ(t,e,n){let r={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!ur(t.sessionsDir))return r;let o=[];try{o=li(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return r}if(o.length===0)return r;let s=null;try{s=e()}catch{return r}if(!s)return r;let i=new Set,a=new Set;for(let l of o){let d=qt(t.sessionsDir,l);try{let p=new s(d,{readonly:!0});try{let h=p.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();h&&(r.eventCount+=Number(h.cnt??0),r.dataBytes+=Number(h.bytes??0));try{let m=p.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();r.sessionCount+=Number(m?.cnt??0)}catch{}try{let m=p.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();m?.bytes&&(r.rescueBytes+=Number(m.bytes))}catch{}try{let m=p.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(m?.mn){let f=Date.parse(m.mn+(m.mn.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f<r.firstMs&&(r.firstMs=f)}if(m?.mx){let f=Date.parse(m.mx+(m.mx.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f>r.lastMs&&(r.lastMs=f)}}catch{}try{let m=p.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let f of m)f.p&&i.add(f.p)}catch{}try{let m=p.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let f of m)f.s&&a.add(f.s)}catch{}}finally{p.close()}}catch{}}r.projectDirs=Array.from(i),r.uuidConvs=a.size;let c=r.eventCount>0?r.dataBytes/r.eventCount:0,u=r.lastMs>0&&n.nowMs-r.lastMs<=n.recencyMs;return r.isReal=r.eventCount>=n.minEvents&&i.size>=n.minProjects&&u&&c>=n.minAvgBytes,r}function cd(t){let e=FZ({home:t?.home}),n=t?.loadDatabase??nt,r={...BZ,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!ur(c.sessionsDir))continue;let u=ZZ(c,n,r);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}function sd(t){return qZ[t]??t}function mt(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let n=e/1024;if(n<1024)return n<100?`${n.toFixed(1)} MB`:`${Math.round(n)} MB`;let r=n/1024;return r<100?`${r.toFixed(2)} GB`:`${r.toFixed(1)} GB`}function VZ(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let n=Math.floor(e/60),r=Math.round(e%60);return r>0?`${n}h ${r}m`:`${n}h`}function rd(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function WZ(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!rd(e)&&(e=""),!e){if(process.platform==="darwin"){try{let r=MZ("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();r&&(e=r.replace(/_/g,"-"))}catch{}e&&!rd(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let r=(t.LC_TIME||t.LANG||"").split(".")[0];r&&(e=r.replace(/_/g,"-")),e&&!rd(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let n=t.CONTEXT_MODE_TZ??"";if(!n)try{n=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n="UTC"}return rd(e)||(e="en-US"),{locale:e,tz:n||"UTC"}}function iR(t){let e=ad();return e?t===e?"~":t.startsWith(e+LZ)?"~"+t.slice(e.length):t:t}function KZ(t,e,n){if(!Number.isFinite(e)||e<=0)return[];let r=e*tc(),o=(y,_=2)=>y.toFixed(_),s=Math.round(r/20),i=(r/200).toFixed(1),a=Math.round(r/73.67),c=Math.round(r*10),u=n>0?Math.round(r*10/n*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),p=(e*1.25/1e6).toFixed(2),h=(e*1/1e6).toFixed(2),m=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,f=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return m&&f?g.push(` $${o(r)} of ${f} tokens your team didn't burn.`):m?g.push(` $${o(r)} of tokens your team didn't burn.`):g.push(` $${o(r)} of Opus 4.7 tokens your team didn't burn.`),g.push(` context-mode kept ${mt(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(g.push(""),g.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),m||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function GZ(t){let{conversation:e,lifetime:n,multiAdapter:r,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],p=e.events*dR,h=Math.round((e.snapshotBytes??0)/4),m=p+h,f=o?.conversation?.totalSavedTokens??0,g=Math.max(m,f),y=(n?.totalEvents??0)*dR,_=Math.round((n?.rescueBytes??0)/4),x=y+_,S=o?.lifetime?.totalSavedTokens??0,E=Math.max(x,S),A=o?.lifetime?.bytesReturned??0,b=o?.lifetime?.bytesAvoided??0,T=A+b>0?Math.max(1,Math.floor(A/4)):Math.max(1,Math.round(E*.02)),P=r?.totalBytes&&r.totalBytes>0?r.totalBytes:E*4,N=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,R=e.daysAlive>=1?`${e.daysAlive.toFixed(1)} days alive \xB7 still going`:`${Math.max(1,Math.round(e.daysAlive*24))} hr alive \xB7 still going`,C=n?.firstEventMs??r?.perAdapter?.[0]?.firstMs??0,F=C>0?Math.max(1,Math.round((c-C)/864e5)):0,W=r?.totalSessions??n?.totalSessions??1,ge=r?.perAdapter.filter(Ue=>Ue.isReal).length??0,Le;if(r&&ge>=2)Le=`across ${ge} AI tools`;else if(r&&ge===1){let Ue=r.perAdapter.find(pn=>pn.isReal);Le=`in ${Ue?sd(Ue.name):"Claude Code"}`}else Le="in Claude Code";F>0?d.push(` Across ${F} days you ran ${kn(W)} conversations ${Le}.`):d.push(` You ran ${kn(W)} conversations ${Le}.`);let st=F>0?P/F:0;d.push(` context-mode kept ${mt(P)} out of your context window \u2014 about ${mt(st)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let $n=e.firstEventMs&&e.firstEventMs>0?aR(e.firstEventMs,i,a):"";if($n?d.push(` This conversation started ${$n} in ${iR(s)}.`):d.push(` This conversation lives in ${iR(s)}.`),d.push(` ${R}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ue=e.lastRescueMs&&e.lastRescueMs>0?aR(e.lastRescueMs,i,a):"",pn=Math.round(e.snapshotBytes/1024);Ue?d.push(` On ${Ue}, /compact fired \u2014 ${pn} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${pn} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let dc=o?.conversation,pc=dc?.bytesAvoided??0,Ad=dc?.bytesReturned??0;if(pc+Ad===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Ue=pc+Ad,pn=Math.max(1,Ad),mn=Math.max(1,Math.floor(Ue/4)),Wn=Math.max(1,Math.floor(pn/4)),Nd=Wr(mn,mn,32),jC=Wr(Wn,mn,32),LC=(1-Wn/mn)*100,zC=Math.max(1,Math.round(mn/Wn));d.push(` Without context-mode ${mt(Ue).padStart(8)} ${Nd} ${kn(mn).padStart(7)} tokens`),d.push(` With context-mode ${mt(pn).padStart(8)} ${jC} ${kn(Wn).padStart(7)} tokens`),d.push(` ${LC.toFixed(0)}% kept out of context \xB7 your AI ran ${zC}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Ue=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${mt(N)} built up \u2014 ${Ue} days, ${e.byDay.length} active:`),d.push(""),d.push(...XZ(e.byDay,i,a))}d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),d.push("");let AC=e.byCategory.reduce((Ue,pn)=>Ue+pn.count,0).toLocaleString(i);d.push(` ${AC} things \u2014 files, errors, decisions, agent runs:`),d.push("");let NC=e.byCategory[0]?.count??1;for(let Ue of e.byCategory)d.push(` ${Ue.label.padEnd(26)} ${String(Ue.count).padStart(5)} ${Wr(Ue.count,NC,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let Tx=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",$x=C>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(C)):"",Px=n?.distinctProjects??0,DC=n?.totalEvents??r?.totalEvents??0;if(d.push(` This chat: ${mt(N)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Tx?` \xB7 started ${Tx}`:""}.`),d.push(` All your work: ${mt(P)} kept out \xB7 ${DC.toLocaleString(i)} captures across ${Px} project${Px===1?"":"s"}${$x?` \xB7 since ${$x}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...KZ(P,E,F)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),n&&n.autoMemoryCount>0){d.push(` ${n.autoMemoryCount} preferences picked up across ${n.autoMemoryProjects} project${n.autoMemoryProjects===1?"":"s"}:`);let Ue=Object.entries(n.autoMemoryByPrefix).sort((mn,Wn)=>Wn[1]-mn[1]),pn=Ue.length>0?Ue[0][1]:1;for(let[mn,Wn]of Ue){let Nd=gR[mn]??mn;d.push(` ${Nd.padEnd(26)} ${String(Wn).padStart(2)} ${Wr(Wn,pn,20)}`)}}else d.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");d.push(""),d.push(""),d.push(" Your AI talks less, remembers more, costs less."),d.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),d.push("");let MC=u?`v${u}`:"context-mode";return d.push(` ${MC}`),u&&l&&l!=="unknown"&&mR(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),JZ(d)}function JZ(t){let e=[],n=0;for(let r of t)r===""?(n++,n<=2&&e.push(r)):(n=0,e.push(r));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function XZ(t,e,n){if(t.length===0)return[];let r=[...t].sort((p,h)=>p.ms-h.ms),o=r[0],s=r[r.length-1],i=Math.max(1,s.ms-o.ms),a=r[0];for(let p of r)p.count>a.count&&(a=p);let c=56,u=Array.from({length:c},()=>"\u2500");for(let p of r){let h=Math.round((p.ms-o.ms)/i*(c-1)),m="\u25CF";p===a&&(m="\u2588"),(p.rescueBytes??0)>0&&(m="\u25C6"),u[h]=m}let l=p=>{let h=new Intl.DateTimeFormat(e,{timeZone:n,month:"short",day:"numeric"}).formatToParts(new Date(p)),m=(h.find(g=>g.type==="month")?.value??"").toLowerCase(),f=h.find(g=>g.type==="day")?.value??"";return`${m} ${f}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let p of r){let h=l(p.ms).padEnd(7),m=`${p.count} captures`,f=p===a?" \u2190 peak":"",g=(p.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((p.rescueBytes??0)/1024)} KB`:"";d.push(` ${h} ${m}${f}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function aR(t,e,n){if(!Number.isFinite(t)||t<=0)return"";let r=new Date(t);if(Number.isNaN(r.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:n,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(r),s=d=>o.find(p=>p.type===d)?.value??"",i=s("day"),a=s("month"),c=s("year"),u=s("hour"),l=s("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${l} (${n})`}function kn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function tc(){let t=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN;if(t!==void 0&&t!==""){let e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 5/1e6}function id(t){return`$${((Number.isFinite(t)&&t>0?t:0)*tc()).toFixed(2)}`}function Wr(t,e,n=40){if(e<=0)return"\u2591".repeat(n);let r=Math.max(1,Math.round(t/e*n));return"\u2588".repeat(Math.min(r,n))+"\u2591".repeat(Math.max(0,n-r))}function cR(t,e){let n=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&n===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let r=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(f=>f.isReal).length??0,a=s?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=s?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let f=i>=2?" everywhere":"";o.push(` All your work${f} \xB7 ${kn(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${kn(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let f=c===0&&n>0?1:c,g=f===1?"1 session":`${kn(f)} sessions`,y=a*256+n;o.push(` ${kn(a)} events \xB7 ${g} \xB7 ~${id(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,f])=>f>0).map(([f,g])=>({category:f,count:g,label:od[f]||f})).sort((f,g)=>g.count-f.count):d=(t.by_category??[]).filter(f=>f&&f.count>0);let p=d.slice(0,r),h=p.length>0?p[0].count:1;for(let f of p)o.push(` ${f.label.padEnd(26)} ${String(f.count).padStart(5)} ${Wr(f.count,h,30)}`);let m=Math.max(0,d.length-r);return m>0&&o.push(` ... ${m} more categor${m===1?"y":"ies"}`),o}function uR(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let n=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),r=n.length>0?n[0][1]:1;for(let[o,s]of n){let i=gR[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${Wr(s,r,20)}`)}return e}function lR(t,e){let n=[],r=id(t),o=(e?.totalEvents??0)*256+t,s=id(o);return n.push(""),n.push("\u2500".repeat(65)),n.push("Your AI talks less, remembers more, costs less."),n.push(`${r} this session \xB7 ${s} lifetime`),n.push("\u2500".repeat(65)),n}function pR(t){if(!t)return[];let e=[],n=[];for(let o of t.perAdapter)(o.isReal?e:n).push(o);if(e.length===0&&n.length===0)return[];let r=[];if(e.length>0){r.push(""),r.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),r.push("");let o=16,s=10,i=10,a=16;r.push(` ${"Tool".padEnd(o)}${"Captures".padStart(s)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,l)=>l.dataBytes+l.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let l=u.dataBytes+u.rescueBytes,d=u.eventCount>0?kn(u.eventCount):"\u2014",p=mt(u.dataBytes),h=mt(l);r.push(` ${sd(u.name).padEnd(o)}${d.padStart(s)}${p.padStart(i)}${h.padStart(a)}`)}}if(n.length>0){e.length>0&&r.push("");let o=n.map(s=>sd(s.name)).join(", ");r.push(` Skipped (${n.length}): ${o}`),r.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),r.push(" or detection probes \u2014 no real chat activity.")}return r}function ud(t,e,n,r){let o=[],s=VZ(t.session.uptime_min),i=r?.lifetime,a=r?.mcpUsage,c=r?.conversation,u=r?.realBytes,l=r?.multiAdapter,d=l?.perAdapter.filter(A=>A.isReal).length??0;if(l&&d>0){let A=l.totalSessions||i?.totalSessions||0,b=i?.firstEventMs??0,T=b>0?Math.max(1,Math.round((Date.now()-b)/864e5)):0,P=T>0?`Across ${T} day${T===1?"":"s"} `:"",N=A>0?`you ran ${kn(A)} conversation${A===1?"":"s"} `:"you ran ",R;if(d>=2)R=`across ${d} AI tools`;else{let C=l.perAdapter.find(F=>F.isReal);R=`in ${C?sd(C.name):"Claude Code"}`}o.push(`${P}${N}${R}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let A=WZ(),b=r?.cwd??process.cwd(),T=r?.now??Date.now(),P=r?.locale??A.locale,N=r?.tz??A.tz;return o.push(...GZ({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:b,locale:P,tz:N,now:T,version:e,latestVersion:n})),o.join(`
|
|
614
|
+
`)}let p=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),h=t.savings.total_bytes_returned,m=t.savings.total_calls,f=p+h,g=f>0?p/f*100:0,y=Math.round(p/4),_=h>0?Math.max(1,Math.round(f/Math.max(h,1))):0;if(p===0){o.push(`context-mode ${s} ${m} calls`),o.push(""),m===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${mt(h)} entered context | 0 tokens saved`),o.push(...cR(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...pR(l)),o.push(...uR(i)),o.push(...lR(0,i)),o.push("");let A=e?`v${e}`:"context-mode";return o.push(A),e&&n&&n!=="unknown"&&mR(n,e)&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
|
|
615
|
+
`)}o.push(`${kn(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${id(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${Wr(f,f)}| ${mt(f)}`),o.push(`With context-mode |${Wr(h,f)}| ${mt(h)}`),o.push(""),_>=2?o.push(`${mt(p)} kept out of your conversation \u2014 ${_}\xD7 longer sessions before compact.`):o.push(`${mt(p)} kept out of your conversation. Never entered context.`),o.push("");let x=[`${m} calls`];t.cache&&t.cache.hits>0&&x.push(`${t.cache.hits} cache hits (+${mt(t.cache.bytes_saved)})`),o.push(x.join(" \xB7 "));let S=t.savings.by_tool.filter(A=>A.calls>0);if(S.length>=2){o.push("");let A=S.map(b=>{let T=b.context_kb*1024,P=g<100?T/(1-g/100):T,N=Math.max(0,P-T);return{...b,returnedBytes:T,estimatedSaved:N}}).sort((b,T)=>T.estimatedSaved-b.estimatedSaved);for(let b of A){let T=b.tool.length>22?b.tool.slice(0,19)+"...":b.tool;o.push(` ${T.padEnd(22)} ${String(b.calls).padStart(4)} calls ${mt(b.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let A=a.filter(b=>b.median_concurrency!=null&&(b.max_concurrency??1)>1);if(A.length>0){o.push(""),o.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let b of A){let T=b.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${T.padEnd(22)} ${b.calls} batches \xB7 ${b.median_concurrency} typical, ${b.max_concurrency} peak`)}}}o.push(...cR(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...pR(l)),o.push(...uR(i)),o.push(...lR(y,i)),o.push("");let E=e?`v${e}`:"context-mode";return o.push(E),e&&n&&n!=="unknown"&&n!==e&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
|
|
616
|
+
`)}var od,zZ,di,BZ,gR,qZ,r7,dR,yR=v(()=>{"use strict";yr();Jt();kr();od={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session intent",goal:"Session goal",role:"Behavior rules",constraint:"Constraints you set",mcp:"MCP tools called",skill:"Skills used",subagent:"Delegated work",decision:"Your decisions","agent-finding":"Agent insights kept","rejected-approach":"Approaches you rejected","external-ref":"External docs indexed",data:"Data references",git:"Git operations",env:"Environment setup",task:"Tasks in progress",error:"Errors caught",compact:"Compactions weathered",resume:"Sessions resumed cleanly",snapshot:"Snapshots restored",cache:"Cache hits saved",latency:"Slow tools recorded","user-prompt":"Your messages remembered",plan:"Plans drafted","blocked-on":"Blockers logged"},zZ={file:"Restored after compact \u2014 no need to re-read",rule:"Your project instructions survive context resets",prompt:"Continues exactly where you left off",decision:"Applied automatically \u2014 won\u2019t ask again",task:"Picks up from where it stopped",error:"Tracked and monitored across compacts",git:"Branch, commit, and repo state preserved",env:"Runtime config carried forward",mcp:"Tool usage patterns remembered",subagent:"Delegation history preserved",skill:"Skill invocations tracked"},di=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,n){let r=e-n,o=e>0?Math.round(r/e*1e3)/10:0;return{rawBytes:e,contextBytes:n,savedBytes:r,savedPercent:o}}static thinkInCodeComparison(e,n){let r=n>0?Math.round(e/n*10)/10:0;return{fileBytes:e,outputBytes:n,ratio:r}}static toolSavings(e){return e.map(n=>({...n,savedBytes:n.rawBytes-n.contextBytes}))}static sandboxIO(e,n){return{inputBytes:e,outputBytes:n}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let n=new Map;for(let o of e){let s;try{s=JSON.parse(o.data)}catch{continue}let i=typeof s.tool_name=="string"?s.tool_name:null;if(!i)continue;let a=n.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,s.truncated!==!0&&s.params&&typeof s.params=="object"){let c=s.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}n.set(i,a)}let r=[];for(let[o,s]of n){let i=null,a=null;if(s.concurrencies.length>0){s.concurrencies.sort((l,d)=>l-d);let c=s.concurrencies,u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}r.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return r.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),r}queryAll(e){let r=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",o=Object.values(e.bytesReturned).reduce((C,F)=>C+F,0),s=Object.values(e.calls).reduce((C,F)=>C+F,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+o,c=a/Math.max(o,1),u=a>0?Math.round((1-o/a)*100):0,l=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),d=Array.from(l).sort().map(C=>({tool:C,calls:e.calls[C]||0,context_kb:Math.round((e.bytesReturned[C]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[C]||0)/4)})),h=((Date.now()-e.sessionStart)/6e4).toFixed(1),m,f=e.cacheMisses??0;if(e.cacheHits>0||e.cacheBytesSaved>0||f>0){let C=a+e.cacheBytesSaved,F=C/Math.max(o,1),W=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),ge=e.cacheHits+f,Le=ge>0?e.cacheHits/ge:0;m={hits:e.cacheHits,misses:f,hit_rate:Le,bytes_saved:e.cacheBytesSaved,ttl_hours_left:W,total_with_cache:C,total_savings_ratio:F}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(r).cnt,y=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(r),x=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(r)?.compact_count??0,S=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(r),E=S?!S.consumed:!1,A=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(r),b=new Map;for(let C of A){b.has(C.category)||b.set(C.category,new Set);let F=b.get(C.category);if(F.size<5){let W=C.data;C.category==="file"?W=C.data.split("/").pop()||C.data:(C.category==="prompt"||C.category==="user-prompt")&&(W=W.length>50?W.slice(0,47)+"...":W),W.length>40&&(W=W.slice(0,37)+"..."),F.add(W)}}let T=y.map(C=>({category:C.category,count:C.cnt,label:od[C.category]||C.category,preview:b.get(C.category)?Array.from(b.get(C.category)).join(", "):"",why:zZ[C.category]||"Survives context resets"})),P=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),R=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(C=>C.cnt>0).map(C=>({category:C.category,count:C.cnt,label:od[C.category]||C.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(o/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:d,total_calls:s,total_bytes_returned:o,kept_out:i,total_processed:a},cache:m,session:{id:r,uptime_min:h},continuity:{total_events:g,by_category:T,compact_count:x,resume_ready:E},projectMemory:{total_events:P.cnt,session_count:P.sessions,by_category:R}}}};BZ={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};gR={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},qZ={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity","antigravity-cli":"Antigravity CLI",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot","copilot-cli":"GitHub Copilot CLI",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};r7=5/1e6;dR=256});var nC={};_e(nC,{AGY_DEFAULT_EXEC_TIMEOUT_MS:()=>KR,REGISTERED_CTX_TOOLS:()=>DR,__resetSuppressionDiagnosticForTests:()=>pq,browserOpenArgv:()=>QR,buildBatchNodeOptionsPrefix:()=>VR,buildFetchCode:()=>YR,classifyIp:()=>oc,currentAttribution:()=>pr,emitSuppressionDiagnostic:()=>LR,extractSnippet:()=>gx,formatBatchQueryResults:()=>qR,getProjectDir:()=>Lt,installStrictClientSchemaCompat:()=>FR,killProcessOnPort:()=>tC,openBrowserSync:()=>eC,positionsFromHighlight:()=>ZR,registerEmptyToolsListHandler:()=>zR,resolveExecTimeout:()=>wd,resolveSessionIdFromSessionDB:()=>HR,runBatchCommands:()=>JR,sanitizeSchemaForStrictClients:()=>_d,server:()=>Pe,shouldSuppressMcpToolsForNativePluginHost:()=>MR,withProjectDirOverride:()=>hq});import{createRequire as $R}from"node:module";import{existsSync as We,unlinkSync as fi,readdirSync as PR,readFileSync as sc,writeFileSync as gd,writeSync as YZ,renameSync as QZ,rmSync as RR,mkdirSync as eq,statSync as CR,symlinkSync as tq,lstatSync as OR,realpathSync as IR}from"node:fs";import{spawnSync as yd}from"node:child_process";import{join as zt,dirname as gi,resolve as Pt,sep as nq,isAbsolute as rq}from"node:path";import{fileURLToPath as oq}from"node:url";import{homedir as hi,tmpdir as mx,cpus as sq}from"node:os";import{request as iq}from"node:https";import{AsyncLocalStorage as aq}from"node:async_hooks";function AR(){return We(Pt(md,"package.json"))?md:gi(md)}function cq(t){try{let e=process.platform==="win32"?yd("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):yd("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});if(e.status!==0)return t;let n=Mc(String(e.stdout));if(n&&We(Pt(n,".codex-plugin","hooks.json")))return n}catch{}return t}function NR(t){let e=AR();return t==="codex"?cq(e):e}function MR(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let n=t.platform??Qe().platform;if(n!=="opencode"&&n!=="kilo")return!1;let r=t.settings??uq(n);return lq(r)&&dq(r)}function uq(t){let e=t==="kilo"?"kilo":"opencode",n=[Pt(`${e}.json`),Pt(`${e}.jsonc`),Pt(`.${e}`,`${e}.json`),Pt(`.${e}`,`${e}.jsonc`),zt(hi(),".config",e,`${e}.json`),zt(hi(),".config",e,`${e}.jsonc`)];for(let r of n)try{if(!We(r))continue;return JSON.parse(Ai(sc(r,"utf8")))}catch{}return null}function lq(t){let e=t?.plugin;return Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.includes("context-mode"))}function dq(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}function LR(t={}){if(ux)return;ux=!0;let e=t.write??(r=>{process.stderr.write(r)}),n=t.platform??"opencode/kilo";e(`[context-mode] ctx_* tools/list intentionally empty on this MCP child: legacy mcp.context-mode block coexists with plugin: ["context-mode"] in ${n}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
|
|
617
|
+
`)}function pq(){ux=!1}function zR(t=Pe){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(Lo,async()=>({tools:[]}))}function fq(t,e){return async n=>{try{return await e(n)}catch(r){let o=bq(r);if(o)try{return Y(t,o)}catch(s){if(s instanceof Kt)return o;throw s}throw r}}}async function hq(t,e){let n=typeof t=="string"?{projectDir:t}:t;return fx.run(n,e)}function _d(t){if(Array.isArray(t))return t.map(_d);if(t===null||typeof t!="object")return t;let e={};for(let[n,r]of Object.entries(t))if(n!=="additionalProperties"){if(n==="const"){e.enum=[r];continue}e[n]=_d(r)}return e}function FR(t=Pe){try{let n=t.server._requestHandlers?.get("tools/list");if(typeof n!="function")return;t.server.setRequestHandler(Lo,async(r,o)=>{let s=await n(r,o);if(s&&Array.isArray(s.tools)){for(let i of s.tools)if(!(!i||i.inputSchema==null))try{i.inputSchema=_d(i.inputSchema)}catch{}}return s})}catch{}}function pr(){let t=fx.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??HR();if(e)return{sessionId:e}}function HR(t){let e=Date.now();if(!t?.bypassCache&&ld&&e-ld.checkedAt<2e3)return ld.sid;try{let n=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!n)return;let r=t?.sessionsDir??Ve(),o=us({projectDir:n,sessionsDir:r});if(!We(o))return;let s=nt(),i=new s(o,{readonly:!0,fileMustExist:!0});try{let c=i.prepare("SELECT session_id FROM session_events ORDER BY created_at DESC LIMIT 1").get()?.session_id;return c&&(ld={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function gq(t){try{let e=Ve();if(!We(e))return;let n=PR(e).filter(r=>r.endsWith("-events.md"));for(let r of n){let o=zt(e,r);try{t.index({path:o,source:"session-events",attribution:pr()}),fi(o)}catch{}}}catch{}}async function yq(){if(En)return En;try{let{getAdapter:t}=await Promise.resolve().then(()=>(lo(),hm)),e=Qe();return await t(e.platform)}catch{return null}}function pi(){if(En)return En.getSessionDir();try{let t=Qe(),e=zi(t.platform);if(e)return Cc({configDir:zt(...e),configDirEnv:_q(e)})}catch{}return Cc({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function _q(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function Ve(){return Sr(br(pi))}function Lt(){let t=fx.getStore();if(t)return t.projectDir;let e,n,r;try{let o=Qe().platform;n=o,o==="claude-code"&&(e=zt(hi(),".claude","projects")),o==="codex"&&(r=process.env.CODEX_HOME??zt(hi(),".codex"))}catch{}return oR({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:n,codexHome:r})}function xq(t){return rq(t)?t:Pt(Lt(),t)}function rc(){return us({projectDir:Lt(),sessionsDir:Ve()})}function xd(){let t=Sr(Yr(pi));return ap({projectDir:Lt(),contentDir:t})}function Zn(){if(!wn){let t=xd();wn=new Ss(t),wn.setDenyChecker(e=>{try{let n=Lt(),r=po("Read",n);return mo(e,r,process.platform==="win32",n).denied}catch{return!0}});try{let e=gi(xd());vm(e,14),wn.cleanupStaleSources(14);let n=zt(hi(),".context-mode","content");We(n)&&vm(n,0)}catch{}Sm()}return gq(wn),wn}function bq(t){return t instanceof Kt?{content:[{type:"text",text:cs(t)}],isError:!0}:null}async function xR(){return new Promise(t=>{let e=iq("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{try{let o=JSON.parse(r);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function kq(){let t=En?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function wq(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function Eq(){return!dr||dr==="unknown"?!1:wq(dr,lr)}function Tq(){if(!Eq())return!1;let t=Date.now();if(dd>=Sq){if(t-_R<vq)return!1;dd=0}return dd===0&&(_R=t),dd++,!0}function $q(){if(!bR){bR=!0;try{let t=Be(),e=Pt(t,"plugins","installed_plugins.json");if(!We(e))return;let n=JSON.parse(sc(e,"utf-8")),r=Pt(t,"plugins","cache"),o;try{o=IR(r)}catch{o=r}let s=AR();for(let[i,a]of Object.entries(n.plugins??{}))if(i==="context-mode@context-mode")for(let c of a){let u=c.installPath;if(!u||We(u)||!Pt(u).startsWith(o+nq))continue;try{OR(u).isSymbolicLink()&&fi(u)}catch{}let l=gi(u);We(l)||eq(l,{recursive:!0}),We(s)&&tq(s,u,process.platform==="win32"?"junction":void 0)}}catch{}}}function Y(t,e){if($q(),Tq()&&e.content.length>0){let r=kq();e.content[0].text=`\u26A0\uFE0F context-mode v${lr} outdated \u2192 v${dr} available. Upgrade: ${r}
|
|
618
|
+
|
|
619
|
+
`+e.content[0].text}let n=e.content.reduce((r,o)=>r+Buffer.byteLength(o.text),0);return ie.calls[t]=(ie.calls[t]||0)+1,ie.bytesReturned[t]=(ie.bytesReturned[t]||0)+n,bd(),setImmediate(()=>ZP(rc(),t,n)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>zP({sessionDbPath:rc(),toolName:t,bytesReturned:n})),e}function Tn(t,e="unknown"){ie.bytesIndexed+=t,bd(),t>0&&setImmediate(()=>FP({sessionDbPath:rc(),source:e,bytesAvoided:t}))}function Aq(t){return Iq.test(t)?t:`pid-${process.ppid}`}function UR(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=Aq(t),n=Sr(as(pi));return zt(n,`stats-${e}.json`)}function bd(){let t=Date.now();if(!(t-lx<Pq)){lx=t;try{let e=Object.values(ie.bytesReturned).reduce((d,p)=>d+p,0),n=Object.values(ie.calls).reduce((d,p)=>d+p,0),r=ie.bytesIndexed+ie.bytesSandboxed+ie.cacheBytesSaved,o=r+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(r/4),a=pd?.tokens??0;if(!pd||t-pd.computedAt>Cq)try{a=(Qa({sessionsDir:Ve()})?.totalEvents??0)*Oq,pd={tokens:a,computedAt:t}}catch{}let c={schemaVersion:Rq,version:lr,updated_at:t,session_start:ie.sessionStart,uptime_ms:t-ie.sessionStart,total_calls:n,bytes_returned:e,bytes_indexed:ie.bytesIndexed,bytes_sandboxed:ie.bytesSandboxed,cache_hits:ie.cacheHits,cache_bytes_saved:ie.cacheBytesSaved,kept_out:r,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*tc()).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*tc()).toFixed(2),by_tool:Object.fromEntries(Object.keys({...ie.calls,...ie.bytesReturned}).map(d=>[d,{calls:ie.calls[d]||0,bytes:ie.bytesReturned[d]||0}]))},u=UR(),l=`${u}.tmp`;gd(l,JSON.stringify(c)),QZ(l,u)}catch{}}}function hx(t,e){try{let n=Em(process.env.CLAUDE_PROJECT_DIR),r=Tm(t,n);if(r.decision==="deny")return Y(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${r.matchedPattern}`}],isError:!0})}catch{}return null}function BR(t,e,n){try{let r=zv(t,e);if(r.length===0)return null;let o=Em(process.env.CLAUDE_PROJECT_DIR);for(let s of r){let i=Tm(s,o);if(i.decision==="deny")return Y(n,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function dx(t,e){try{let n=Lt(),r=po("Read",n),o=mo(t,r,process.platform==="win32",n);if(o.denied)return Y(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}function ZR(t){let e=[],n=0,r=0;for(;r<t.length;)if(t[r]===Mq){for(e.push(n),r++;r<t.length&&t[r]!==jq;)n++,r++;r<t.length&&r++}else n++,r++;return e}function gx(t,e,n=1500,r){if(t.length<=n)return t;let o=[];if(r)for(let u of ZR(r))o.push(u);if(o.length===0){let u=e.toLowerCase().split(/\s+/).filter(d=>d.length>2),l=t.toLowerCase();for(let d of u){let p=l.indexOf(d);for(;p!==-1;)o.push(p),p=l.indexOf(d,p+1)}}if(o.length===0)return t.slice(0,n)+`
|
|
620
|
+
\u2026`;o.sort((u,l)=>u-l);let s=300,i=[];for(let u of o){let l=Math.max(0,u-s),d=Math.min(t.length,u+s);i.length>0&&l<=i[i.length-1][1]?i[i.length-1][1]=d:i.push([l,d])}let a=[],c=0;for(let[u,l]of i){if(c>=n)break;let d=t.slice(u,Math.min(l,u+(n-c)));a.push((u>0?"\u2026":"")+d+(l<t.length?"\u2026":"")),c+=d.length}return a.join(`
|
|
621
|
+
|
|
622
|
+
`)}function qR(t,e,n,r=80*1024,o="batch"){let s=[],i=0,a=o==="global"?void 0:n;for(let c of e){if(i>r){s.push(`## ${c}
|
|
611
623
|
(output cap reached \u2014 use ctx_search(queries: ["${c}"]) for details)
|
|
612
|
-
`);continue}let u=t.searchWithFallback(c,3,a,void 0,"exact");if(s.push(`## ${c}`),s.push(""),u.length>0){for(let l of u){let d=
|
|
613
|
-
> **Scope:** Queries searched the entire persistent index (query_scope: "global").`):s.push('\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])` or call ctx_batch_execute with `query_scope: "global"`.'),s}function
|
|
614
|
-
\u2026 (truncated)`}function
|
|
624
|
+
`);continue}let u=t.searchWithFallback(c,3,a,void 0,"exact");if(s.push(`## ${c}`),s.push(""),u.length>0){for(let l of u){let d=gx(l.content,c,3e3,l.highlighted);s.push(`### ${l.title}`),s.push(d),s.push(""),i+=d.length+l.title.length}continue}s.push("No matching sections found."),s.push("")}return o==="global"?s.push(`
|
|
625
|
+
> **Scope:** Queries searched the entire persistent index (query_scope: "global").`):s.push('\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])` or call ctx_batch_execute with `query_scope: "global"`.'),s}function Lq(t){return`'${t.replace(/'/g,"'\\''")}'`}function zq(t){return`'${t.replace(/'/g,"''")}'`}function VR(t,e){let n=`--require ${e}`,r=t.toLowerCase(),o=r.split(/[\\/]/).pop()??r;return r.includes("powershell")||r.includes("pwsh")?`$env:NODE_OPTIONS=${zq(n)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${n.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${Lq(n)} `}function WR(t){let e=t.replace(/\s+/g," ").trim();return e.length<=SR?e:e.slice(0,SR)+"\u2026"}function wd(t){if(t!==void 0)return t;if(Qe().platform!=="antigravity-cli")return;let e=Number(process.env.CONTEXT_MODE_AGY_EXEC_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:KR}function Fq(t){return t.length<=vR?t:t.slice(0,vR)+`
|
|
626
|
+
\u2026 (truncated)`}function GR(t,e,n){let r=n?`path=${n}
|
|
615
627
|
`:"",o=`\`\`\`${t}
|
|
616
|
-
${
|
|
617
|
-
\`\`\``;return`${
|
|
628
|
+
${Fq(e)}
|
|
629
|
+
\`\`\``;return`${r}${o}
|
|
618
630
|
|
|
619
|
-
`}function
|
|
631
|
+
`}function kR(t,e,n,r){let o=n||"(no output)",s=o.matchAll(/__CM_FS__:(\d+)/g),i=0;for(let c of s)i+=parseInt(c[1]);i>0&&(r?.(i),o=o.replace(/__CM_FS__:\d+\n?/g,""));let a=WR(e);return`# ${t}
|
|
620
632
|
|
|
621
633
|
$ ${a}
|
|
622
634
|
|
|
623
635
|
${o}
|
|
624
|
-
`}function
|
|
636
|
+
`}function wR(t){let e=t.stdout||"",n=t.stderr||"";return n?e?`${e}${e.endsWith(`
|
|
625
637
|
`)?"":`
|
|
626
|
-
`}${
|
|
638
|
+
`}${n}`:n:e}async function JR(t,e,n){let{timeout:r,concurrency:o,nodeOptsPrefix:s,cwd:i,onFsBytes:a}=e;if(o<=1){let p=[],h=Date.now(),m=!1;for(let f=0;f<t.length;f++){let g=t[f],y;if(r!==void 0){let x=Date.now()-h,S=r-x;if(S<=0){p.push(`# ${g.label}
|
|
627
639
|
|
|
628
640
|
(skipped \u2014 batch timeout exceeded)
|
|
629
|
-
`),
|
|
641
|
+
`),m=!0;continue}y=S}let _=await n.execute({language:"shell",code:`${s}${g.command}`,timeout:y,cwd:i});if(p.push(kR(g.label,g.command,wR(_),a)),_.timedOut){m=!0;for(let x=f+1;x<t.length;x++)p.push(`# ${t[x].label}
|
|
630
642
|
|
|
631
643
|
(skipped \u2014 batch timeout exceeded)
|
|
632
|
-
`);break}}return{outputs:
|
|
633
|
-
(timed out after ${
|
|
634
|
-
`:
|
|
635
|
-
|
|
636
|
-
(executor error: ${
|
|
637
|
-
`}}return{outputs:
|
|
638
|
-
Use ctx_search(queries: ["..."]) to query this content. Use source: "${
|
|
639
|
-
`).length,s=Buffer.byteLength(t),i=
|
|
640
|
-
`)}let l=[`Indexed ${a.totalChunks} sections from "${
|
|
644
|
+
`);break}}return{outputs:p,timedOut:m}}let c=t.map(p=>({run:async()=>{let h=await n.execute({language:"shell",code:`${s}${p.command}`,timeout:r,cwd:i}),m=kR(p.label,p.command,wR(h),a);return{output:h.timedOut?m.replace(/\n$/,"")+`
|
|
645
|
+
(timed out after ${r??"?"}ms)
|
|
646
|
+
`:m,timedOut:!!h.timedOut}}})),{settled:u}=await X_(c,{concurrency:o}),l=new Array(t.length),d=!1;for(let p=0;p<u.length;p++){let h=u[p];if(h.status==="fulfilled")l[p]=h.value.output,h.value.timedOut&&(d=!0);else{let m=h.reason instanceof Error?h.reason.message:String(h.reason);l[p]=`# ${t[p].label}
|
|
647
|
+
|
|
648
|
+
(executor error: ${m})
|
|
649
|
+
`}}return{outputs:l,timedOut:d}}function XR(t,e){let n=Zn();Tn(Buffer.byteLength(t));let r=n.index({content:t,source:e,attribution:pr()});return{content:[{type:"text",text:`Indexed ${r.totalChunks} sections (${r.codeChunks} with code) from: ${r.label}
|
|
650
|
+
Use ctx_search(queries: ["..."]) to query this content. Use source: "${r.label}" to scope results.`}]}}function mi(t,e,n,r=5){let o=t.split(`
|
|
651
|
+
`).length,s=Buffer.byteLength(t),i=Zn(),a=i.indexPlainText(t,n,void 0,pr()),c=i.searchWithFallback(e,r,n),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let d=[`Indexed ${a.totalChunks} sections from "${n}" into knowledge base.`,`No sections matched intent "${e}" in ${o}-line output (${(s/1024).toFixed(1)}KB).`];return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to explore the indexed content."),d.join(`
|
|
652
|
+
`)}let l=[`Indexed ${a.totalChunks} sections from "${n}" into knowledge base.`,`${c.length} sections matched "${e}" (${o} lines, ${(s/1024).toFixed(1)}KB):`,""];for(let d of c){let p=d.content.split(`
|
|
641
653
|
`)[0].slice(0,120);l.push(` - ${d.title}: ${p}`)}return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to retrieve full content of any section."),l.join(`
|
|
642
|
-
`)}function
|
|
654
|
+
`)}function yx(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}function Bq(){try{return pr()?.sessionId??"__default__"}catch{return"__default__"}}function _x(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function xx(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function Zq(t){let e=_x(t);return Array.isArray(e)?e.map((n,r)=>typeof n=="string"?{label:`cmd_${r+1}`,command:n}:n):e}function qq(){return sx||(sx=$R(import.meta.url).resolve("turndown")),sx}function Vq(){return ix||(ix=$R(import.meta.url).resolve("turndown-plugin-gfm")),ix}function YR(t,e){let n=JSON.stringify(qq()),r=JSON.stringify(Vq()),o=JSON.stringify(e),s=oc.toString(),i=oc.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
|
|
643
655
|
var classifyIp = ${i};`,c=process.env.CTX_FETCH_STRICT==="1";return`
|
|
644
|
-
const TurndownService = require(${
|
|
645
|
-
const { gfm } = require(${
|
|
656
|
+
const TurndownService = require(${n});
|
|
657
|
+
const { gfm } = require(${r});
|
|
646
658
|
const fs = require('fs');
|
|
647
659
|
const dns = require('no' + 'de:dns');
|
|
648
660
|
const dnsPromises = require('no' + 'de:dns/promises');
|
|
@@ -884,14 +896,14 @@ async function main() {
|
|
|
884
896
|
emit('text', text);
|
|
885
897
|
}
|
|
886
898
|
main();
|
|
887
|
-
`}function
|
|
899
|
+
`}function Kq(t){if(t===0)return"0ms";let e=1440*60*1e3,n=3600*1e3,r=60*1e3;return t%e===0?`${t/e}d`:t%n===0?`${t/n}h`:t%r===0?`${t/r}m`:`${t}ms`}async function Gq(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let n=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:r}=await import("node:dns/promises"),o=await r(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=oc(s.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${s.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&n)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${s.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(r){let o=r?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=r instanceof Error?r.message:String(r),a=s?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`DNS lookup failed for "${e.hostname}": ${i}${a}`,reason:"exit"}}return null}function oc(t){let e=t.indexOf("%"),n=e===-1?t:t.slice(0,e),r=n.toLowerCase();if(r.includes(":")){let a=r.match(/^::ffff:([\d.]+)$/);return a?oc(a[1]):r==="::"||r.startsWith("fe8")||r.startsWith("fe9")||r.startsWith("fea")||r.startsWith("feb")||r.startsWith("ff")?"block":r==="::1"||r.startsWith("fc")||r.startsWith("fd")?"private":"public"}if(!n.includes("."))return"block";let o=n.split(".").map(a=>parseInt(a,10));if(o.length!==4||o.some(a=>isNaN(a)||a<0||a>255))return"block";let[s,i]=o;return s===169&&i===254||s===0||s>=224?"block":s===127||s===10||s===172&&i>=16&&i<=31||s===192&&i===168?"private":"public"}async function Jq(t,e,n,r){let o=await Gq(t);if(o)return o;if(!n&&r!==0){let i=Zn(),a=Y_(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=r??Wq;if(l<d){let p=Math.floor(l/36e5),h=Math.floor(l/(60*1e3)),m=p>0?`${p}h ago`:h>0?`${h}m ago`:"just now",f=c.chunkCount*1600;return{kind:"cached",label:c.label,chunkCount:c.chunkCount,estimatedBytes:f,ageStr:m,ttlStr:Kq(d)}}}}let s=zt(mx(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=YR(t,s),a=await ic.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let l=a.stderr||a.stdout||"unknown error",p=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(l)?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`${l}${p}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{let d=CR(s).size;if(d>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${d} bytes exceeds cap 52428800`,reason:"read"};u=sc(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return u.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:u,header:c}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{RR(s)}catch{}}}function Xq(t){let e=Zn(),n=Y_(t.source,t.url),r=pr(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,n,void 0,r):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,n,void 0,r):o=e.index({content:t.markdown,source:n,attribution:r}),Tn(Buffer.byteLength(t.markdown));let s=t.markdown.length>ER?DP(t.markdown,ER)+`
|
|
888
900
|
|
|
889
|
-
\u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:o.label,totalChunks:o.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function
|
|
890
|
-
${wi(
|
|
891
|
-
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var
|
|
892
|
-
`)}),process.on("uncaughtException",t=>{
|
|
893
|
-
`)}));
|
|
894
|
-
`);process.on("exit",()=>{try{
|
|
901
|
+
\u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:o.label,totalChunks:o.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function ax(t,e){if(!We(e))return;let n=0;try{for(let r of PR(e))if(!(!r.startsWith("stats-")||!r.endsWith(".json")))try{let o=JSON.parse(sc(zt(e,r),"utf-8"));n+=(o?.bytes_sandboxed??0)+(o?.bytes_indexed??0)}catch{}}catch{}if(n>0){let r=(t.rescueBytes??0)/4;t.totalEvents=Math.round((n/4+r)/256)}}function TR(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function QR(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}function eC(t,e=process.platform,n=yd){let r=QR(t,e),o=[];for(let{cmd:s,args:i}of r)try{let a=n(s,i,{stdio:"ignore",timeout:nc});if(!a.error&&a.status===0)return{ok:!0,method:s};let c=a.error?.message??`status=${a.status===null?"signaled":a.status}`;o.push(`${s}: ${c}`)}catch(a){o.push(`${s}: ${a instanceof Error?a.message:String(a)}`)}return{ok:!1,method:"none",reason:o.join("; ")}}function tC(t,e=process.platform,n=yd){let r={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return r.errors.push(`invalid port: ${t}`),r;try{if(e==="win32"){let o=n("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:nc});if(o.error)return r.errors.push(`netstat: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;let s=`:${t}`,i=new Set;for(let a of o.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let l=u[0],d=u[1],p=u[2],h=u[u.length-1];l==="TCP"&&d.endsWith(s)&&(p!=="0.0.0.0:0"&&p!=="[::]:0"||/^\d+$/.test(h)&&i.add(h))}for(let a of i){r.attemptedPids.push(a);try{let c=n("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:nc});c.error||c.status!==0?r.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):r.killedPids.push(a)}catch(c){r.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=n("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:nc});if(o.error)return r.errors.push(`lsof: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){r.attemptedPids.push(i);try{let a=n("kill",[i],{stdio:"ignore",timeout:nc});a.error||a.status!==0?r.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):r.killedPids.push(i)}catch(a){r.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){r.errors.push(o instanceof Error?o.message:String(o))}return r}async function Yq(){let t=Sm();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?mx():"/tmp",n=zt(e,`context-mode-mcp-ready-${process.pid}`),r,o=()=>{ic.cleanupBackgrounded(),wn&&wn.close();try{fi(kd)}catch{}try{fi(n)}catch{}r&&clearInterval(r)},s=async()=>{try{lx=0,bd()}catch{}o(),process.exit(0)};process.on("exit",o),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),AP({onShutdown:()=>s()});let i=new Xl;await Pe.connect(i);try{gd(n,String(process.pid))}catch{}r=setInterval(()=>{try{gd(n,String(process.pid))}catch{}},3e4),r.unref();try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(lo(),hm)),u=Pe.server.getClientVersion(),l=a(u??void 0);En=await c(l.platform),u&&console.error(`MCP client: ${u.name} v${u.version} \u2192 ${l.platform}`)}catch{}try{let a=qP(rc());if(a){for(let[c,u]of Object.entries(a.calls))ie.calls[c]=u;for(let[c,u]of Object.entries(a.bytesReturned))ie.bytesReturned[c]=u;a.sessionStart>0&&(ie.sessionStart=a.sessionStart)}}catch{}xR().then(a=>{a!=="unknown"&&(dr=a)}),setInterval(()=>{xR().then(a=>{a!=="unknown"&&(dr=a)})},3600*1e3).unref(),setInterval(()=>bd(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${lr} running on stdio`),console.error(`Detected runtimes:
|
|
902
|
+
${wi(Jo)}`),hr()||(console.error(`
|
|
903
|
+
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var md,lr,Jo,fd,Pe,DR,jR,ux,mq,fx,ic,kd,wn,ld,En,ie,dr,dd,_R,Sq,vq,bR,Pq,Rq,Cq,Oq,lx,pd,Iq,Nq,Dq,Mq,jq,SR,KR,vR,Sd,vd,Hq,px,hd,Uq,sx,ix,Wq,ER,nc,cx,rC=v(()=>{"use strict";mP();yP();Kl();J_();CP();km();OP();$m();Yo();IP();NP();MP();Jt();LP();UP();VP();YP();tR();nR();Rn();lo();Op();np();Ni();kr();sR();yr();yR();zo();md=gi(oq(import.meta.url)),lr=(()=>{for(let t of["../package.json","./package.json"]){let e=Pt(md,t);if(We(e))try{return JSON.parse(sc(e,"utf8")).version}catch{}}return"unknown"})();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
|
|
904
|
+
`)}),process.on("uncaughtException",t=>{try{YZ(2,`[context-mode] uncaughtException: ${t?.message??t}
|
|
905
|
+
`)}finally{process.exit(1)}}));Jo=Xr(),fd=Ei(Jo),Pe=new Gl({name:"context-mode",version:lr}),DR=[];jR=MR(),ux=!1;mq=Pe.registerTool.bind(Pe);Pe.registerTool=(...t)=>{let[e,n,r]=t;if(jR){LR();return}let o=fq(e,r);return DR.push({name:e,config:n,handler:o}),t[2]=o,mq(...t)};jR&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&zR(Pe);fx=new aq;Pe.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Pe.server.setRequestHandler(Hs,async()=>({prompts:[]}));Pe.server.setRequestHandler(zs,async()=>({resources:[]}));Pe.server.setRequestHandler(Fs,async()=>({resourceTemplates:[]}));ic=new ai({runtimes:Jo,projectRoot:()=>Lt()}),kd=zt(mx(),`cm-fs-preload-${process.pid}.js`);gd(kd,`(function(){var __cm_fs=0;process.on('exit',function(){if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch(e){}});try{var f=require('fs');var ors=f.readFileSync;f.readFileSync=function(){var r=ors.apply(this,arguments);if(Buffer.isBuffer(r))__cm_fs+=r.length;else if(typeof r==='string')__cm_fs+=Buffer.byteLength(r);return r;};}catch(e){}})();
|
|
906
|
+
`);process.on("exit",()=>{try{fi(kd)}catch{}});wn=null;En=null;ie={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};dr=null,dd=0,_R=0,Sq=3,vq=3600*1e3;bR=!1;Pq=500,Rq=2,Cq=3e4,Oq=256,lx=0,Iq=/^[A-Za-z0-9._-]+$/;Nq=fd.join(", "),Dq=hr()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",Mq="",jq="";SR=500;KR=12e4;vR=2e3;Pe.registerTool("ctx_execute",{title:"Execute Code",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run code in a sandboxed subprocess.${Dq} Languages: ${Nq}.
|
|
895
907
|
|
|
896
908
|
Think-in-Code \u2014 the core philosophy: the bytes your code processes never enter your conversation memory; only what you console.log() does. Reading a 700 KB log directly means 700 KB of your remaining reasoning capacity gets spent on raw bytes. Running code over that same log in this sandbox and printing a 3 KB summary leaves you with 697 KB of capacity for the actual work.
|
|
897
909
|
|
|
@@ -921,10 +933,10 @@ WHEN NOT:
|
|
|
921
933
|
RETURNS:
|
|
922
934
|
Only what your code prints. Wrap risky calls in try/catch \u2014 uncaught errors go to stderr and may leak more than intended. When \`intent\` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout; use ctx_search(queries: [...]) to drill into specific sections.
|
|
923
935
|
|
|
924
|
-
EXAMPLE: ctx_execute(language: "
|
|
925
|
-
EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(\`\${hooks.length} hook-related issues\`)")`,inputSchema:
|
|
936
|
+
EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('npm test', {encoding:'utf8', stdio:['ignore','pipe','pipe']}); console.log(out.split('\\\\n').filter(l => /(FAIL|\u2717|\xD7|Error:|Tests +.*(failed|passed))/i.test(l)).slice(0, 60).join('\\\\n'))")
|
|
937
|
+
EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(\`\${hooks.length} hook-related issues\`)")`,inputSchema:j.object({language:j.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:j.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), IO.puts (Elixir), or Console.WriteLine (C#) to output a summary to context."),timeout:j.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs (which is the right layer for this policy). Pass an explicit value for long-running builds (Gradle/Maven/SBT)."),background:j.preprocess(xx,j.boolean()).optional().default(!1).describe("Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts \u2014 the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background."),cwd:j.string().optional().describe("Optional working directory for shell commands. Non-shell languages still execute from their sandbox temp directory."),intent:j.string().optional().describe(`What you're looking for in the output. When provided and output is large (>5KB), indexes output into knowledge base and returns section titles + previews \u2014 not full content. Use ctx_search(queries: [...]) to retrieve specific sections. Example: 'failing tests', 'HTTP 500 errors'.
|
|
926
938
|
|
|
927
|
-
TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:
|
|
939
|
+
TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:n,background:r,cwd:o,intent:s})=>{if(t==="shell"){let i=hx(e,"execute");if(i)return i}else{let i=BR(e,t,"execute");if(i)return i}try{let i=e;(t==="javascript"||t==="typescript")&&(i=`
|
|
928
940
|
// FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
|
|
929
941
|
let __cm_fs=0;
|
|
930
942
|
process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
|
|
@@ -981,16 +993,16 @@ if(__cm_req.cache)require.cache=__cm_req.cache;}
|
|
|
981
993
|
async function __cm_main(){
|
|
982
994
|
${e}
|
|
983
995
|
}
|
|
984
|
-
__cm_main().catch(e=>{console.error(e);process.exitCode=1});${
|
|
996
|
+
__cm_main().catch(e=>{console.error(e);process.exitCode=1});${r?`
|
|
985
997
|
setInterval(()=>{},2147483647);`:""}
|
|
986
|
-
})(typeof require!=='undefined'?require:null);`);let
|
|
998
|
+
})(typeof require!=='undefined'?require:null);`);let a=wd(n),c=await ic.execute({language:t,code:i,timeout:a,background:r,cwd:o}),u=GR(t,e),l=c.stderr?.match(/__CM_NET__:(\d+)/);l&&(ie.bytesSandboxed+=parseInt(l[1]),c.stderr=c.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let d=c.stderr?.match(/__CM_FS__:(\d+)/);if(d&&(ie.bytesSandboxed+=parseInt(d[1]),c.stderr=c.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),c.timedOut){let h=c.stdout?.trim();return c.backgrounded&&h?Y("ctx_execute",{content:[{type:"text",text:`${u}${h}
|
|
987
999
|
|
|
988
|
-
_(process backgrounded after ${
|
|
1000
|
+
_(process backgrounded after ${a}ms \u2014 still running)_`}]}):h?Y("ctx_execute",{content:[{type:"text",text:`${u}${h}
|
|
989
1001
|
|
|
990
|
-
_(timed out after ${
|
|
1002
|
+
_(timed out after ${a}ms \u2014 partial output shown above)_`}]}):Y("ctx_execute",{content:[{type:"text",text:`${u}Execution timed out after ${a}ms
|
|
991
1003
|
|
|
992
1004
|
stderr:
|
|
993
|
-
${
|
|
1005
|
+
${c.stderr}`}],isError:!0})}if(c.exitCode!==0){let{isError:h,output:m}=Q_({language:t,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return s&&s.trim().length>0&&Buffer.byteLength(m)>Sd?(Tn(Buffer.byteLength(m)),Y("ctx_execute",{content:[{type:"text",text:`${u}${mi(m,s,h?`execute:${t}:error`:`execute:${t}`)}`}],isError:h})):Buffer.byteLength(m)>vd?(Tn(Buffer.byteLength(m)),Y("ctx_execute",{content:[{type:"text",text:`${u}${mi(m,"errors failures exceptions",h?`execute:${t}:error`:`execute:${t}`)}`}],isError:h})):Y("ctx_execute",{content:[{type:"text",text:`${u}${m}`}],isError:h})}let p=c.stdout||"(no output)";if(s&&s.trim().length>0&&Buffer.byteLength(p)>Sd)return Tn(Buffer.byteLength(p)),Y("ctx_execute",{content:[{type:"text",text:`${u}${mi(p,s,`execute:${t}`)}`}]});if(Buffer.byteLength(p)>vd){let h=XR(p,`execute:${t}`),m={...h,content:h.content.map((f,g)=>g===0&&f.type==="text"?{...f,text:`${u}${f.text}`}:f)};return Y("ctx_execute",m)}return Y("ctx_execute",{content:[{type:"text",text:`${u}${p}`}]})}catch(i){let a=i instanceof Error?i.message:String(i);return Y("ctx_execute",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});Sd=5e3,vd=102400;Pe.registerTool("ctx_execute_file",{title:"Execute File Processing",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Read a file into a sandboxed FILE_CONTENT variable and run code over it. Only what you console.log() enters your conversation \u2014 the file bytes stay in the sandbox.
|
|
994
1006
|
|
|
995
1007
|
Think-in-Code applied to file-level analysis: Reading the whole file means every byte enters your conversation memory and costs reasoning capacity for the rest of the session. Running code over it here lets you keep the raw bytes out and only the derived answer in. Same principle as ctx_execute, scoped to one named file via the FILE_CONTENT variable.
|
|
996
1008
|
|
|
@@ -1009,7 +1021,7 @@ RETURNS:
|
|
|
1009
1021
|
Only what your code prints. The FILE_CONTENT variable holds the raw bytes inside the sandbox; nothing else leaves. When \`intent\` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout.
|
|
1010
1022
|
|
|
1011
1023
|
EXAMPLE: ctx_execute_file(path: "huge.log", language: "javascript", code: "const errs = FILE_CONTENT.split('\\\\n').filter(l => /ERROR|FATAL/.test(l)); console.log(\`\${errs.length} error lines\`); console.log(errs.slice(-5).join('\\\\n'))")
|
|
1012
|
-
EXAMPLE: ctx_execute_file(path: "data.csv", language: "javascript", code: "const rows = FILE_CONTENT.split('\\\\n'); console.log(\`rows: \${rows.length - 1}, header: \${rows[0]}\`)")`,inputSchema:
|
|
1024
|
+
EXAMPLE: ctx_execute_file(path: "data.csv", language: "javascript", code: "const rows = FILE_CONTENT.split('\\\\n'); console.log(\`rows: \${rows.length - 1}, header: \${rows[0]}\`)")`,inputSchema:j.object({path:j.string().describe("Absolute file path or relative to project root"),language:j.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:j.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:j.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs."),intent:j.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:n,timeout:r,intent:o})=>{let s=dx(t,"ctx_execute_file");if(s)return s;if(e==="shell"){let i=hx(n,"execute_file");if(i)return i}else{let i=BR(n,e,"execute_file");if(i)return i}try{let i=wd(r),a=await ic.executeFile({path:t,language:e,code:n,timeout:i}),c=GR(e,n,t);if(a.timedOut)return Y("ctx_execute_file",{content:[{type:"text",text:`${c}Timed out processing ${t} after ${i}ms`}],isError:!0});if(a.exitCode!==0){let{isError:l,output:d}=Q_({language:e,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr});return o&&o.trim().length>0&&Buffer.byteLength(d)>Sd?(Tn(Buffer.byteLength(d)),Y("ctx_execute_file",{content:[{type:"text",text:`${c}${mi(d,o,l?`file:${t}:error`:`file:${t}`)}`}],isError:l})):Buffer.byteLength(d)>vd?(Tn(Buffer.byteLength(d)),Y("ctx_execute_file",{content:[{type:"text",text:`${c}${mi(d,"errors failures exceptions",l?`file:${t}:error`:`file:${t}`)}`}],isError:l})):Y("ctx_execute_file",{content:[{type:"text",text:`${c}${d}`}],isError:l})}let u=a.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(u)>Sd)return Tn(Buffer.byteLength(u)),Y("ctx_execute_file",{content:[{type:"text",text:`${c}${mi(u,o,`file:${t}`)}`}]});if(Buffer.byteLength(u)>vd){let l=XR(u,`file:${t}`),d={...l,content:l.content.map((p,h)=>h===0&&p.type==="text"?{...p,text:`${c}${p.text}`}:p)};return Y("ctx_execute_file",d)}return Y("ctx_execute_file",{content:[{type:"text",text:`${c}${u}`}]})}catch(i){let a=i instanceof Error?i.message:String(i);return Y("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});Pe.registerTool("ctx_index",{title:"Index Content",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},description:`Store content in a searchable knowledge base (BM25 over FTS5). Splits markdown by headings, keeps code blocks intact, and persists the raw chunks. The full content stays in storage \u2014 retrieve any section on-demand via ctx_search; nothing is summarized or truncated.
|
|
1013
1025
|
|
|
1014
1026
|
WHEN:
|
|
1015
1027
|
- Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
|
|
@@ -1027,37 +1039,37 @@ RETURNS:
|
|
|
1027
1039
|
Indexing metadata: chunk counts (total, code-bearing), source label, and the exact ctx_search call shape to query the indexed content. Raw content is NOT echoed back \u2014 it lives in storage, retrievable via ctx_search(source: "<label>"). When \`path\` is provided, a content hash is stored so ctx_search results auto-flag staleness on future calls.
|
|
1028
1040
|
|
|
1029
1041
|
EXAMPLE: ctx_index(content: "# React useEffect\\n\\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
|
|
1030
|
-
EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:
|
|
1031
|
-
Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)
|
|
1032
|
-
Use ctx_search(queries: ["..."]) to query this content. Use source: "${p.label}" to scope results.`}]})}catch(l){let d=l instanceof Error?l.message:String(l);return
|
|
1042
|
+
EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:j.object({content:j.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:j.string().optional().describe("File OR directory path to read and index (content never enters context). Provide this OR content. Directory paths trigger a bounded recursive walk (#687)."),source:j.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')"),include:j.array(j.string()).optional().describe("Directory-only: glob patterns to include (default: all matching extensions)."),exclude:j.array(j.string()).optional().describe("Directory-only: glob patterns to exclude. Merged with defaults (node_modules, .git, dist, build, .next, coverage, .venv, __pycache__, .DS_Store)."),maxDepth:j.number().int().min(0).optional().describe("Directory-only: max recursion depth from root (default: 5)."),maxFiles:j.number().int().min(1).optional().describe("Directory-only: hard cap on files indexed (default: 200) \u2014 FTS5 blow-up guard."),extensions:j.array(j.string()).optional().describe("Directory-only: allowed file extensions (default: .md .mdx .txt .json .yaml .yml .ts .tsx .js .jsx .py .rs .go .sh)."),respectGitignore:j.boolean().optional().describe("Directory-only: apply nearest .gitignore (default: true)."),followSymlinks:j.boolean().optional().describe("Directory-only: follow directory symlinks (default: false \u2014 cycle hazard + escape risk).")})},async({content:t,path:e,source:n,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return Y("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let l=dx(e,"ctx_index");if(l)return l}try{let l=e?xq(e):void 0;if(l&&We(l)&&OR(l).isSymbolicLink()){let m;try{m=IR(l)}catch{return Y("ctx_index",{content:[{type:"text",text:"Error: symlink target could not be resolved."}]})}if(m!==l){let f=dx(m,"ctx_index");if(f)return f}}if(l&&We(l)&&CR(l).isDirectory()){let h=Zn(),m=Lt(),f=po("Read",m),g=process.platform==="win32",y=A=>{try{return mo(A,f,g,m).denied}catch{return!1}},_=h.indexDirectory({path:l,source:n??l,attribution:pr(),perFileDeny:y,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),x=_.capped?` (cap reached \u2014 only first ${_.filesIndexed} of ${_.totalSeen}+ files; raise maxFiles to index more)`:"",S=_.denied>0?` (${_.denied} file${_.denied===1?"":"s"} blocked by Read deny policy)`:"",E=_.failed>0?` (${_.failed} file${_.failed===1?"":"s"} failed to read)`:"";return Y("ctx_index",{content:[{type:"text",text:`Indexed ${_.filesIndexed} file${_.filesIndexed===1?"":"s"} (${_.totalChunks} sections) from directory: ${_.label}${x}${S}${E}
|
|
1043
|
+
Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)Tn(Buffer.byteLength(t));else if(l)try{let h=await import("fs");Tn(h.readFileSync(l).byteLength)}catch{}let p=Zn().index({content:t,path:l,source:n??l,attribution:pr()});return Y("ctx_index",{content:[{type:"text",text:`Indexed ${p.totalChunks} sections (${p.codeChunks} with code) from: ${p.label}
|
|
1044
|
+
Use ctx_search(queries: ["..."]) to query this content. Use source: "${p.label}" to scope results.`}]})}catch(l){let d=l instanceof Error?l.message:String(l);return Y("ctx_index",{content:[{type:"text",text:`Index error: ${d}`}],isError:!0})}});Hq=yx("CONTEXT_MODE_SEARCH_WINDOW_MS",6e4),px=yx("CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER",3),hd=yx("CONTEXT_MODE_SEARCH_BLOCK_AFTER",8),Uq=new td({windowMs:Hq,softCapAfter:px,blockAfter:hd});Pe.registerTool("ctx_search",{title:"Search Indexed Content",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},description:'Search a unified knowledge base with a multi-strategy ranking pipeline. Two parallel matchers run on every query: a Porter-stemming matcher ("caching" finds "cached", "caches", "cach") and a trigram-substring matcher ("useEff" finds "useEffect"). Their ranked lists are merged via Reciprocal Rank Fusion, so a document that ranks well in both surfaces above one that wins only on a single strategy. Multi-term queries get an additional proximity-rerank pass that boosts passages where the query terms appear close together. Typos are corrected via Levenshtein distance and re-searched. Result snippets are window-extracted around the matched terms, not blindly truncated.\n\nThe knowledge base is unified: queries reach indexed content you stored (ctx_index, ctx_fetch_and_index, ctx_batch_execute output) AND auto-captured session memory written by hooks (decisions, errors, blockers, plans, user prompts, rejected approaches, tool failures, compaction guides \u2014 26 event categories). File-backed sources carry a content hash and auto-flag staleness when the source file changes.\n\nWHEN:\n - You want to recall something that exists in storage (recently indexed content, prior session events, auto-memory) instead of re-reading raw sources\n - You have multiple related questions about the same body of knowledge \u2014 batch every question into one call (the ranking pipeline runs per-query but the round-trip cost is paid once)\n - You want to scope the query to one labelled source (pass `source` \u2014 partial match is fine)\n - You want a chronological view across current session + prior sessions + persistent auto-memory (pass `sort: "timeline"` \u2014 the default `relevance` mode only ranks within the current session)\n - You want to filter ranked results by content shape (pass `contentType: "code"` to surface implementation snippets or `contentType: "prose"` to surface explanations)\n\nWHEN NOT:\n - The data you want to query has never been stored in the knowledge base AND no session memory has accumulated around it \u2014 capture first (run a gather-and-index call), then come back here to query\n - You have one ad-hoc question against data that is not in the knowledge base \u2014 answer it inline by running code in the sandbox tool; one round-trip instead of capture-then-query\n\nRETURNS:\n Per-query ranked sections with window-extracted snippets. Use 2-4 specific technical terms per query. Common session-memory source labels: `decision` (user corrections / preferences), `error` and `error-resolution` (past failures + their fixes), `blocker`, `plan`, `user-prompt`, `rejected-approach`, `compaction` (post-compact session guide). See ctx_stats for live category counts. Each response carries a throttle counter (call #N/M in the rolling time window); results taper toward the soft cap and calls block after the hard cap. Tune via CONTEXT_MODE_SEARCH_WINDOW_MS, CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER, CONTEXT_MODE_SEARCH_BLOCK_AFTER.\n\nEXAMPLE: ctx_search(queries: ["root cause", "proposed fix", "test coverage"], source: "issue-#683")\nEXAMPLE: ctx_search(queries: ["what did we decide about caching"], source: "decision", sort: "timeline")\nEXAMPLE: ctx_search(queries: ["useEffect cleanup pattern"], source: "react-docs", contentType: "code", limit: 5)\nEXAMPLE: ctx_search(queries: ["last user prompt", "active skills", "open blockers"], sort: "timeline")',inputSchema:QP(ox)},async t=>{try{let e=Zn(),n=t.sort||"relevance";if(n!=="timeline"&&e.getStats().chunks===0)return Y("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
|
|
1033
1045
|
|
|
1034
1046
|
ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
|
|
1035
1047
|
\u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
|
|
1036
1048
|
\u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
|
|
1037
1049
|
\u2022 ctx_index(content, source) \u2014 manually index text content
|
|
1038
1050
|
|
|
1039
|
-
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let
|
|
1051
|
+
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let r=t,o=[];if(Array.isArray(r.queries)&&r.queries.length>0?o.push(...r.queries):typeof r.query=="string"&&r.query.length>0&&o.push(r.query),o.length===0)return Y("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a,project:c}=t,u=eR(c,ox,()=>Lt()),l=Date.now(),d=Uq.record(Bq(),l),p=d.count;if(d.blocked)return Y("ctx_search",{content:[{type:"text",text:`BLOCKED: ${p} search calls in ${Math.round((l-d.windowStart)/1e3)}s. You're flooding context. STOP making individual search calls. Use ctx_batch_execute(commands, queries) for your next research step.`}],isError:!0});let h=d.softCapped?1:Math.min(s,2),m=40*1024,f=0,g=[],y=null;if(n==="timeline"||typeof u=="string")try{let T=Ve(),P=Lt(),N=us({projectDir:P,sessionsDir:T});We(N)&&(y=new Gt({dbPath:N}))}catch{}let x;if(typeof u=="string"&&y)try{x=new Set(y.getSessionIdsForProject(u))}catch{}let S=En?.getConfigDir()??Be();try{for(let T of o){if(f>m){g.push(`## ${T}
|
|
1040
1052
|
(output cap reached)
|
|
1041
|
-
`);continue}let
|
|
1042
|
-
No results found.`);continue}let
|
|
1043
|
-
${
|
|
1053
|
+
`);continue}let P;if(n==="timeline"?P=XP({query:T,limit:h,store:e,sort:n,source:i,contentType:a,sessionDB:y,projectDir:Lt(),configDir:S,adapter:En??void 0,projectScope:u}):P=e.searchWithFallback(T,h,i,a,"like",x),P.length===0){g.push(`## ${T}
|
|
1054
|
+
No results found.`);continue}let N=P.map((R,C)=>{let F=R.origin||"current-session",W=R.timestamp?R.timestamp.slice(0,16).replace("T"," "):"",ge=`--- [${F}${W?" | "+W:""} | ${R.source}] ---`,Le=`### ${R.title}`,st=gx(R.content,T,1500,R.highlighted);return`${ge}
|
|
1055
|
+
${Le}
|
|
1044
1056
|
|
|
1045
|
-
${
|
|
1057
|
+
${st}`}).join(`
|
|
1046
1058
|
|
|
1047
|
-
`);
|
|
1059
|
+
`);g.push(`## ${T}
|
|
1048
1060
|
|
|
1049
|
-
${
|
|
1061
|
+
${N}`),f+=N.length}}finally{try{y?.close()}catch{}}let E=g.join(`
|
|
1050
1062
|
|
|
1051
1063
|
---
|
|
1052
1064
|
|
|
1053
|
-
`);e.lastRefreshCount>0&&(
|
|
1065
|
+
`);e.lastRefreshCount>0&&(E=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
|
|
1054
1066
|
|
|
1055
|
-
`+
|
|
1067
|
+
`+E);let A=Math.max(0,hd-p),b=Math.max(0,px-p);if(p>=px?E+=`
|
|
1056
1068
|
|
|
1057
|
-
\u26A0 search call #${
|
|
1069
|
+
\u26A0 search call #${p}/${hd} in this window. Results limited to ${h}/query. ${A} call(s) remaining before block. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`:E+=`
|
|
1058
1070
|
|
|
1059
|
-
> Throttle: call #${
|
|
1060
|
-
Indexed sources: ${
|
|
1071
|
+
> Throttle: call #${p}/${hd} in this window. ${b} call(s) before soft cap. Prefer ctx_search(queries: [...]) array form for multi-query workloads \u2014 it counts as a single call.`,E.trim().length===0){let T=e.listSources(),P=T.length>0?`
|
|
1072
|
+
Indexed sources: ${T.map(N=>`"${N.label}" (${N.chunkCount} sections)`).join(", ")}`:"";return Y("ctx_search",{content:[{type:"text",text:`No results found.${P}`}]})}return Y("ctx_search",{content:[{type:"text",text:E}]})}catch(e){let n=e instanceof Error?e.message:String(e);return Y("ctx_search",{content:[{type:"text",text:`Search error: ${n}`}],isError:!0})}});sx=null,ix=null;Wq=1440*60*1e3,ER=3072;Pe.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},description:`Fetches URL content, converts HTML to markdown (JSON is chunked by key paths, plain text indexed directly), persists it in a searchable knowledge base, and returns a small preview window per source. The raw page bytes never enter your conversation \u2014 they live in storage and you retrieve any section on-demand via ctx_search.
|
|
1061
1073
|
|
|
1062
1074
|
Caching: every fetch is cached on disk and reused for repeat calls within the TTL window. The default TTL is 24 hours; override per-call with the \`ttl\` parameter (milliseconds, \`ttl: 0\` bypasses cache like \`force: true\`). Stored content older than 14 days is cleaned up on startup.
|
|
1063
1075
|
|
|
@@ -1077,15 +1089,15 @@ RETURNS:
|
|
|
1077
1089
|
EXAMPLE: ctx_fetch_and_index(
|
|
1078
1090
|
requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
|
|
1079
1091
|
concurrency: 5
|
|
1080
|
-
)`,inputSchema:
|
|
1092
|
+
)`,inputSchema:j.object({url:j.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:j.string().optional().describe("Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry."),requests:j.preprocess(_x,j.array(j.object({url:j.string().describe("URL to fetch"),source:j.string().optional().describe("Label for this URL's indexed content")})).min(1)).optional().describe("Batch shape: array of {url, source?} entries. Use with concurrency>1 for parallel fetch. Each request indexed under its own source label. Output preserves input order."),concurrency:j.coerce.number().int().min(1).max(8).optional().default(1).describe("Max URLs to fetch in parallel (1-8, default: 1). Use 4-8 for I/O-bound multi-URL batches (library docs, changelogs, pricing pages). Capped by os.cpus().length on small machines (response notes when capped). Indexing is always serial regardless \u2014 only fetches race."),force:j.preprocess(xx,j.boolean()).optional().describe("Skip cache and re-fetch even if content was recently indexed"),ttl:j.coerce.number().int().min(0).optional().describe("Override the cache freshness window for this call, in milliseconds. `ttl: 0` bypasses the cache like `force: true`; omit to use the default 24h TTL.")})},async({url:t,source:e,requests:n,concurrency:r,force:o,ttl:s})=>{let i=n||(t?[{url:t,source:e}]:[]);if(i.length===0)return Y("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let a=!n&&i.length===1,c=r??1,u=i.map(R=>({run:()=>Jq(R.url,R.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:p}=await X_(u,{concurrency:c,capByCpuCount:!a&&c>1}),h=[];for(let R=0;R<l.length;R++){let C=l[R];if(C.status==="rejected"){let W=C.reason instanceof Error?C.reason.message:String(C.reason);h.push({kind:"job_error",url:i[R].url,error:W});continue}let F=C.value;if(F.kind==="cached"){ie.cacheHits++,ie.cacheBytesSaved+=F.estimatedBytes;let W=F.estimatedBytes,ge=F.label;setImmediate(()=>HP({sessionDbPath:rc(),source:ge,bytesAvoided:W})),h.push({kind:"cached",label:F.label,chunkCount:F.chunkCount,ageStr:F.ageStr,ttlStr:F.ttlStr})}else F.kind==="fetch_error"?h.push({kind:"fetch_error",url:F.url,error:F.error,reason:F.reason}):(ie.cacheMisses++,h.push({kind:"fetched",indexed:Xq(F)}))}if(a){let R=h[0];if(R.kind==="cached")return Y("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${R.label}** \u2014 ${R.chunkCount} sections, indexed ${R.ageStr} (fresh, TTL: ${R.ttlStr}).
|
|
1081
1093
|
To refresh: call ctx_fetch_and_index again with \`force: true\`.
|
|
1082
1094
|
|
|
1083
1095
|
You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
|
|
1084
|
-
Use: ctx_search(queries: [...], source: "${R.label}")`}]});if(R.kind==="fetched"){let
|
|
1085
|
-
`);return
|
|
1096
|
+
Use: ctx_search(queries: [...], source: "${R.label}")`}]});if(R.kind==="fetched"){let C=(R.indexed.totalBytes/1024).toFixed(1),F=[`Fetched and indexed **${R.indexed.totalChunks} sections** (${C}KB) from: ${R.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${R.indexed.label}") for specific lookups.`,"","---","",R.indexed.preview].join(`
|
|
1097
|
+
`);return Y("ctx_fetch_and_index",{content:[{type:"text",text:F}]})}if(R.kind==="fetch_error"){let C=R.reason==="empty"?`Fetched ${R.url} but got empty content`:R.reason==="read"?`Fetched ${R.url} but could not read subprocess output`:R.reason==="exit"?`Failed to fetch ${R.url}: ${R.error}`:`Fetch error: ${R.error}`;return Y("ctx_fetch_and_index",{content:[{type:"text",text:C}],isError:!0})}return Y("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${R.error}`}],isError:!0})}let m=384,f=[],g=0,y=0,_=0,x=0,S=0,E=[];for(let R of h)if(R.kind==="cached")_++,f.push(`- [cache] ${R.label} \u2014 ${R.chunkCount} sections (${R.ageStr}, TTL: ${R.ttlStr})`);else if(R.kind==="fetched"){x++,g+=R.indexed.totalChunks,y+=R.indexed.totalBytes;let C=(R.indexed.totalBytes/1024).toFixed(1);f.push(`- [new] ${R.indexed.label} \u2014 ${R.indexed.totalChunks} sections (${C}KB)`);let F=R.indexed.preview.length>m?R.indexed.preview.slice(0,m).trimEnd()+"\u2026":R.indexed.preview;E.push(`### ${R.indexed.label}
|
|
1086
1098
|
|
|
1087
|
-
${F}`)}else
|
|
1088
|
-
`);return
|
|
1099
|
+
${F}`)}else S++,f.push(`- [err] ${R.url}: ${R.error}`);let A=(y/1024).toFixed(1),b=p?` cap=${d}/${sq().length}cpu`:"",T=(R,C,F)=>`${R} ${R===1?C:F}`,N=[`fetched ${i.length} c=${d}${b}. ok=${x} cache=${_} err=${S}. ${T(g,"section","sections")} ${A}KB.`,"",...f,"",'ctx_search(queries: [...], source: "<label>") for full content.',...E.length>0?["","---","",...E]:[]].join(`
|
|
1100
|
+
`);return Y("ctx_fetch_and_index",{content:[{type:"text",text:N}],isError:S===i.length})});Pe.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run multiple commands in ONE call. Every command's output is auto-indexed into the knowledge base; if you also pass \`queries\`, the matching sections come back in the same round trip so a follow-up search call is not needed.
|
|
1089
1101
|
|
|
1090
1102
|
Concurrency parallelizes the FETCH phase (run-the-commands). The DERIVATION phase \u2014 turning raw output into an answer \u2014 still belongs in code: add a processing command that consumes the indexed output and prints only the answer, so the raw bytes never enter your conversation (Think-in-Code, same principle as the sandbox tool).
|
|
1091
1103
|
|
|
@@ -1110,14 +1122,14 @@ EXAMPLE: ctx_batch_execute(
|
|
|
1110
1122
|
],
|
|
1111
1123
|
queries: ["root cause", "proposed fix"],
|
|
1112
1124
|
concurrency: 2
|
|
1113
|
-
)`,inputSchema:
|
|
1114
|
-
`),
|
|
1115
|
-
`).length;if(
|
|
1116
|
-
Searchable terms for follow-up: ${
|
|
1117
|
-
`);return
|
|
1118
|
-
`)}]})});
|
|
1119
|
-
`),
|
|
1120
|
-
`);return
|
|
1125
|
+
)`,inputSchema:j.object({commands:j.preprocess(Zq,j.array(j.object({label:j.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:j.string().describe("Shell command to execute")})).min(1).describe("Commands to execute as a batch. Output is labeled with the section header. Default order is sequential; pass concurrency>1 to run in parallel (output stays in input order).")),queries:j.preprocess(_x,j.array(j.string()).min(1).describe("Search queries to extract information from indexed output. Use 5-8 comprehensive queries. Each returns top 5 matching sections with full content. This is your ONLY chance \u2014 put ALL your questions here. No follow-up calls needed.")),timeout:j.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs. With concurrency=1, the value (when set) is a shared budget across commands; with concurrency>1, it is applied per-command."),concurrency:j.coerce.number().int().min(1).max(8).optional().default(1).describe("Max commands to run in parallel (1-8, default: 1). Use 4-8 for I/O-bound batches (network, gh, curl, multi-repo git reads). Keep at 1 for CPU-bound (npm test, build, lint) or stateful commands (ports, locks). >1 switches to per-command timeouts (no shared budget) and individual `(timed out)` blocks instead of cascading skip."),cwd:j.string().optional().describe("Optional working directory for all shell commands in this batch."),query_scope:j.enum(["batch","global"]).optional().default("batch").describe("Scope for `queries` (default: `batch`). `batch` searches ONLY the chunks produced by this batch's commands \u2014 useful when you want answers about the just-fetched output. `global` searches the entire persistent index (same scope as ctx_search) \u2014 useful when you want the batch commands to enrich context and the queries to also surface related prior knowledge in one round trip.")})},async({commands:t,queries:e,timeout:n,concurrency:r,cwd:o,query_scope:s})=>{for(let i of t){let a=hx(i.command,"batch_execute");if(a)return a}try{let i=VR(Jo.shell,kd),a=wd(n),{outputs:c,timedOut:u}=await JR(t,{timeout:a,concurrency:r,nodeOptsPrefix:i,cwd:o,onFsBytes:b=>{ie.bytesSandboxed+=b}},ic),l=c.join(`
|
|
1126
|
+
`),d=Buffer.byteLength(l),p=l.split(`
|
|
1127
|
+
`).length;if(u&&c.length===0)return Y("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${a}ms. No output captured.`}],isError:!0});Tn(d);let h=Zn(),m=`batch:${t.map(b=>b.label).join(",").slice(0,80)}`,f=h.index({content:l,source:m,attribution:pr()}),g=["## Commands",""];for(let b of t)g.push(`- ${b.label}: \`${WR(b.command)}\``);let y=h.getChunksBySource(f.sourceId),_=["## Indexed Sections",""],x=[];for(let b of y){let T=Buffer.byteLength(b.content);_.push(`- ${b.title} (${(T/1024).toFixed(1)}KB)`),x.push(b.title)}let S=qR(h,e,m,void 0,s),E=h.getDistinctiveTerms?h.getDistinctiveTerms(f.sourceId):[],A=[`Executed ${t.length} commands (${p} lines, ${(d/1024).toFixed(1)}KB). Indexed ${f.totalChunks} sections. Searched ${e.length} queries.`,"",...g,"",..._,"",...S,E.length>0?`
|
|
1128
|
+
Searchable terms for follow-up: ${E.join(", ")}`:""].join(`
|
|
1129
|
+
`);return Y("ctx_batch_execute",{content:[{type:"text",text:A}]})}catch(i){let a=i instanceof Error?i.message:String(i);return Y("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${a}`}],isError:!0})}});Pe.registerTool("ctx_stats",{title:"Session Statistics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:j.object({})},async()=>{let t;try{let e=Lt(),n=rt(e),r=us({projectDir:e,sessionsDir:Ve()});if(We(r)){let o=nt(),s=new o(r,{readonly:!0});try{let i=new di(s),a=i.queryAll(ie),c=i.getMcpToolUsage(),u=Qa({sessionsDir:Ve()}),l;try{l=cd()}catch{}let d,p;try{let m=process.env.CLAUDE_SESSION_ID;if(m||(m=s.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),m){d=fR({sessionId:m,sessionsDir:Ve(),worktreeHash:n});let f=xd(),g;try{let S=nt(),E=(await import("node:fs")).readdirSync(Ve()).filter(b=>b.endsWith(".db")&&(!n||b.startsWith(n))),A;for(let b of E)try{let T=new S((await import("node:path")).join(Ve(),b),{readonly:!0});try{let P=T.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(m);if(P?.project_dir){A=P.project_dir;break}}finally{T.close()}}catch{}g=A?ec({projectDir:A,sessionsDir:Ve(),worktreeHash:n,contentDbPath:f}):ec({sessionId:m,sessionsDir:Ve(),worktreeHash:n,contentDbPath:f})}catch{g=ec({sessionId:m,sessionsDir:Ve(),worktreeHash:n,contentDbPath:f})}let y=ec({sessionsDir:Ve()}),_=hR(f),x={...y,contentBytes:y.contentBytes+_,bytesAvoided:y.bytesAvoided+_,totalSavedTokens:Math.floor((y.eventDataBytes+y.bytesAvoided+_+y.snapshotBytes)/4)};p={conversation:g,lifetime:x}}}catch{}En?.name==="Pi"&&ax(u,Ve());let h;try{h=Zn().getIndexState()}catch{}t=ud(a,lr,dr,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:p,indexState:h,cwd:e})}finally{s.close()}}else{let s=new di(TR()).queryAll(ie),i=Qa({sessionsDir:Ve()});En?.name==="Pi"&&ax(i,Ve());let a;try{a=cd()}catch{}let c;try{c=Zn().getIndexState()}catch{}t=ud(s,lr,dr,{lifetime:i,multiAdapter:a,indexState:c})}}catch{let n=new di(TR()).queryAll(ie),r;try{r=Qa({sessionsDir:Ve()})}catch{}En?.name==="Pi"&&r&&ax(r,Ve());let o;try{o=cd()}catch{}t=ud(n,lr,dr,r||o?{lifetime:r,multiAdapter:o}:void 0)}return Y("ctx_stats",{content:[{type:"text",text:t}]})});Pe.registerTool("ctx_doctor",{title:"Run Diagnostics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},description:"Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.",inputSchema:j.object({})},async()=>{let t=["context-mode doctor",""],e;try{e=Qe(Pe.server.getClientVersion()??void 0).platform}catch{e=Qe().platform}let n=NR(e),r=11,o=(fd.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${fd.length}/${r} (${o}%) \u2014 ${fd.join(", ")}`),hr()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let s=br(pi),i=Yr(pi),a=as(pi);t.push(`[OK] Storage sessions: ${s.path} (${Ri(s)})`),t.push(`[OK] Storage content: ${i.path} (${Ri(i)})`),t.push(`[OK] Storage stats: ${a.path} (${Ri(a)})`);{let u=new ai({runtimes:Jo});try{let l=await u.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(l.exitCode===0&&l.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let d=l.stderr?.trim()?` (${l.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${l.exitCode}${d}`)}}catch(l){t.push(`[FAIL] Server test: FAIL \u2014 ${l instanceof Error?l.message:l}`)}finally{u.cleanupBackgrounded()}}{let u;try{let l=nt();u=new l(":memory:"),u.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),u.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let d=u.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();d&&d.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(l){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${l instanceof Error?l.message:l}`)}finally{try{u?.close()}catch{}}}let c=await yq();if(c){for(let l of c.validateHooks(n)){let d=l.status==="pass"?"[OK]":l.status==="warn"?"[WARN]":"[FAIL]",p=l.fix?` \u2014 fix: ${l.fix}`:"";t.push(`${d} ${l.check}: ${l.message}${p}`)}let u=vc(c,n);u.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let l of u){let d=Pt(n,l);We(d)?t.push(`[OK] Hook script: PASS \u2014 ${d}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${d}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${lr}`),Y("ctx_doctor",{content:[{type:"text",text:t.join(`
|
|
1130
|
+
`)}]})});Pe.registerTool("ctx_upgrade",{title:"Upgrade Plugin",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:j.object({})},async()=>{let t="",e,n;try{let c=Pe.server.getClientVersion(),u=Qe(c??void 0);n=u.platform,t=` --platform ${u.platform}`,e=Jr(u.platform)&&Jo.javascript?{platform:u.platform,jsRuntime:Jo.javascript}:void 0}catch{try{n=Qe().platform}catch{}}let r=NR(n),o=Pt(r,"cli.bundle.mjs"),s=Pt(r,"build","cli.js");try{let c=Ve(),u=zt(gi(c),"insight-cache");We(u)&&(tC(4747),RR(u,{recursive:!0,force:!0}))}catch{}let i;if(We(o))i=`${vi(o,e)} upgrade${t}`;else if(We(s))i=`${vi(s,e)} upgrade${t}`;else{let u=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync,lstatSync}from"node:fs";','import{join,resolve,sep}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(r)};`,'const T=mkdtempSync(join(tmpdir(),"ctx-upgrade-"));',"try{",'console.log("- [x] Starting inline upgrade (no CLI found)");','execFileSync("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",T],{stdio:"inherit"});','console.log("- [x] Cloned latest source");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["run","build"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Built from source");','const pkg=JSON.parse(readFileSync(join(T,"package.json"),"utf8"));','const items=[...(Array.isArray(pkg.files)?pkg.files:[]),"src","package.json"];',"const PW=resolve(P)+sep;const TW=resolve(T)+sep;","const noSymlink=(src)=>{try{return !lstatSync(src).isSymbolicLink()}catch{return false}};","for(const item of items){const from=resolve(T,item);const to=resolve(P,item);if(!(to+sep).startsWith(PW))continue;if(!(from+sep).startsWith(TW))continue;if(!noSymlink(from))continue;if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true,filter:noSymlink});}}",'console.log("- [x] Copied package files");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install","--production"],{cwd:P,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Installed production dependencies");','console.log("## context-mode upgrade complete");',"}catch(e){",'console.error("- [ ] Upgrade failed:",e.message);',"process.exit(1);","}finally{","try{rmSync(T,{recursive:true,force:true})}catch{}","}"].join(`
|
|
1131
|
+
`),l=Pt(r,".ctx-upgrade-inline.mjs"),{writeFileSync:d}=await import("node:fs");d(l,u),i=vi(l,e)}let a=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",i,"```","","After the command completes, display results as a markdown checklist:","- `[x]` for success, `[ ]` for failure","- Example format:"," ```"," ## context-mode upgrade"," - [x] Pulled latest from GitHub"," - [x] Built and installed v0.9.24"," - [x] npm global updated"," - [x] Hooks configured"," - [x] Doctor: all checks PASS"," ```","- Tell the user to restart their session to pick up the new version."].join(`
|
|
1132
|
+
`);return Y("ctx_upgrade",{content:[{type:"text",text:a}]})});Pe.registerTool("ctx_purge",{title:"Purge Knowledge Base",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},description:`DESTRUCTIVE: permanently delete indexed content. Cannot be undone. Requires confirm:true and exactly one scope.
|
|
1121
1133
|
|
|
1122
1134
|
WHEN:
|
|
1123
1135
|
- User explicitly asks to clear a specific session ('purge this session', 'wipe this conversation')
|
|
@@ -1141,85 +1153,75 @@ RETURNS:
|
|
|
1141
1153
|
A summary of removed rows + the resolved scope.
|
|
1142
1154
|
|
|
1143
1155
|
EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
|
|
1144
|
-
EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
-
|
|
1148
|
-
|
|
1149
|
-
`)
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
`,"utf-8")}catch{return"noop"}return"healed"}function xR({snapshotsDir:t,currentVersion:e}){let r={rewritten:[]};if(!t||typeof t!="string"||!e||typeof e!="string")return r;let n;try{if(!sc(t))return r;n=RZ(t)}catch{return r}let o=/(context-mode[/\\]context-mode[/\\])([^/\\]+)([/\\]bin)/g;for(let s of n){if(!s.endsWith(".sh"))continue;let i=IZ(t,s),a;try{if(!hR(i).isFile())continue;a=ex(i,"utf-8")}catch{continue}let c=!1,u=a.replace(o,(d,p,h,m)=>h===e?d:(c=!0,`${p}${e}${m}`));if(!c)continue;let l=`${i}.tmp-${process.pid}-${Date.now()}`;try{tx(l,u,"utf-8"),CZ(l,i),r.rewritten.push(i)}catch{try{OZ(l)}catch{}}}return r}function NZ({snapshotsDir:t,pluginCacheRoot:e,currentVersion:r}){return xR({snapshotsDir:t,currentVersion:r})}function bR(t){if(!(!t||!sc(t)))try{let e=ex(t,"utf-8");e.startsWith("#!")||tx(t,`#!/usr/bin/env node
|
|
1154
|
-
${e}`,"utf-8"),(hR(t).mode&511)!==493&&PZ(t,493)}catch{}}var SR=S(()=>{"use strict"});import{stdout as nC,stdin as oC}from"node:process";import*as gn from"node:readline";var cx=t=>t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109,ux=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,lx=t=>t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t===94192||t===94193||t>=94208&&t<=100343||t>=100352&&t<=101589||t>=101632&&t<=101640||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128727||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129672||t>=129680&&t<=129725||t>=129727&&t<=129733||t>=129742&&t<=129755||t>=129760&&t<=129768||t>=129776&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141;var xd=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,cc=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,uc=/\t{1,1000}/y,bd=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),lc=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,VR=new RegExp("\\p{M}+","gu"),WR={limit:1/0,ellipsis:""},dx=(t,e={},r={})=>{let n=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?dx(o,WR,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,l=r.emojiWidth??2,d=r.fullWidthWidth??2,p=r.regularWidth??1,h=r.wideWidth??2,m=0,f=0,g=t.length,y=0,_=!1,x=g,v=Math.max(0,n-s),E=0,C=0,b=0,k=0;e:for(;;){if(C>E||f>=g&&f>m){let P=t.slice(E,C)||t.slice(m,f);y=0;for(let N of P.replaceAll(VR,"")){let R=N.codePointAt(0)||0;if(ux(R)?k=d:lx(R)?k=h:u!==p&&cx(R)?k=u:k=p,b+k>v&&(x=Math.min(x,Math.max(E,m)+y)),b+k>n){_=!0;break e}y+=N.length,b+=k}E=C=0}if(f>=g)break;if(lc.lastIndex=f,lc.test(t)){if(y=lc.lastIndex-f,k=y*p,b+k>v&&(x=Math.min(x,f+Math.floor((v-b)/p))),b+k>n){_=!0;break}b+=k,E=m,C=f,f=m=lc.lastIndex;continue}if(xd.lastIndex=f,xd.test(t)){if(b+i>v&&(x=Math.min(x,f)),b+i>n){_=!0;break}b+=i,E=m,C=f,f=m=xd.lastIndex;continue}if(cc.lastIndex=f,cc.test(t)){if(y=cc.lastIndex-f,k=y*a,b+k>v&&(x=Math.min(x,f+Math.floor((v-b)/a))),b+k>n){_=!0;break}b+=k,E=m,C=f,f=m=cc.lastIndex;continue}if(uc.lastIndex=f,uc.test(t)){if(y=uc.lastIndex-f,k=y*c,b+k>v&&(x=Math.min(x,f+Math.floor((v-b)/c))),b+k>n){_=!0;break}b+=k,E=m,C=f,f=m=uc.lastIndex;continue}if(bd.lastIndex=f,bd.test(t)){if(b+l>v&&(x=Math.min(x,f)),b+l>n){_=!0;break}b+=l,E=m,C=f,f=m=bd.lastIndex;continue}f+=1}return{width:_?v:b,index:_?x:g,truncated:_,ellipsed:_&&n>=s}},px=dx;var KR={limit:1/0,ellipsis:"",ellipsisWidth:0},GR=(t,e={})=>px(t,KR,e).width,xt=GR;var dc="\x1B",yx="\x9B",JR=39,Sd="\x07",_x="[",XR="]",xx="m",kd=`${XR}8;;`,mx=new RegExp(`(?:\\${_x}(?<code>\\d+)m|\\${kd}(?<uri>.*)${Sd})`,"y"),fx=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},hx=t=>`${dc}${_x}${t}${xx}`,gx=t=>`${dc}${kd}${t}${Sd}`,vd=(t,e,r)=>{let n=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:xt(i),c=n.next(),u=n.next(),l=0;for(;!c.done;){let d=c.value,p=xt(d);a+p<=r?t[t.length-1]+=d:(t.push(d),a=0),(d===dc||d===yx)&&(o=!0,s=e.startsWith(kd,l+1)),o?s?d===Sd&&(o=!1,s=!1):d===xx&&(o=!1):(a+=p,a===r&&!u.done&&(t.push(""),a=0)),c=u,u=n.next(),l+=d.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},YR=t=>{let e=t.split(" "),r=e.length;for(;r&&!xt(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},QR=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",o,s,i=t.split(" "),a=[""],c=0;for(let d=0;d<i.length;d++){let p=i[d];if(r.trim!==!1){let m=a.at(-1)??"",f=m.trimStart();m.length!==f.length&&(a[a.length-1]=f,c=xt(f))}d!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let h=xt(p);if(r.hard&&h>e){let m=e-c,f=1+Math.floor((h-m-1)/e);Math.floor((h-1)/e)<f&&a.push(""),vd(a,p,e),c=xt(a.at(-1)??"");continue}if(c+h>e&&c&&h){if(r.wordWrap===!1&&c<e){vd(a,p,e),c=xt(a.at(-1)??"");continue}a.push(""),c=0}if(c+h>e&&r.wordWrap===!1){vd(a,p,e),c=xt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=h}r.trim!==!1&&(a=a.map(d=>YR(d)));let u=a.join(`
|
|
1155
|
-
`),l=!1;for(let d=0;d<u.length;d++){let p=u[d];if(n+=p,!l)l=p>="\uD800"&&p<="\uDBFF";else continue;if(p===dc||p===yx){mx.lastIndex=d+1;let m=mx.exec(u)?.groups;if(m?.code!==void 0){let f=Number.parseFloat(m.code);o=f===JR?void 0:f}else m?.uri!==void 0&&(s=m.uri.length===0?void 0:m.uri)}if(u[d+1]===`
|
|
1156
|
-
`){s&&(n+=gx(""));let h=o?fx(o):void 0;o&&h&&(n+=hx(h))}else p===`
|
|
1157
|
-
`&&(o&&fx(o)&&(n+=hx(o)),s&&(n+=gx(s)))}return n},eC=/\r?\n/;function Jo(t,e,r){return String(t).normalize().split(eC).map(n=>QR(n,e,r)).join(`
|
|
1158
|
-
`)}var bi=xi(Ed(),1);import{ReadStream as vx}from"node:tty";var sC=["up","down","left","right","space","enter","cancel"],iC=["January","February","March","April","May","June","July","August","September","October","November","December"],Rr={actions:new Set(sC),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...iC],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function Sx(t,e){if(typeof t=="string")return Rr.aliases.get(t)===e;for(let r of t)if(r!==void 0&&Sx(r,e))return!0;return!1}var aC=globalThis.process.platform.startsWith("win");function kx({input:t=oC,output:e=nC,overwrite:r=!0,hideCursor:n=!0}={}){let o=gn.createInterface({input:t,output:e,prompt:"",tabSize:1});gn.emitKeypressEvents(t,o),t instanceof vx&&t.isTTY&&t.setRawMode(!0);let s=(i,{name:a,sequence:c})=>{let u=String(i);if(Sx([u,a,c],"cancel")){n&&e.write(bi.cursor.show),process.exit(0);return}if(!r)return;gn.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{gn.clearLine(e,1,()=>{t.once("keypress",s)})})};return n&&e.write(bi.cursor.hide),t.once("keypress",s),()=>{t.off("keypress",s),n&&e.write(bi.cursor.show),t instanceof vx&&t.isTTY&&!aC&&t.setRawMode(!1),o.terminal=!1,o.close()}}var $d=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as De,stripVTControlCharacters as Fq}from"node:util";import Vt from"node:process";var vi=xi(Ed(),1);function uC(){return Vt.platform!=="win32"?Vt.env.TERM!=="linux":!!Vt.env.CI||!!Vt.env.WT_SESSION||!!Vt.env.TERMINUS_SUBLIME||Vt.env.ConEmuTask==="{cmd::Cmder}"||Vt.env.TERM_PROGRAM==="Terminus-Sublime"||Vt.env.TERM_PROGRAM==="vscode"||Vt.env.TERM==="xterm-256color"||Vt.env.TERM==="alacritty"||Vt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Td=uC(),lC=()=>process.env.CI==="true";var _e=(t,e)=>Td?t:e,Zq=_e("\u25C6","*"),dC=_e("\u25A0","x"),pC=_e("\u25B2","x"),Pd=_e("\u25C7","o"),mC=_e("\u250C","T"),yn=_e("\u2502","|"),fC=_e("\u2514","\u2014"),qq=_e("\u2510","T"),Vq=_e("\u2518","\u2014"),Wq=_e("\u25CF",">"),Kq=_e("\u25CB"," "),Gq=_e("\u25FB","[\u2022]"),Jq=_e("\u25FC","[+]"),Xq=_e("\u25FB","[ ]"),Yq=_e("\u25AA","\u2022"),wx=_e("\u2500","-"),hC=_e("\u256E","+"),gC=_e("\u251C","+"),yC=_e("\u256F","+"),_C=_e("\u2570","+"),Qq=_e("\u256D","+"),xC=_e("\u25CF","\u2022"),bC=_e("\u25C6","*"),vC=_e("\u25B2","!"),SC=_e("\u25A0","x");var I={message:(t=[],{symbol:e=De("gray",yn),secondarySymbol:r=De("gray",yn),output:n=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??Rr.withGuide,c=a?r:"",u=a?`${e} `:"",l=a?`${r} `:"";for(let p=0;p<o;p++)i.push(c);let d=Array.isArray(t)?t:t.split(`
|
|
1159
|
-
`);if(d.length>0){let[p,...h]=d;p.length>0?i.push(`${u}${p}`):i.push(a?e:"");for(let m of h)m.length>0?i.push(`${l}${m}`):i.push(a?r:"")}n.write(`${i.join(`
|
|
1156
|
+
EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:j.object({confirm:j.preprocess(xx,j.boolean()).describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:j.string().optional().describe("UUID of a single session. Pairs with confirm:true to wipe only that session's events + per-session FTS5 chunks. Sibling sessions and the stats file are preserved. MUST NOT be combined with scope:'project'."),scope:j.enum(["session","project"]).optional().describe("Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.")})},async({confirm:t,sessionId:e,scope:n})=>{if(e&&n==="project")return Y("ctx_purge",{content:[{type:"text",text:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe."}],isError:!0});if(!t)return Y("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let r=n??(e?"session":"project");!n&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let o;try{o=xd()}catch{}if(wn){try{wn.cleanup()}catch{}wn=null}let s=o?gi(o):void 0,{deleted:i}=jP({projectDir:Lt(),sessionsDir:Ve(),storePath:o,contentDir:s,legacyContentDir:zt(hi(),".context-mode","content"),contentHash:On(Lt()),scope:r,sessionId:e});if(r==="project"){ie.calls={},ie.bytesReturned={},ie.bytesIndexed=0,ie.bytesSandboxed=0,ie.cacheHits=0,ie.cacheBytesSaved=0,ie.sessionStart=Date.now(),i.push("session stats");try{let c=UR();We(c)&&fi(c)}catch{}}let a=r==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return Y("ctx_purge",{content:[{type:"text",text:a}]})});nc=5e3;cx="https://context-mode.com/insight";Pe.registerTool("ctx_insight",{title:"Open Insight Dashboard",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},description:"Opens the context-mode Insight dashboard (https://context-mode.com/insight) in your default browser \u2014 a dashboard launcher for the hosted analytics layer, not a Q&A engine. Insight surfaces per-engineer productive rate, retry waste, blocker detection, and role-narrowed views for CTO, EM, IC, CISO, FinOps, and DevOps. For natural-language queries over your indexed content, use ctx_search.",inputSchema:j.object({})},async()=>{let t=eC(cx),e=t.ok?`Opening Insight in your browser: ${cx}`:`Could not auto-open your browser (${t.reason}).
|
|
1157
|
+
Open Insight manually: ${cx}`;return Y("ctx_insight",{content:[{type:"text",text:e}]})});FR();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&Yq().catch(t=>{console.error("Fatal:",t),process.exit(1)})});var dC={};_e(dC,{needsHookNormalization:()=>cc,normalizeHooksJson:()=>cC,normalizeHooksJsonOnly:()=>lC,normalizeHooksOnStartup:()=>Qq,normalizePluginJson:()=>uC});import{existsSync as oC,readFileSync as sC,writeFileSync as iC}from"node:fs";import{resolve as aC}from"node:path";function Kr(t){return String(t).replace(/\\/g,"/")}function bx(t){if(!t)return null;let e=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?:\/|$)/.exec(Kr(t));return e?e[1]:null}function Sx(t,e){if(!e||!t||typeof t!="string")return!1;let n=Kr(t);Ed.lastIndex=0;let r;for(;(r=Ed.exec(n))!==null;)if(r[1]!==e)return!0;return!1}function cc(t,e){return!t||typeof t!="string"?!1:t.includes(ac)?!0:Sx(t,bx(e))}function cC(t,e,n){if(!cc(t,n))return t;let r=Kr(e),o=Kr(n),s=bx(n),i;try{i=JSON.parse(t)}catch{return t}let a=i?.hooks;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let l=a[u];if(Array.isArray(l))for(let d of l){let p=d?.hooks;if(Array.isArray(p))for(let h of p){if(typeof h?.command!="string")continue;let m=h.command.includes(ac),f=Sx(h.command,s);if(!m&&!f)continue;let g=h.command;m&&(g=g.replaceAll(ac,o),g=g.replace(/^\s*node\s+/,`"${r}" `)),f&&(g=Kr(g).replace(Ed,`context-mode/context-mode/${s}`)),h.command=g,c=!0}}}return c?JSON.stringify(i,null,2):t}function uC(t,e,n){if(!cc(t,n))return t;let r=Kr(e),o=Kr(n),s=bx(n),i;try{i=JSON.parse(t)}catch{return t}let a=i?.mcpServers;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let l=a[u];if(!(!l||typeof l!="object")){if(Array.isArray(l.args)){let d=l.args,p=d.map(h=>{if(typeof h!="string")return h;let m=h;return m.includes(ac)&&(m=m.replaceAll(ac,o)),Sx(m,s)&&(m=Kr(m).replace(Ed,`context-mode/context-mode/${s}`)),m});p.some((h,m)=>h!==d[m])&&(l.args=p,c=!0)}l.command==="node"&&c&&(l.command=r)}}return c?JSON.stringify(i,null,2):t}function lC({pluginRoot:t,nodePath:e,jsRuntimePath:n,platform:r}){let o=n||e;if(!(r!=="win32"&&r!=="linux"&&!(n&&n!==e))&&!(!t||!o))try{let a=aC(t,"hooks","hooks.json");if(oC(a)){let c=sC(a,"utf-8");if(cc(c,t)){let u=cC(c,o,t);u!==c&&iC(a,u,"utf-8")}}}catch{}}function Qq({pluginRoot:t,nodePath:e,jsRuntimePath:n,platform:r}){if(lC({pluginRoot:t,nodePath:e,jsRuntimePath:n,platform:r}),!(r!=="win32"&&r!=="linux")&&!(!t||!e))try{let o=aC(t,".claude-plugin","plugin.json");if(oC(o)){let s=sC(o,"utf-8");if(cc(s,t)){let i=uC(s,e,t);i!==s&&iC(o,i,"utf-8")}}}catch{}}var ac,Ed,pC=v(()=>{"use strict";ac="${CLAUDE_PLUGIN_ROOT}",Ed=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?=\/)/g});var bC={};_e(bC,{buildHookCommand:()=>yC,ensureShebangAndExecBit:()=>xC,extractNodePath:()=>hC,isStaleNodePath:()=>gC,rewriteShellSnapshots:()=>_C,selfHealCacheHealHook:()=>s4,selfHealShellSnapshots:()=>i4});import{existsSync as uc,readFileSync as vx,writeFileSync as kx,chmodSync as e4,statSync as fC,readdirSync as t4,renameSync as n4,unlinkSync as r4}from"node:fs";import{join as o4}from"node:path";function mC(t){return String(t).replace(/\\/g,"/")}function hC(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e)return null;let n;if(e.startsWith('"')){let o=e.indexOf('"',1);if(o===-1)return null;n=e.slice(1,o)}else{let o=e.search(/\s/);n=o===-1?e:e.slice(0,o)}if(!n)return null;let r=n.split(/[\\/]/).pop()??"";return/^node(\.exe)?$/i.test(r)?n:null}function gC(t){let e=hC(t);if(!e)return!1;try{return!uc(e)}catch{return!1}}function yC({scriptPath:t,platform:e,nodePath:n}){if(!t||typeof t!="string")throw new TypeError("buildHookCommand: scriptPath is required");let r=mC(t);if(e==="win32"){if(!n||typeof n!="string")throw new TypeError("buildHookCommand: nodePath is required on win32");return`"${mC(n)}" "${r}"`}return`"${r}"`}function s4({settingsPath:t,scriptPath:e,platform:n,nodePath:r}){if(!t||!uc(t))return"missing-settings";let o;try{o=vx(t,"utf-8")}catch{return"noop"}let s;try{s=JSON.parse(o)}catch{return"noop"}let i=s?.hooks;if(!i||typeof i!="object")return"noop";let a=Array.isArray(i.SessionStart)?i.SessionStart:null;if(!a)return"noop";let c=!1;for(let u of a){let l=u?.hooks;if(Array.isArray(l))for(let d of l)typeof d?.command=="string"&&d.command.includes("context-mode-cache-heal")&&gC(d.command)&&(d.command=yC({scriptPath:e,platform:n,nodePath:r}),c=!0)}if(!c)return"noop";if(n!=="win32"&&e&&uc(e))try{xC(e)}catch{}try{kx(t,JSON.stringify(s,null,2)+`
|
|
1158
|
+
`,"utf-8")}catch{return"noop"}return"healed"}function _C({snapshotsDir:t,currentVersion:e}){let n={rewritten:[]};if(!t||typeof t!="string"||!e||typeof e!="string")return n;let r;try{if(!uc(t))return n;r=t4(t)}catch{return n}let o=/(context-mode[/\\]context-mode[/\\])([^/\\]+)([/\\]bin)/g;for(let s of r){if(!s.endsWith(".sh"))continue;let i=o4(t,s),a;try{if(!fC(i).isFile())continue;a=vx(i,"utf-8")}catch{continue}let c=!1,u=a.replace(o,(d,p,h,m)=>h===e?d:(c=!0,`${p}${e}${m}`));if(!c)continue;let l=`${i}.tmp-${process.pid}-${Date.now()}`;try{kx(l,u,"utf-8"),n4(l,i),n.rewritten.push(i)}catch{try{r4(l)}catch{}}}return n}function i4({snapshotsDir:t,pluginCacheRoot:e,currentVersion:n}){return _C({snapshotsDir:t,currentVersion:n})}function xC(t){if(!(!t||!uc(t)))try{let e=vx(t,"utf-8");e.startsWith("#!")||kx(t,`#!/usr/bin/env node
|
|
1159
|
+
${e}`,"utf-8"),(fC(t).mode&511)!==493&&e4(t,493)}catch{}}var SC=v(()=>{"use strict"});import{stdout as rO,stdin as oO}from"node:process";import*as mr from"node:readline";var Rx=t=>t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109,Cx=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Ox=t=>t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t===94192||t===94193||t>=94208&&t<=100343||t>=100352&&t<=101589||t>=101632&&t<=101640||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128727||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129672||t>=129680&&t<=129725||t>=129727&&t<=129733||t>=129742&&t<=129755||t>=129760&&t<=129768||t>=129776&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141;var Md=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,mc=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,fc=/\t{1,1000}/y,jd=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),hc=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,VC=new RegExp("\\p{M}+","gu"),WC={limit:1/0,ellipsis:""},Ix=(t,e={},n={})=>{let r=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?Ix(o,WC,n).width:0),i=n.ansiWidth??0,a=n.controlWidth??0,c=n.tabWidth??8,u=n.ambiguousWidth??1,l=n.emojiWidth??2,d=n.fullWidthWidth??2,p=n.regularWidth??1,h=n.wideWidth??2,m=0,f=0,g=t.length,y=0,_=!1,x=g,S=Math.max(0,r-s),E=0,A=0,b=0,T=0;e:for(;;){if(A>E||f>=g&&f>m){let P=t.slice(E,A)||t.slice(m,f);y=0;for(let N of P.replaceAll(VC,"")){let R=N.codePointAt(0)||0;if(Cx(R)?T=d:Ox(R)?T=h:u!==p&&Rx(R)?T=u:T=p,b+T>S&&(x=Math.min(x,Math.max(E,m)+y)),b+T>r){_=!0;break e}y+=N.length,b+=T}E=A=0}if(f>=g)break;if(hc.lastIndex=f,hc.test(t)){if(y=hc.lastIndex-f,T=y*p,b+T>S&&(x=Math.min(x,f+Math.floor((S-b)/p))),b+T>r){_=!0;break}b+=T,E=m,A=f,f=m=hc.lastIndex;continue}if(Md.lastIndex=f,Md.test(t)){if(b+i>S&&(x=Math.min(x,f)),b+i>r){_=!0;break}b+=i,E=m,A=f,f=m=Md.lastIndex;continue}if(mc.lastIndex=f,mc.test(t)){if(y=mc.lastIndex-f,T=y*a,b+T>S&&(x=Math.min(x,f+Math.floor((S-b)/a))),b+T>r){_=!0;break}b+=T,E=m,A=f,f=m=mc.lastIndex;continue}if(fc.lastIndex=f,fc.test(t)){if(y=fc.lastIndex-f,T=y*c,b+T>S&&(x=Math.min(x,f+Math.floor((S-b)/c))),b+T>r){_=!0;break}b+=T,E=m,A=f,f=m=fc.lastIndex;continue}if(jd.lastIndex=f,jd.test(t)){if(b+l>S&&(x=Math.min(x,f)),b+l>r){_=!0;break}b+=l,E=m,A=f,f=m=jd.lastIndex;continue}f+=1}return{width:_?S:b,index:_?x:g,truncated:_,ellipsed:_&&r>=s}},Ax=Ix;var KC={limit:1/0,ellipsis:"",ellipsisWidth:0},GC=(t,e={})=>Ax(t,KC,e).width,bt=GC;var gc="\x1B",Lx="\x9B",JC=39,zd="\x07",zx="[",XC="]",Fx="m",Fd=`${XC}8;;`,Nx=new RegExp(`(?:\\${zx}(?<code>\\d+)m|\\${Fd}(?<uri>.*)${zd})`,"y"),Dx=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},Mx=t=>`${gc}${zx}${t}${Fx}`,jx=t=>`${gc}${Fd}${t}${zd}`,Ld=(t,e,n)=>{let r=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:bt(i),c=r.next(),u=r.next(),l=0;for(;!c.done;){let d=c.value,p=bt(d);a+p<=n?t[t.length-1]+=d:(t.push(d),a=0),(d===gc||d===Lx)&&(o=!0,s=e.startsWith(Fd,l+1)),o?s?d===zd&&(o=!1,s=!1):d===Fx&&(o=!1):(a+=p,a===n&&!u.done&&(t.push(""),a=0)),c=u,u=r.next(),l+=d.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},YC=t=>{let e=t.split(" "),n=e.length;for(;n&&!bt(e[n-1]);)n--;return n===e.length?t:e.slice(0,n).join(" ")+e.slice(n).join("")},QC=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let r="",o,s,i=t.split(" "),a=[""],c=0;for(let d=0;d<i.length;d++){let p=i[d];if(n.trim!==!1){let m=a.at(-1)??"",f=m.trimStart();m.length!==f.length&&(a[a.length-1]=f,c=bt(f))}d!==0&&(c>=e&&(n.wordWrap===!1||n.trim===!1)&&(a.push(""),c=0),(c||n.trim===!1)&&(a[a.length-1]+=" ",c++));let h=bt(p);if(n.hard&&h>e){let m=e-c,f=1+Math.floor((h-m-1)/e);Math.floor((h-1)/e)<f&&a.push(""),Ld(a,p,e),c=bt(a.at(-1)??"");continue}if(c+h>e&&c&&h){if(n.wordWrap===!1&&c<e){Ld(a,p,e),c=bt(a.at(-1)??"");continue}a.push(""),c=0}if(c+h>e&&n.wordWrap===!1){Ld(a,p,e),c=bt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=h}n.trim!==!1&&(a=a.map(d=>YC(d)));let u=a.join(`
|
|
1160
|
+
`),l=!1;for(let d=0;d<u.length;d++){let p=u[d];if(r+=p,!l)l=p>="\uD800"&&p<="\uDBFF";else continue;if(p===gc||p===Lx){Nx.lastIndex=d+1;let m=Nx.exec(u)?.groups;if(m?.code!==void 0){let f=Number.parseFloat(m.code);o=f===JC?void 0:f}else m?.uri!==void 0&&(s=m.uri.length===0?void 0:m.uri)}if(u[d+1]===`
|
|
1161
|
+
`){s&&(r+=jx(""));let h=o?Dx(o):void 0;o&&h&&(r+=Mx(h))}else p===`
|
|
1162
|
+
`&&(o&&Dx(o)&&(r+=Mx(o)),s&&(r+=jx(s)))}return r},eO=/\r?\n/;function Xo(t,e,n){return String(t).normalize().split(eO).map(r=>QC(r,e,n)).join(`
|
|
1163
|
+
`)}var bi=xi(Ud(),1);import{ReadStream as Ux}from"node:tty";var sO=["up","down","left","right","space","enter","cancel"],iO=["January","February","March","April","May","June","July","August","September","October","November","December"],Pn={actions:new Set(sO),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...iO],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function Bx(t,e){if(typeof t=="string")return Pn.aliases.get(t)===e;for(let n of t)if(n!==void 0&&Bx(n,e))return!0;return!1}var aO=globalThis.process.platform.startsWith("win");function Zx({input:t=oO,output:e=rO,overwrite:n=!0,hideCursor:r=!0}={}){let o=mr.createInterface({input:t,output:e,prompt:"",tabSize:1});mr.emitKeypressEvents(t,o),t instanceof Ux&&t.isTTY&&t.setRawMode(!0);let s=(i,{name:a,sequence:c})=>{let u=String(i);if(Bx([u,a,c],"cancel")){r&&e.write(bi.cursor.show),process.exit(0);return}if(!n)return;mr.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{mr.clearLine(e,1,()=>{t.once("keypress",s)})})};return r&&e.write(bi.cursor.hide),t.once("keypress",s),()=>{t.off("keypress",s),r&&e.write(bi.cursor.show),t instanceof Ux&&t.isTTY&&!aO&&t.setRawMode(!1),o.terminal=!1,o.close()}}var Bd=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as Ae,stripVTControlCharacters as d9}from"node:util";import Vt from"node:process";var Si=xi(Ud(),1);function uO(){return Vt.platform!=="win32"?Vt.env.TERM!=="linux":!!Vt.env.CI||!!Vt.env.WT_SESSION||!!Vt.env.TERMINUS_SUBLIME||Vt.env.ConEmuTask==="{cmd::Cmder}"||Vt.env.TERM_PROGRAM==="Terminus-Sublime"||Vt.env.TERM_PROGRAM==="vscode"||Vt.env.TERM==="xterm-256color"||Vt.env.TERM==="alacritty"||Vt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Zd=uO(),lO=()=>process.env.CI==="true";var xe=(t,e)=>Zd?t:e,h9=xe("\u25C6","*"),dO=xe("\u25A0","x"),pO=xe("\u25B2","x"),qd=xe("\u25C7","o"),mO=xe("\u250C","T"),fr=xe("\u2502","|"),fO=xe("\u2514","\u2014"),g9=xe("\u2510","T"),y9=xe("\u2518","\u2014"),_9=xe("\u25CF",">"),x9=xe("\u25CB"," "),b9=xe("\u25FB","[\u2022]"),S9=xe("\u25FC","[+]"),v9=xe("\u25FB","[ ]"),k9=xe("\u25AA","\u2022"),qx=xe("\u2500","-"),hO=xe("\u256E","+"),gO=xe("\u251C","+"),yO=xe("\u256F","+"),_O=xe("\u2570","+"),w9=xe("\u256D","+"),xO=xe("\u25CF","\u2022"),bO=xe("\u25C6","*"),SO=xe("\u25B2","!"),vO=xe("\u25A0","x");var O={message:(t=[],{symbol:e=Ae("gray",fr),secondarySymbol:n=Ae("gray",fr),output:r=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??Pn.withGuide,c=a?n:"",u=a?`${e} `:"",l=a?`${n} `:"";for(let p=0;p<o;p++)i.push(c);let d=Array.isArray(t)?t:t.split(`
|
|
1164
|
+
`);if(d.length>0){let[p,...h]=d;p.length>0?i.push(`${u}${p}`):i.push(a?e:"");for(let m of h)m.length>0?i.push(`${l}${m}`):i.push(a?n:"")}r.write(`${i.join(`
|
|
1160
1165
|
`)}
|
|
1161
|
-
`)},info:(t,e)=>{
|
|
1162
|
-
`)},
|
|
1163
|
-
${
|
|
1164
|
-
|
|
1165
|
-
`)};var
|
|
1166
|
-
`),s=o.reduce((c,u)=>Math.max(
|
|
1167
|
-
`).map(s),""],a=
|
|
1168
|
-
`),l=o?`${
|
|
1169
|
-
`:"",d=o?
|
|
1166
|
+
`)},info:(t,e)=>{O.message(t,{...e,symbol:Ae("blue",xO)})},success:(t,e)=>{O.message(t,{...e,symbol:Ae("green",bO)})},step:(t,e)=>{O.message(t,{...e,symbol:Ae("green",qd)})},warn:(t,e)=>{O.message(t,{...e,symbol:Ae("yellow",SO)})},warning:(t,e)=>{O.warn(t,e)},error:(t,e)=>{O.message(t,{...e,symbol:Ae("red",vO)})}};var Vd=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Pn.withGuide?`${Ae("gray",mO)} `:"";n.write(`${r}${t}
|
|
1167
|
+
`)},yc=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Pn.withGuide?`${Ae("gray",fr)}
|
|
1168
|
+
${Ae("gray",fO)} `:"";n.write(`${r}${t}
|
|
1169
|
+
|
|
1170
|
+
`)};var kO=t=>Ae("dim",t),wO=(t,e,n)=>{let r={hard:!0,trim:!1},o=Xo(t,e,r).split(`
|
|
1171
|
+
`),s=o.reduce((c,u)=>Math.max(bt(u),c),0),i=o.map(n).reduce((c,u)=>Math.max(bt(u),c),0),a=e-(i-s);return Xo(t,a,r)},_c=(t="",e="",n)=>{let r=n?.output??Vt.stdout,o=n?.withGuide??Pn.withGuide,s=n?.format??kO,i=["",...wO(t,Bd(r)-6,s).split(`
|
|
1172
|
+
`).map(s),""],a=bt(e),c=Math.max(i.reduce((p,h)=>{let m=bt(h);return m>p?m:p},0),a)+2,u=i.map(p=>`${Ae("gray",fr)} ${p}${" ".repeat(c-bt(p))}${Ae("gray",fr)}`).join(`
|
|
1173
|
+
`),l=o?`${Ae("gray",fr)}
|
|
1174
|
+
`:"",d=o?gO:_O;r.write(`${l}${Ae("green",qd)} ${Ae("reset",e)} ${Ae("gray",qx.repeat(Math.max(c-a-1,1))+hO)}
|
|
1170
1175
|
${u}
|
|
1171
|
-
${
|
|
1172
|
-
`)};var
|
|
1173
|
-
`);let
|
|
1174
|
-
`);
|
|
1175
|
-
`);let ge=0,
|
|
1176
|
-
`):
|
|
1177
|
-
`)),b(),l()};return{start:
|
|
1178
|
-
`)}catch{}return null}return i[1]}catch{return null}}
|
|
1179
|
-
`))}if(
|
|
1180
|
-
Could not auto-open browser. Open manually: ${t}`),s=
|
|
1181
|
-
`),"Storage paths"),
|
|
1176
|
+
${Ae("gray",d+qx.repeat(c+2)+yO)}
|
|
1177
|
+
`)};var EO=t=>Ae("magenta",t),Wd=({indicator:t="dots",onCancel:e,output:n=process.stdout,cancelMessage:r,errorMessage:o,frames:s=Zd?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=Zd?80:120,signal:a,...c}={})=>{let u=lO(),l,d,p=!1,h=!1,m="",f,g=performance.now(),y=Bd(n),_=c?.styleFrame??EO,x=W=>{let ge=W>1?o??Pn.messages.error:r??Pn.messages.cancel;h=W===1,p&&(F(ge,W),h&&typeof e=="function"&&e())},S=()=>x(2),E=()=>x(1),A=()=>{process.on("uncaughtExceptionMonitor",S),process.on("unhandledRejection",S),process.on("SIGINT",E),process.on("SIGTERM",E),process.on("exit",x),a&&a.addEventListener("abort",E)},b=()=>{process.removeListener("uncaughtExceptionMonitor",S),process.removeListener("unhandledRejection",S),process.removeListener("SIGINT",E),process.removeListener("SIGTERM",E),process.removeListener("exit",x),a&&a.removeEventListener("abort",E)},T=()=>{if(f===void 0)return;u&&n.write(`
|
|
1178
|
+
`);let W=Xo(f,y,{hard:!0,trim:!1}).split(`
|
|
1179
|
+
`);W.length>1&&n.write(Si.cursor.up(W.length-1)),n.write(Si.cursor.to(0)),n.write(Si.erase.down())},P=W=>W.replace(/\.+$/,""),N=W=>{let ge=(performance.now()-W)/1e3,Le=Math.floor(ge/60),st=Math.floor(ge%60);return Le>0?`[${Le}m ${st}s]`:`[${st}s]`},R=c.withGuide??Pn.withGuide,C=(W="")=>{p=!0,l=Zx({output:n}),m=P(W),g=performance.now(),R&&n.write(`${Ae("gray",fr)}
|
|
1180
|
+
`);let ge=0,Le=0;A(),d=setInterval(()=>{if(u&&m===f)return;T(),f=m;let st=_(s[ge]),$n;if(u)$n=`${st} ${m}...`;else if(t==="timer")$n=`${st} ${m} ${N(g)}`;else{let pc=".".repeat(Math.floor(Le)).slice(0,3);$n=`${st} ${m}${pc}`}let dc=Xo($n,y,{hard:!0,trim:!1});n.write(dc),ge=ge+1<s.length?ge+1:0,Le=Le<4?Le+.125:0},i)},F=(W="",ge=0,Le=!1)=>{if(!p)return;p=!1,clearInterval(d),T();let st=ge===0?Ae("green",qd):ge===1?Ae("red",dO):Ae("red",pO);m=W??m,Le||(t==="timer"?n.write(`${st} ${m} ${N(g)}
|
|
1181
|
+
`):n.write(`${st} ${m}
|
|
1182
|
+
`)),b(),l()};return{start:C,stop:(W="")=>F(W,0),message:(W="")=>{m=P(W??m)},cancel:(W="")=>F(W,1),error:(W="")=>F(W,2),clear:()=>F("",0,!0),get isCancelled(){return h}}},E9={light:xe("\u2500","-"),heavy:xe("\u2501","="),block:xe("\u2588","#")};var T9=`${Ae("gray",fr)} `;var k=xi(Kx(),1);Yo();np();kr();Jt();km();$m();import{execFileSync as yi,execSync as a4,execFile as c4}from"node:child_process";import{readFileSync as qn,cpSync as vC,accessSync as EC,existsSync as Ze,readdirSync as u4,rmSync as Td,closeSync as l4,openSync as d4,chmodSync as p4,lstatSync as m4,realpathSync as Rd,statSync as TC,constants as $C}from"node:fs";import{request as f4}from"node:https";import{resolve as Q,dirname as PC,join as lc,sep as Vn,basename as h4,isAbsolute as g4}from"node:path";import{tmpdir as y4,devNull as _4,homedir as Cd}from"node:os";import{fileURLToPath as x4,pathToFileURL as Od}from"node:url";import{execFileSync as JN}from"node:child_process";var XN="node.*plugins/(cache|marketplaces)/.*context-mode.*start\\.mjs",YN=`Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -match 'plugins[\\\\/](cache|marketplaces)[\\\\/].*context-mode.*start\\.mjs' } | Select-Object -ExpandProperty ProcessId`,QN=(t,e)=>JN(t,[...e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),eD=t=>{try{return process.kill(t,0),!0}catch{return!1}},tD=(t,e)=>{process.kill(t,e)};function nD(t){let e=new Set;for(let n of t.split(/\r?\n/)){let r=n.trim();if(!r||!/^\d+$/.test(r))continue;let o=Number.parseInt(r,10);Number.isFinite(o)&&o>0&&e.add(o)}return[...e]}function Fv(t){let e=t.platform??process.platform,n=t.runCommand??QN,r="";try{e==="win32"?r=n("powershell",["-NoProfile","-Command",YN]):r=n("pgrep",["-f",XN])}catch{return[]}return nD(r).filter(o=>o!==t.ownPid&&o!==t.ownPpid)}function rD(t){return new Promise(e=>{setTimeout(e,t)})}async function Hv(t){let e=t.timeoutMs??1500,n=t.pollIntervalMs??100,r=t.isAlive??eD,o=t.sendSignal??tD,s={terminatedBySigterm:0,terminatedBySigkill:0,totalKilled:0};if(t.pids.length===0)return s;let i=new Set,a=new Set;for(let d of t.pids){r(d)&&(i.add(d),a.add(d));try{o(d,"SIGTERM")}catch(p){p?.code!=="ESRCH"&&a.delete(d)}}let c=Date.now()+e,u=0;for(;a.size>0&&Date.now()<c;){await rD(n);for(let d of[...a])r(d)||(a.delete(d),u++)}let l=0;for(let d of a){try{o(d,"SIGKILL")}catch(p){if(p?.code==="ESRCH"){u++;continue}continue}i.has(d)&&l++}return{terminatedBySigterm:u,terminatedBySigkill:l,totalKilled:u+l}}Pm();import{existsSync as dD}from"node:fs";import{execSync as pD,execFileSync as l6,spawnSync as d6}from"node:child_process";function Bv({platform:t=process.platform,existsSync:e=dD,exec:n=pD,now:r=()=>new Date().getFullYear()}={}){if(t!=="win32")return null;try{let o="C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\vswhere.exe";if(!e(o))return null;let i=n(`"${o}" -latest -property displayName`,{encoding:"utf-8",stdio:"pipe",timeout:15e3}).trim().match(/\b(20\d{2})\b/);if(!i)return null;let a=Number(i[1]),c=r()+5;if(a>c){try{process.stderr.write(`[context-mode] vswhere displayName reports VS year ${a} (> ${c}); ignoring as likely corrupted output. Falling back to node-gyp default detection.
|
|
1183
|
+
`)}catch{}return null}return i[1]}catch{return null}}lo();Rn();function b4(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}var S4={"claude-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs",stop:"hooks/stop.mjs"},"gemini-cli":{beforeagent:"hooks/gemini-cli/beforeagent.mjs",beforetool:"hooks/gemini-cli/beforetool.mjs",aftertool:"hooks/gemini-cli/aftertool.mjs",precompress:"hooks/gemini-cli/precompress.mjs",sessionstart:"hooks/gemini-cli/sessionstart.mjs"},"vscode-copilot":{pretooluse:"hooks/vscode-copilot/pretooluse.mjs",posttooluse:"hooks/vscode-copilot/posttooluse.mjs",precompact:"hooks/vscode-copilot/precompact.mjs",sessionstart:"hooks/vscode-copilot/sessionstart.mjs"},cursor:{pretooluse:"hooks/cursor/pretooluse.mjs",posttooluse:"hooks/cursor/posttooluse.mjs",sessionstart:"hooks/cursor/sessionstart.mjs",stop:"hooks/cursor/stop.mjs",afteragentresponse:"hooks/cursor/afteragentresponse.mjs"},codex:{pretooluse:"hooks/codex/pretooluse.mjs",posttooluse:"hooks/codex/posttooluse.mjs",precompact:"hooks/codex/precompact.mjs",sessionstart:"hooks/codex/sessionstart.mjs",userpromptsubmit:"hooks/codex/userpromptsubmit.mjs",stop:"hooks/codex/stop.mjs"},kiro:{pretooluse:"hooks/kiro/pretooluse.mjs",posttooluse:"hooks/kiro/posttooluse.mjs"},"jetbrains-copilot":{pretooluse:"hooks/jetbrains-copilot/pretooluse.mjs",posttooluse:"hooks/jetbrains-copilot/posttooluse.mjs",precompact:"hooks/jetbrains-copilot/precompact.mjs",sessionstart:"hooks/jetbrains-copilot/sessionstart.mjs"},"copilot-cli":{pretooluse:"hooks/copilot-cli/pretooluse.mjs",posttooluse:"hooks/copilot-cli/posttooluse.mjs",precompact:"hooks/copilot-cli/precompact.mjs",sessionstart:"hooks/copilot-cli/sessionstart.mjs",userpromptsubmit:"hooks/copilot-cli/userpromptsubmit.mjs",stop:"hooks/copilot-cli/stop.mjs"},"antigravity-cli":{pretooluse:"hooks/antigravity-cli/pretooluse.mjs",posttooluse:"hooks/antigravity-cli/posttooluse.mjs",stop:"hooks/antigravity-cli/stop.mjs"},kimi:{pretooluse:"hooks/kimi/pretooluse.mjs",posttooluse:"hooks/kimi/posttooluse.mjs",precompact:"hooks/kimi/precompact.mjs",sessionstart:"hooks/kimi/sessionstart.mjs",sessionend:"hooks/kimi/sessionend.mjs",userpromptsubmit:"hooks/kimi/userpromptsubmit.mjs",stop:"hooks/kimi/stop.mjs"},"qwen-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"}};async function v4(t,e){try{l4(2),d4(_4,"w")}catch{process.stderr.write=(()=>!0)}let n=S4[t]?.[e];n||process.exit(0);let r=_i();await import(Od(lc(r,n)).href)}var ft=process.argv.slice(2);function k4(){console.log(["Usage:"," context-mode Start MCP server (stdio)"," context-mode index <path> Index a file or directory into the FTS5 knowledge base"," context-mode search <query...> Search the current project's FTS5 knowledge base"," context-mode doctor Diagnose runtime issues, hooks, FTS5, version"," context-mode upgrade Fix hooks, permissions, and settings"," context-mode hook <platform> <event> Dispatch a configured hook script"," context-mode statusline Print Claude Code status line","","Index options:"," --source <label> Source label (default: project:<directory-name> or path)"," --project <path> Project identity for the content DB (default: indexed dir or cwd)"," --max-depth <n> Directory recursion depth (default: 5)"," --max-files <n> Directory file cap (default: 200)"," --ext <.ts,.md> Comma-separated extension allowlist"," --include <glob> Directory include pattern (repeatable)"," --exclude <glob> Directory exclude pattern (repeatable)"," --no-gitignore Do not apply .gitignore during directory walks"," --follow-symlinks Follow directory symlinks inside the root","","Search options:"," --project <path> Project identity for the content DB (default: cwd)"," --source <label> Filter to a source label (partial match)"," --limit <n> Results to show (default: 3)"," --type <code|prose> Filter by content type","","Environment:"," CONTEXT_MODE_DIR=/absolute/path Override sessions/content storage root; empty is ignored, non-empty must be absolute"].join(`
|
|
1184
|
+
`))}if(ft[0]==="--help"||ft[0]==="-h"||ft[0]==="help")k4();else if(ft[0]==="index")O4(ft.slice(1)).then(t=>process.exit(t));else if(ft[0]==="search")I4(ft.slice(1)).then(t=>process.exit(t));else if(ft[0]==="doctor")A4().then(t=>process.exit(t));else if(ft[0]==="upgrade"){let t=ft.indexOf("--platform"),e=t>=0&&ft[t+1]?ft[t+1]:void 0;D4(e?{platform:e}:void 0).catch(n=>{let r=n instanceof Error?n.message:String(n);O.error(k.default.red(r)),process.exit(1)})}else ft[0]==="hook"?v4(ft[1],ft[2]):ft[0]==="insight"?N4():ft[0]==="statusline"?M4():Promise.resolve().then(()=>(rC(),nC));function mQ(t){return t.replace(/\\/g,"/")}var Id=process.platform==="win32";function $d(t,e={}){yi(Id?"npm.cmd":"npm",t,{...e,...Id?{shell:!0}:{}})}function fQ(t,e={}){let n={...e,...Id?{shell:!0}:{}};a4(Id?t.replace(/^npm /,"npm.cmd "):t,n)}function w4(t,e=process.platform,n=c4){let r={stdio:"ignore"},o=()=>console.error(`
|
|
1185
|
+
Could not auto-open browser. Open manually: ${t}`),s=b4(t,e),i=!1;for(let{cmd:a,args:c}of s)try{n(a,c,r),i=!0;break}catch{}i||o()}function E4(){let t=x4(import.meta.url),e=PC(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?Q(e,".."):e}function T4(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let n=process.env.LOCALAPPDATA;return n?Q(n,t,...e):Q(Cd(),"AppData","Local",t,...e)}return Q(Cd(),".cache",t,...e)}function _i(){let t=Qe().platform;return Jr(t)?T4(t):E4()}function RC(){try{return JSON.parse(qn(Q(_i(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function $4(){return new Promise(t=>{let e=f4("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{try{let o=JSON.parse(r);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function Pd(t){return t.envVar?t.envVar:"adapter default"}function CC(t){let e=[],n={};for(let r=0;r<t.length;r++){let o=t[r];if(!o.startsWith("--")||o==="--"){e.push(o);continue}let s=o.slice(2),i=s.indexOf("="),a=i>=0?s.slice(0,i):s,c=i>=0?s.slice(i+1):void 0,u=t[r+1],l=c!==void 0?c:u&&!u.startsWith("--")?(r++,u):!0;if(a==="include"||a==="exclude"){let d=n[a];n[a]=Array.isArray(d)?[...d,String(l)]:[String(l)]}else n[a]=l}return{positional:e,flags:n}}function Gr(t,e){let n=t[e];if(typeof n=="string"&&n.length>0)return n}function kC(t,e){return t[e]===!0||t[e]==="true"}function wC(t,e){let n=t[e];if(Array.isArray(n))return n.filter(Boolean);if(typeof n=="string"&&n.length>0)return[n]}function Ex(t,e,n={}){let r=Gr(t,e);if(!r)return;let o=Number(r),s=n.min??1;if(!Number.isInteger(o)||o<s)throw new Error(`--${e} must be an integer >= ${s}`);return o}function P4(t){let e=Gr(t,"ext")??Gr(t,"extensions");if(!e)return;let n=e.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.startsWith(".")?r:`.${r}`);return n.length>0?n:void 0}function OC(t,e){return t?Q(t):Q(e)}async function IC(t){let e=await Fi(Qe().platform),n=Yr(()=>e.getSessionDir()),r=Sr(n),{resolveContentStorePath:o}=await Promise.resolve().then(()=>(Jt(),Sb)),s=o({projectDir:t,contentDir:r});return{store:new Ss(s),dbPath:s,contentDir:r}}function R4(t){try{if(TC(t).isDirectory())return`project:${h4(t)||t}`}catch{}return t}function C4(t,e){let n=po("Read",e);if(mo(t,n,process.platform==="win32",e).denied)throw new Error(`Read denied by policy: ${t}`)}async function O4(t){try{let e=CC(t),n=e.positional[0];if(!n||n==="-h"||n==="--help")return console.log("Usage: context-mode index <path> [--source label] [--project path] [--max-files n] [--max-depth n] [--ext .ts,.md]"),n?0:1;let r=g4(n)?Q(n):Q(process.cwd(),n);if(!Ze(r))throw new Error(`Path does not exist: ${r}`);let o=TC(r),s=OC(Gr(e.flags,"project"),o.isDirectory()?r:PC(r)),i=Gr(e.flags,"source")??R4(r),{store:a,dbPath:c}=await IC(s);try{if(C4(r,s),o.isDirectory()){let u=po("Read",s),l=a.indexDirectory({path:r,source:i,include:wC(e.flags,"include"),exclude:wC(e.flags,"exclude"),maxDepth:Ex(e.flags,"max-depth",{min:0}),maxFiles:Ex(e.flags,"max-files"),extensions:P4(e.flags),respectGitignore:!kC(e.flags,"no-gitignore"),followSymlinks:kC(e.flags,"follow-symlinks"),perFileDeny:m=>{try{return mo(m,u,process.platform==="win32",s).denied}catch{return!1}}}),d=l.capped?` (cap reached at ${l.filesIndexed} files)`:"",p=l.denied>0?`; ${l.denied} denied`:"",h=l.failed>0?`; ${l.failed} failed`:"";console.log(`Indexed ${l.filesIndexed} files (${l.totalChunks} sections) from ${r}${d}${p}${h}`)}else{let u=a.index({path:r,source:i});console.log(`Indexed ${u.totalChunks} sections (${u.codeChunks} with code) from ${r}`)}return console.log(`Source: ${i}`),console.log(`Project: ${s}`),console.log(`DB: ${c}`),0}finally{a.close()}}catch(e){let n=e instanceof Error?e.message:String(e);return console.error(`context-mode index: ${n}`),1}}async function I4(t){try{let e=CC(t),n=e.positional.join(" ").trim();if(!n||n==="-h"||n==="--help")return console.log("Usage: context-mode search <query...> [--source label] [--project path] [--limit n] [--type code|prose]"),n?0:1;let r=OC(Gr(e.flags,"project"),process.cwd()),{store:o,dbPath:s}=await IC(r);try{let i=Ex(e.flags,"limit")??3,a=Gr(e.flags,"type");if(a&&a!=="code"&&a!=="prose")throw new Error("--type must be code or prose");let c=o.searchWithFallback(n,i,Gr(e.flags,"source"),a);if(c.length===0)return console.log(`No matches for: ${n}`),console.log(`Project: ${r}`),console.log(`DB: ${s}`),0;for(let[u,l]of c.entries()){let d=l.content.replace(/\s+/g," ").trim(),p=d.length>500?`${d.slice(0,500)}...`:d;console.log(`## ${u+1}. ${l.title}`),console.log(`Source: ${l.source}`),console.log(`Type: ${l.contentType}`),console.log(p),console.log("")}return 0}finally{o.close()}}catch(e){let n=e instanceof Error?e.message:String(e);return console.error(`context-mode search: ${n}`),1}}function wx(t){try{return Sr(t),O.success(k.default.green(`Storage ${t.kind}: PASS`)+k.default.dim(` \u2014 ${t.path} (${Pd(t)})`)),0}catch(e){if(e instanceof Kt)return O.error(k.default.red(`Storage ${t.kind}: FAIL`)+k.default.dim(` \u2014 ${cs(e)}`)),1;throw e}}async function A4(){process.stdout.isTTY&&console.clear();let t=Qe(),e=await Fi(t.platform);Vd(k.default.bgMagenta(k.default.white(" context-mode doctor "))),O.info(`Platform: ${k.default.cyan(e.name)}`+k.default.dim(` (${t.confidence} confidence \u2014 ${t.reason})`));let n=0;try{let y=br(()=>e.getSessionDir()),_=Yr(()=>y.path),x=as(()=>y.path);_c([`sessions: ${y.path} (${Pd(y)})`,`content: ${_.path} (${Pd(_)})`,`stats: ${x.path} (${Pd(x)})`].join(`
|
|
1186
|
+
`),"Storage paths"),n+=wx(y),n+=wx(_),n+=wx(x)}catch(y){if(y instanceof Kt)n++,O.error(k.default.red(`Storage ${y.kind}: FAIL`)+k.default.dim(` \u2014 ${cs(y)}`));else throw y}let r=Wd();r.start("Running diagnostics");let o,s;try{o=Xr(),s=Ei(o)}catch{return r.stop("Diagnostics partial"),O.warn(k.default.yellow("Could not detect runtimes")+k.default.dim(" \u2014 module may be missing, restart session after upgrade")),yc(k.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}r.stop("Diagnostics complete"),_c(wi(o),"Runtimes");{let{hasModernSqlite:y}=await Promise.resolve().then(()=>(yr(),sp));process.platform==="linux"&&!y()&&!hr()&&(n++,O.error(k.default.red("Node version: FAIL")+` \u2014 Linux + Node ${process.versions.node} is unsafe (SIGSEGV)`+k.default.dim(`
|
|
1182
1187
|
context-mode requires Node.js >= 22.5 (or Bun) on Linux to avoid the
|
|
1183
1188
|
V8 madvise(MADV_DONTNEED) SIGSEGV in better-sqlite3 (1-4/hour).
|
|
1184
1189
|
Refs: https://github.com/nodejs/node/issues/62515
|
|
1185
1190
|
https://github.com/mksglu/context-mode/issues/564
|
|
1186
1191
|
Fix: nvm install 22.5 && nvm use 22.5 && npm install -g context-mode
|
|
1187
|
-
Or: curl -fsSL https://bun.sh/install | bash && bun add -g context-mode`)))}
|
|
1188
|
-
Run: ${y.fix}`):"")):
|
|
1189
|
-
Run: ${y.fix}`):""));
|
|
1192
|
+
Or: curl -fsSL https://bun.sh/install | bash && bun add -g context-mode`)))}hr()?O.success(k.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):O.warn(k.default.yellow("Performance: NORMAL")+" \u2014 Using Node.js (install Bun for 3-5x speed boost)");let i=11,a=(s.length/i*100).toFixed(0);s.length<2?(n++,O.error(k.default.red(`Language coverage: ${s.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+k.default.dim(` \u2014 ${s.join(", ")||"none"}`))):O.info(`Language coverage: ${s.length}/${i} (${a}%)`+k.default.dim(` \u2014 ${s.join(", ")}`)),O.step("Testing server initialization...");try{let{PolyglotExecutor:y}=await Promise.resolve().then(()=>(J_(),RP)),x=await new y({runtimes:o}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(x.exitCode===0&&x.stdout.trim()==="ok")O.success(k.default.green("Server test: PASS"));else{n++;let S=x.stderr?.trim()?` (${x.stderr.trim().slice(0,200)})`:"";O.error(k.default.red("Server test: FAIL")+` \u2014 exit ${x.exitCode}${S}`)}}catch(y){let _=y instanceof Error?y.message:String(y);_.includes("Cannot find module")||_.includes("MODULE_NOT_FOUND")?O.warn(k.default.yellow("Server test: SKIP")+k.default.dim(" \u2014 module not available (restart session after upgrade)")):(n++,O.error(k.default.red("Server test: FAIL")+` \u2014 ${_}`))}O.step(`Checking ${e.name} hooks configuration...`);let c=_i(),u=e.validateHooks(c);for(let y of u)y.status==="pass"?O.success(k.default.green(`${y.check}: PASS`)+` \u2014 ${y.message}`):y.status==="warn"?O.warn(k.default.yellow(`${y.check}: WARN`)+` \u2014 ${y.message}`+(y.fix?k.default.dim(`
|
|
1193
|
+
Run: ${y.fix}`):"")):O.error(k.default.red(`${y.check}: FAIL`)+` \u2014 ${y.message}`+(y.fix?k.default.dim(`
|
|
1194
|
+
Run: ${y.fix}`):""));O.step("Checking hook scripts...");let l=e.getHealthChecks?.(c)??[];if(l.length>0)for(let y of l){let _=y.check();_.status==="OK"?O.success(k.default.green(`${y.name}: PASS`)+(_.detail?k.default.dim(` \u2014 ${_.detail}`):"")):O.error(k.default.red(`${y.name}: FAIL`)+(_.detail?k.default.dim(` \u2014 ${_.detail}`):""))}else{let y=vc(e,c);if(y.length===0)O.success(k.default.green("Hook scripts: PASS")+k.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let _ of y){let x=Q(c,_);try{EC(x,$C.R_OK),O.success(k.default.green("Hook script exists: PASS")+k.default.dim(` \u2014 ${x}`))}catch{O.error(k.default.red("Hook script exists: FAIL")+k.default.dim(` \u2014 not found at ${x}`))}}}O.step(`Checking ${e.name} plugin registration...`);let d=e.checkPluginRegistration();d.status==="pass"?O.success(k.default.green("Plugin enabled: PASS")+k.default.dim(` \u2014 ${d.message}`)):O.warn(k.default.yellow("Plugin enabled: WARN")+` \u2014 ${d.message}`),O.step("Checking team-shared hook configs in your workspace...");{let E=function(b){return!!(b.startsWith("/")||/^[A-Za-z]:[/\\]/.test(b)||b.includes("\\\\")||b.includes("fnm_multishells")||b.includes("process.execPath"))},A=function(b,T){if(typeof b=="string")T(b);else if(Array.isArray(b))for(let P of b)A(P,T);else if(b&&typeof b=="object")for(let P of Object.values(b))A(P,T)};var f=E,g=A;let y=process.cwd(),_=[".github/hooks/context-mode.json",".cursor/hooks.json",".jetbrains/copilot/hooks.json"],x=0,S=0;for(let b of _){let T=Q(y,b);if(Ze(T)){S++;try{let P=JSON.parse(qn(T,"utf-8")),N=[];if(A(P,R=>{E(R)&&N.push(R)}),N.length>0){n++,x++;let R=N[0].length>100?N[0].slice(0,97)+"...":N[0];O.error(k.default.red("Hook config: FAIL")+` \u2014 ${b} has your machine's local paths baked in`+k.default.dim(`
|
|
1190
1195
|
This file is committed to git, so teammates and CI will get your path and the hooks will break for them.
|
|
1191
1196
|
Found ${N.length} hard-coded path(s), e.g.: ${R}
|
|
1192
1197
|
Fix: run /context-mode:ctx-upgrade \u2014 it rewrites the file to a portable form that works on every machine.
|
|
1193
|
-
Details: https://github.com/mksglu/context-mode/issues/613`))}else
|
|
1198
|
+
Details: https://github.com/mksglu/context-mode/issues/613`))}else O.success(k.default.green("Hook config: PASS")+k.default.dim(` \u2014 ${b} is portable (no hard-coded paths)`))}catch(P){let N=P instanceof Error?P.message:String(P);O.warn(k.default.yellow("Hook config: WARN")+` \u2014 ${b} is not valid JSON`+k.default.dim(`
|
|
1194
1199
|
Doctor cannot scan it for portability issues until the file parses.
|
|
1195
1200
|
Fix: open the file and check it in a JSON validator, or delete it and run /context-mode:ctx-upgrade to regenerate.
|
|
1196
|
-
Parser said: ${N.slice(0,160)}`))}}}
|
|
1201
|
+
Parser said: ${N.slice(0,160)}`))}}}S===0&&O.info(k.default.dim("Hook config: SKIP \u2014 no team-shared hook configs found in this workspace"))}O.step("Checking for leftover .mcp.json files from older versions...");{let y=lc(Cd(),".claude","plugins","cache","context-mode","context-mode");if(!Ze(y))O.info(k.default.dim("Leftover .mcp.json check: SKIP \u2014 no plugin cache exists yet (Claude Code has not installed context-mode here)"));else{let _=0,x=[];try{let S=u4(y);for(let E of S){let A=lc(y,E,".mcp.json");Ze(A)&&(_++,x.length<5&&x.push(E))}}catch(S){let E=S instanceof Error?S.message:String(S);O.warn(k.default.yellow("Leftover .mcp.json check: WARN")+" \u2014 could not read the plugin cache directory"+k.default.dim(`
|
|
1197
1202
|
Path: ${y}
|
|
1198
1203
|
Reason: ${E.slice(0,160)}
|
|
1199
|
-
Fix: check that the directory is readable, then re-run doctor. If the issue persists, run /context-mode:ctx-upgrade.`)),_=0}_===0?
|
|
1204
|
+
Fix: check that the directory is readable, then re-run doctor. If the issue persists, run /context-mode:ctx-upgrade.`)),_=0}_===0?O.success(k.default.green("Leftover .mcp.json check: PASS")+k.default.dim(" \u2014 no old .mcp.json files in the plugin cache")):O.warn(k.default.yellow("Leftover .mcp.json check: WARN")+` \u2014 found ${_} old .mcp.json file(s) left over from previous context-mode versions`+k.default.dim(`
|
|
1200
1205
|
These are harmless but should be cleaned up so they cannot confuse Claude Code after an auto-update.
|
|
1201
1206
|
Versions affected: ${x.join(", ")}${_>x.length?", ...":""}
|
|
1202
1207
|
Fix: run /context-mode:ctx-upgrade \u2014 it sweeps these files automatically on the next run.
|
|
1203
|
-
Details: https://github.com/mksglu/context-mode/issues/609`))}}
|
|
1204
|
-
Path: ${
|
|
1208
|
+
Details: https://github.com/mksglu/context-mode/issues/609`))}}O.step("Checking FTS5 / SQLite...");try{let y=(await Promise.resolve().then(()=>(yr(),sp))).loadDatabase(),_=new y(":memory:");_.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),_.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let x=_.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();_.close(),x&&x.content==="hello world"?O.success(k.default.green("FTS5 / SQLite: PASS")+" \u2014 native module works"):(n++,O.error(k.default.red("FTS5 / SQLite: FAIL")+" \u2014 query returned unexpected result"))}catch(y){let _=y instanceof Error?y.message:String(y),x=_i(),S=Q(x,"node_modules","better-sqlite3");!Ze(S)?(n++,O.error(k.default.red("FTS5 / better-sqlite3: FAIL")+k.default.dim(" \u2014 package-missing")+k.default.dim(`
|
|
1209
|
+
Path: ${S}
|
|
1205
1210
|
Root cause: npm silently skipped better-sqlite3 because the package's \`engines\` field excluded the running Node (issue #514, e.g. Node 26 vs better-sqlite3@12.x).
|
|
1206
1211
|
Try (primary): cd "${x}" && npm install better-sqlite3 --no-optional
|
|
1207
|
-
Try (fallback): /context-mode:ctx-upgrade`))):_.includes("Cannot find module")||_.includes("MODULE_NOT_FOUND")?
|
|
1212
|
+
Try (fallback): /context-mode:ctx-upgrade`))):_.includes("Cannot find module")||_.includes("MODULE_NOT_FOUND")?O.warn(k.default.yellow("FTS5 / better-sqlite3: SKIP")+k.default.dim(" \u2014 module not available (restart session after upgrade)")):(n++,(/Could not locate the bindings file/i.test(_)||/bindings\.node/i.test(_)||/\bbindings\b/i.test(_))&&process.platform==="win32"?O.error(k.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${_}`+k.default.dim(`
|
|
1208
1213
|
Root cause: prebuild-install was likely not on PATH, so install fell through to node-gyp without an MSVC toolchain (Windows).
|
|
1209
1214
|
Try (primary): npm install better-sqlite3 # re-resolves the dep tree and re-links the prebuild-install bin shim to fetch a prebuilt binary
|
|
1210
|
-
Try (fallback): npm rebuild better-sqlite3`)):
|
|
1211
|
-
Try: npm rebuild better-sqlite3`)))}
|
|
1212
|
-
Run: /context-mode:ctx-upgrade`)),m==="standalone"?
|
|
1213
|
-
Run: /context-mode:ctx-upgrade`)):
|
|
1215
|
+
Try (fallback): npm rebuild better-sqlite3`)):O.error(k.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${_}`+k.default.dim(`
|
|
1216
|
+
Try: npm rebuild better-sqlite3`)))}O.step("Checking versions...");let p=RC(),h=await $4(),m=e.getInstalledVersion();return h==="unknown"?O.warn(k.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, could not reach npm registry`):p===h?O.success(k.default.green("npm (MCP): PASS")+` \u2014 v${p}`):O.warn(k.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, latest v${h}`+k.default.dim(`
|
|
1217
|
+
Run: /context-mode:ctx-upgrade`)),m==="standalone"?O.info(k.default.dim(`${e.name}: standalone MCP mode`)+" \u2014 no platform plugin version to compare"):m==="not installed"?O.info(k.default.dim(`${e.name}: not installed`)+" \u2014 using standalone MCP mode"):h!=="unknown"&&m===h?O.success(k.default.green(`${e.name}: PASS`)+` \u2014 v${m}`):h!=="unknown"?O.warn(k.default.yellow(`${e.name}: WARN`)+` \u2014 v${m}, latest v${h}`+k.default.dim(`
|
|
1218
|
+
Run: /context-mode:ctx-upgrade`)):O.info(`${e.name}: v${m}`+k.default.dim(" \u2014 could not verify against npm registry")),n>0?(yc(k.default.red(`Diagnostics failed \u2014 ${n} critical issue(s) found`)),1):(yc(s.length>=4?k.default.green("Diagnostics complete!"):k.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function N4(){let t="https://context-mode.com/insight";console.log(`
|
|
1214
1219
|
context-mode Insight
|
|
1215
|
-
${
|
|
1216
|
-
`);let
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
Try
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
Try (primary): cd "${n}" && npm install better-sqlite3 --no-optional`)+w.default.dim(`
|
|
1224
|
-
Try (fallback): /context-mode:ctx-doctor`))),s.start("Updating npm global package");try{ld(["install","-g",n,"--no-audit","--no-fund"],{stdio:"pipe",timeout:3e4}),s.stop(w.default.green("npm global updated")),o.push("Updated npm global package")}catch{s.stop(w.default.yellow("npm global update skipped")),I.info(w.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}}_i(c,{recursive:!0,force:!0});try{let b=qe(),k=Q(b,"plugins","installed_plugins.json");if($e(k)){let P=Q(b,"plugins","cache"),N;try{N=pd(P)}catch{N=P}let R=N+Kr,F=JSON.parse(Wr(k,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(F))for(let K of F){let ge=K?.installPath;if(typeof ge!="string"||!ge||ge===n)continue;let We=Q(ge);if(!(We+Kr).startsWith(R)||!$e(We))continue;let _t;try{_t=pd(We)}catch{continue}if(!(_t+Kr).startsWith(R))continue;let Pr=Q(p,"skills");$e(Pr)&&(kR(Pr,Q(_t,"skills"),{recursive:!0}),o.push("Synced skills to active install path"))}}}catch{}o.push(`Updated v${a} \u2192 v${m}`),I.success(w.default.green("Plugin reinstalled from GitHub!")+w.default.dim(` \u2014 v${m}`))}}catch(p){let h=p instanceof Error?p.message:String(p);s.stop(w.default.red("Update failed")),I.error(w.default.red("GitHub pull failed")+` \u2014 ${h}`),process.exitCode=1,I.warn(w.default.yellow("In-place files were NOT updated")+w.default.dim(" \u2014 old version is still on disk; hooks/settings will still be refreshed.")),I.info(w.default.dim(" Recovery: re-run /ctx-upgrade once network is stable, or run /context-mode:ctx-doctor for a full health check."));try{_i(c,{recursive:!0,force:!0})}catch{}}I.step(`Backing up ${r.name} settings...`);let u=r.backupSettings();u?.endsWith(".bak")?(I.success(w.default.green("Backup created")+w.default.dim(" -> "+u)),o.push("Backed up settings")):u?I.success(w.default.green("Backup skipped")+w.default.dim(" \u2014 no changes needed")):I.warn(w.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),I.step(`Configuring ${r.name} hooks...`);try{let p=r.configureAllHooks(n);for(let h of p)I.info(w.default.dim(` ${h}`)),o.push(h);I.success(w.default.green("Hooks configured")+w.default.dim(` \u2014 ${r.name}`))}catch(p){let h=p instanceof Error?p.message:String(p);throw new Error(`Hook configuration failed: ${h}`)}I.step("Setting hook script permissions...");let l=r.setHookPermissions(n);if(process.platform!=="win32")for(let p of["build/cli.js","cli.bundle.mjs"]){let h=Q(n,p);try{$R(h,PR.F_OK),FZ(h,493),l.push(h)}catch{}}l.length>0?(I.success(w.default.green("Permissions set")+w.default.dim(` \u2014 ${l.length} hook script(s)`)),o.push(`Set ${l.length} hook scripts as executable`)):I.error(w.default.red("No hook scripts found")+w.default.dim(" \u2014 expected in "+Q(n,"hooks"))),o.length>0?mc(o.map(p=>w.default.green(" + ")+p).join(`
|
|
1225
|
-
`),"Changes Applied"):I.info(w.default.dim("No changes were needed."));let d=r.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";I.warn(w.default.yellow("Restart for new MCP tools to take effect.")+w.default.dim(` (${d})`)),I.step("Running doctor to verify..."),console.log();try{let p=Q(n,"cli.bundle.mjs"),h=Q(n,"build","cli.js"),m=$e(p)?p:h;yi("node",[m,"doctor"],{stdio:"inherit",timeout:3e4,cwd:n,env:{...process.env,CONTEXT_MODE_PLATFORM:e.platform}})}catch{I.warn(w.default.yellow("Doctor had warnings")+w.default.dim(` \u2014 restart your ${r.name} session to pick up the new version`))}}function dq(){let t=qe(),e=[Q(Go(),"bin","statusline.mjs"),Q(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let n=Q(t,"plugins","installed_plugins.json");if($e(n)){let o=Q(t,"plugins","cache"),s;try{s=pd(o)}catch{s=o}let i=s+Kr,c=JSON.parse(Wr(n,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(c))for(let u of c){let l=u?.installPath;if(typeof l!="string"||!l)continue;let d=Q(l);if(!(d+Kr).startsWith(i))continue;let p;try{p=pd(d)}catch{continue}(p+Kr).startsWith(i)&&e.push(Q(p,"bin","statusline.mjs"))}}}catch{}let r=e.find(n=>$e(n));r||process.exit(0),import(fd(r).href).catch(()=>{process.exit(0)})}export{YZ as npmExec,ld as npmExecFile,QZ as openInBrowser,bY as toUnixPath};
|
|
1220
|
+
${t}
|
|
1221
|
+
`),w4(t)}async function D4(t){process.stdout.isTTY&&console.clear();let e=t?.platform?{platform:t.platform,confidence:"high",reason:`--platform ${t.platform} from ctx_upgrade handler`}:Qe(),n=await Fi(e.platform);Vd(k.default.bgCyan(k.default.black(" context-mode upgrade "))),O.info(`Platform: ${k.default.cyan(n.name)}`+k.default.dim(` (${e.confidence} confidence)`));let r=_i(),o=[],s=Wd(),i=Q(Be(),"plugins","marketplaces","context-mode");if(Ze(lc(i,".git"))){s.start("Syncing marketplace clone");try{yi("git",["-C",i,"status","--porcelain"],{stdio:"pipe",encoding:"utf-8",timeout:5e3}).trim()?(s.stop(k.default.yellow("Marketplace clone has local edits \u2014 skipping git pull")),O.info(k.default.dim(` Run manually: git -C "${i}" stash && git pull --ff-only`))):(yi("git",["-C",i,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),yi("git",["-C",i,"reset","--hard","origin/HEAD"],{stdio:"pipe",timeout:1e4}),s.stop(k.default.green("Marketplace clone synced")),o.push("Marketplace clone updated to upstream"))}catch(p){let h=p instanceof Error?p.message:String(p);s.stop(k.default.yellow("Marketplace sync skipped")),O.warn(k.default.yellow("git refresh on marketplace failed")+` \u2014 ${h}`),O.info(k.default.dim(" Continuing \u2014 cache dir update will still happen."))}}O.step("Pulling latest from GitHub...");let a=RC(),c=lc(y4(),`context-mode-upgrade-${Date.now()}`);s.start("Cloning mksglu/context-mode");try{yi("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",c],{stdio:"pipe",timeout:3e4}),s.stop("Downloaded");let p=c,m=JSON.parse(qn(Q(p,"package.json"),"utf-8")).version??"unknown";if(m===a)O.success(k.default.green("Already on latest")+` \u2014 v${a}`),Td(c,{recursive:!0,force:!0});else{O.info(`Update available: ${k.default.yellow("v"+a)} \u2192 ${k.default.green("v"+m)}`);try{let b=Fv({ownPid:process.pid,ownPpid:process.ppid});if(b.length>0){let T=await Hv({pids:b});if(T.totalKilled>0){let P=T.totalKilled===1?"sibling MCP server":"sibling MCP servers";O.info(k.default.dim(`Stopped ${T.totalKilled} ${P} (SIGTERM: ${T.terminatedBySigterm}, SIGKILL: ${T.terminatedBySigkill})`))}}}catch{}s.start("Installing dependencies & building");let f=Bv();$d(["install","--no-audit","--no-fund"],{cwd:p,stdio:"pipe",timeout:12e4,...f?{env:{...process.env,npm_config_msvs_version:f}}:{}}),$d(["run","build"],{cwd:p,stdio:"pipe",timeout:6e4}),s.stop("Built successfully"),s.start("Updating files in-place");let y=[...JSON.parse(qn(Q(p,"package.json"),"utf-8")).files||[],"src","package.json"],_=Q(r)+Vn,x=Q(p)+Vn,S=b=>{try{return!m4(b).isSymbolicLink()}catch{return!1}};for(let b of y){let T=Q(p,b),P=Q(r,b);if((P+Vn).startsWith(_)&&(T+Vn).startsWith(x)&&S(T)&&Ze(T))try{Td(P,{recursive:!0,force:!0}),vC(T,P,{recursive:!0,filter:S})}catch{}}try{let b;try{let{resolveHookRuntime:P}=await Promise.resolve().then(()=>(Yo(),tb)),N=P();N.isBun&&(b=N.path)}catch{}(await Promise.resolve().then(()=>(pC(),dC))).normalizeHooksJsonOnly({pluginRoot:r,nodePath:process.execPath,jsRuntimePath:b,platform:process.platform})}catch{}try{if(e.platform==="claude-code"){let{rewriteShellSnapshots:b}=await Promise.resolve().then(()=>(SC(),bC)),T=Q(Be(),"shell-snapshots"),P=b({snapshotsDir:T,currentVersion:m});P.rewritten.length>0&&O.info(k.default.dim(` Healed ${P.rewritten.length} stale shell snapshot(s) \u2014 Bash tool calls in the active session will pick up v${m} immediately`))}}catch{}s.stop(k.default.green(`Updated in-place to v${m}`));let E=Q(r,".claude-plugin","plugin.json"),A=null;try{let b=JSON.parse(qn(E,"utf-8"));b&&typeof b.version=="string"&&(A=b.version)}catch{}if(A!==m)throw new Error(`pluginRoot manifest version mismatch \u2014 disk says "${A??"<missing>"}" but newVersion is "${m}". Refusing to bump registry.`);n.updatePluginRegistry(r,m),O.info(k.default.dim(" Registry synced to "+r));try{let b=Q(Be(),"plugins","installed_plugins.json");if(Ze(b)){let P=JSON.parse(qn(b,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(P))for(let N of P){let R=N?.installPath;if(typeof R!="string"||!R)continue;if(!Ze(R))throw new Error(`installPath does not exist on disk: ${R}`);let C=Q(R,".claude-plugin","plugin.json");if(!Ze(C))throw new Error(`missing plugin.json manifest at ${C}`);let F=JSON.parse(qn(C,"utf-8"));if(F?.version!==N.version)throw new Error(`version mismatch \u2014 registry says "${N.version}" but ${C} says "${F?.version}"`)}}}catch(b){let T=b instanceof Error?b.message:String(b);throw new Error(`Registry consistency check failed: ${T}`)}try{let b=Q(Be(),"plugins","cache"),T="context-mode@context-mode",P=Qc({pluginRoot:r,pluginCacheRoot:b,pluginKey:T});if(P&&P.error)throw new Error(P.error);let N=Qc({pluginRoot:r,pluginCacheRoot:b,pluginKey:T});if(N&&Array.isArray(N.healed)&&N.healed.length>0)throw new Error(`Plugin manifest drift: plugin.json mcpServers.args still poisoned after first heal pass (healed=${N.healed.join(",")})`)}catch(b){let T=b instanceof Error?b.message:String(b);throw new Error(`plugin.json drift check failed: ${T}`)}try{let b=Q(Be(),"plugins","cache"),T="context-mode@context-mode",P=eu({pluginCacheRoot:b,pluginKey:T});P&&P.removed&&P.removed.length>0&&O.info(k.default.dim(` Swept ${P.removed.length} stale .mcp.json file(s) from cache`));let N=eu({pluginCacheRoot:b,pluginKey:T});if(N&&Array.isArray(N.removed)&&N.removed.length>0)throw new Error(`.mcp.json sweep drift: ${N.removed.length} file(s) still present after first pass`)}catch(b){let T=b instanceof Error?b.message:String(b);throw new Error(`.mcp.json sweep check failed: ${T}`)}try{let{healClaudeJsonMcpArgs:b}=await Promise.resolve().then(()=>(Pm(),Uv)),T=Q(Cd(),".claude.json"),P=Q(Be(),"plugins","cache","context-mode","context-mode"),N=b({dotClaudeJsonPath:T,pluginCacheParent:P,newPluginRoot:r});N.healed&&N.healed.length>0&&O.info(k.default.dim(" ~/.claude.json user MCP registrations updated \u2192 "+m))}catch{}try{let b=Q(i,".claude-plugin","plugin.json");if(Ze(b)){let T=JSON.parse(qn(b,"utf-8"));T?.version!==m&&(O.warn(k.default.yellow("Marketplace clone version mismatch")+` \u2014 ${i} reports "${T?.version}" but expected "${m}"`),O.info(k.default.dim(` Run manually: git -C "${i}" fetch --tags origin && git -C "${i}" reset --hard origin/HEAD`)))}}catch{}if(s.start("Installing production dependencies"),$d(["install","--production","--no-audit","--no-fund"],{cwd:r,stdio:"pipe",timeout:6e4}),s.stop("Dependencies ready"),!Jr(e.platform)){s.start("Verifying native addon ABI");let b=Q(r,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let P=Q(r,"hooks","ensure-deps.mjs");if(!Ze(P))throw new Error(`missing ${P}`);await import(`${Od(P).href}?upgrade=${Date.now()}`),Ze(b)?(s.stop(k.default.green("Native addons OK")+k.default.dim(" \u2014 ABI cache present")),o.push(`better-sqlite3 ABI ${process.versions.modules} cache ready`)):(s.stop(k.default.yellow("Native addon ABI cache missing")),O.warn(k.default.dim(` Try manually: cd "${r}" && npm rebuild better-sqlite3`)))}catch(P){let N=P instanceof Error?P.message:String(P);s.stop(k.default.yellow("Native addon ABI bootstrap unavailable")),O.warn(k.default.yellow("better-sqlite3 ABI repair did not run")+` \u2014 ${N}`+k.default.dim(`
|
|
1222
|
+
Try manually: cd "${r}" && npm rebuild better-sqlite3`))}let T=Q(r,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!Ze(T))try{let P=Q(r,"scripts","heal-better-sqlite3.mjs");if(Ze(P)){let N=await import(`${Od(P).href}?upgrade=${Date.now()}`);typeof N.healBetterSqlite3Binding=="function"&&N.healBetterSqlite3Binding(r)}}catch{}Ze(T)||(process.exitCode=1,O.error(k.default.red("better-sqlite3 native binding: MISSING")+k.default.dim(`
|
|
1223
|
+
Path: ${T}`)+k.default.dim(`
|
|
1224
|
+
Cause: npm silently skipped the package (Node engine mismatch, issue #514)`)+k.default.dim(`
|
|
1225
|
+
Try (primary): cd "${r}" && npm install better-sqlite3 --no-optional`)+k.default.dim(`
|
|
1226
|
+
Try (fallback): /context-mode:ctx-doctor`))),s.start("Updating npm global package");try{$d(["install","-g",r,"--no-audit","--no-fund"],{stdio:"pipe",timeout:3e4}),s.stop(k.default.green("npm global updated")),o.push("Updated npm global package")}catch{s.stop(k.default.yellow("npm global update skipped")),O.info(k.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}}Td(c,{recursive:!0,force:!0});try{let b=Be(),T=Q(b,"plugins","installed_plugins.json");if(Ze(T)){let P=Q(b,"plugins","cache"),N;try{N=Rd(P)}catch{N=P}let R=N+Vn,F=JSON.parse(qn(T,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(F))for(let W of F){let ge=W?.installPath;if(typeof ge!="string"||!ge||ge===r)continue;let Le=Q(ge);if(!(Le+Vn).startsWith(R)||!Ze(Le))continue;let st;try{st=Rd(Le)}catch{continue}if(!(st+Vn).startsWith(R))continue;let $n=Q(p,"skills");Ze($n)&&(vC($n,Q(st,"skills"),{recursive:!0}),o.push("Synced skills to active install path"))}}}catch{}o.push(`Updated v${a} \u2192 v${m}`),O.success(k.default.green("Plugin reinstalled from GitHub!")+k.default.dim(` \u2014 v${m}`))}}catch(p){let h=p instanceof Error?p.message:String(p);s.stop(k.default.red("Update failed")),O.error(k.default.red("GitHub pull failed")+` \u2014 ${h}`),process.exitCode=1,O.warn(k.default.yellow("In-place files were NOT updated")+k.default.dim(" \u2014 old version is still on disk; hooks/settings will still be refreshed.")),O.info(k.default.dim(" Recovery: re-run /ctx-upgrade once network is stable, or run /context-mode:ctx-doctor for a full health check."));try{Td(c,{recursive:!0,force:!0})}catch{}}O.step(`Backing up ${n.name} settings...`);let u=n.backupSettings();u?.endsWith(".bak")?(O.success(k.default.green("Backup created")+k.default.dim(" -> "+u)),o.push("Backed up settings")):u?O.success(k.default.green("Backup skipped")+k.default.dim(" \u2014 no changes needed")):O.warn(k.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),O.step(`Configuring ${n.name} hooks...`);try{let p=n.configureAllHooks(r);for(let h of p)O.info(k.default.dim(` ${h}`)),o.push(h);O.success(k.default.green("Hooks configured")+k.default.dim(` \u2014 ${n.name}`))}catch(p){let h=p instanceof Error?p.message:String(p);throw new Error(`Hook configuration failed: ${h}`)}O.step("Setting hook script permissions...");let l=n.setHookPermissions(r);if(process.platform!=="win32")for(let p of["build/cli.js","cli.bundle.mjs"]){let h=Q(r,p);try{EC(h,$C.F_OK),p4(h,493),l.push(h)}catch{}}l.length>0?(O.success(k.default.green("Permissions set")+k.default.dim(` \u2014 ${l.length} hook script(s)`)),o.push(`Set ${l.length} hook scripts as executable`)):O.error(k.default.red("No hook scripts found")+k.default.dim(" \u2014 expected in "+Q(r,"hooks"))),o.length>0?_c(o.map(p=>k.default.green(" + ")+p).join(`
|
|
1227
|
+
`),"Changes Applied"):O.info(k.default.dim("No changes were needed."));let d=n.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";O.warn(k.default.yellow("Restart for new MCP tools to take effect.")+k.default.dim(` (${d})`)),O.step("Running doctor to verify..."),console.log();try{let p=Q(r,"cli.bundle.mjs"),h=Q(r,"build","cli.js"),m=Ze(p)?p:h;yi("node",[m,"doctor"],{stdio:"inherit",timeout:3e4,cwd:r,env:{...process.env,CONTEXT_MODE_PLATFORM:e.platform}})}catch{O.warn(k.default.yellow("Doctor had warnings")+k.default.dim(` \u2014 restart your ${n.name} session to pick up the new version`))}}function M4(){let t=Be(),e=[Q(_i(),"bin","statusline.mjs"),Q(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let r=Q(t,"plugins","installed_plugins.json");if(Ze(r)){let o=Q(t,"plugins","cache"),s;try{s=Rd(o)}catch{s=o}let i=s+Vn,c=JSON.parse(qn(r,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(c))for(let u of c){let l=u?.installPath;if(typeof l!="string"||!l)continue;let d=Q(l);if(!(d+Vn).startsWith(i))continue;let p;try{p=Rd(d)}catch{continue}(p+Vn).startsWith(i)&&e.push(Q(p,"bin","statusline.mjs"))}}}catch{}let n=e.find(r=>Ze(r));n||process.exit(0),import(Od(n).href).catch(()=>{process.exit(0)})}export{fQ as npmExec,$d as npmExecFile,w4 as openInBrowser,mQ as toUnixPath};
|