context-mode 1.0.117 → 1.0.119
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/.openclaw-plugin/openclaw.plugin.json +1 -1
- package/.openclaw-plugin/package.json +1 -1
- package/bin/statusline.mjs +43 -36
- package/build/adapters/pi/mcp-bridge.d.ts +28 -3
- package/build/adapters/pi/mcp-bridge.js +127 -14
- package/build/adapters/qwen-code/index.js +6 -2
- package/build/cli.js +93 -5
- package/build/opencode-plugin.js +2 -5
- package/build/server.js +25 -8
- package/build/session/analytics.d.ts +21 -0
- package/build/session/analytics.js +1 -1
- package/build/util/project-dir.js +9 -5
- package/cli.bundle.mjs +148 -139
- package/hooks/core/routing.mjs +13 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +5 -6
- package/scripts/heal-better-sqlite3.mjs +53 -6
- package/scripts/heal-installed-plugins.mjs +104 -0
- package/scripts/postinstall.mjs +35 -1
- package/server.bundle.mjs +88 -88
- package/skills/UPSTREAM-CREDITS.md +51 -0
- package/skills/diagnose/SKILL.md +122 -0
- package/skills/diagnose/scripts/hitl-loop.template.sh +41 -0
- package/skills/grill-me/SKILL.md +15 -0
- package/skills/grill-with-docs/ADR-FORMAT.md +47 -0
- package/skills/grill-with-docs/CONTEXT-FORMAT.md +77 -0
- package/skills/grill-with-docs/SKILL.md +93 -0
- package/skills/improve-codebase-architecture/DEEPENING.md +37 -0
- package/skills/improve-codebase-architecture/INTERFACE-DESIGN.md +44 -0
- package/skills/improve-codebase-architecture/LANGUAGE.md +53 -0
- package/skills/improve-codebase-architecture/SKILL.md +76 -0
- package/skills/tdd/SKILL.md +114 -0
- package/skills/tdd/deep-modules.md +33 -0
- package/skills/tdd/interface-design.md +31 -0
- package/skills/tdd/mocking.md +59 -0
- package/skills/tdd/refactoring.md +10 -0
- package/skills/tdd/tests.md +61 -0
- package/start.mjs +25 -1
- package/build/cache-heal.d.ts +0 -48
- package/build/cache-heal.js +0 -150
- package/build/routing-block.d.ts +0 -8
- package/build/routing-block.js +0 -86
- package/build/tool-naming.d.ts +0 -4
- package/build/tool-naming.js +0 -24
package/cli.bundle.mjs
CHANGED
|
@@ -1,77 +1,77 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}function fa(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"),e}function
|
|
4
|
-
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),r;let s=n.hooks,o=this.readPluginHooks(e),i=this.checkHookType(s,o,
|
|
5
|
-
`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function
|
|
6
|
-
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let s=n.hooks,o=s?.[$e.BEFORE_TOOL];if(o&&o.length>0){let a=o.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.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 r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=s?.[$e.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.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 r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(s=>typeof s=="string"&&s.includes("context-mode")):Object.keys(r).some(s=>s.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=
|
|
7
|
-
`,"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}`}}});var
|
|
8
|
-
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r;let s=this.hasContextModePlugin(n);return Array.isArray(n.plugin)?r.push({check:"Plugin registration",status:s?"pass":"fail",message:s?"context-mode found in plugin array":"context-mode not found in plugin array",fix:s?void 0:"context-mode upgrade"}):r.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),r}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=
|
|
9
|
-
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),r;let s=n.plugins,o=s?.entries;if(o){let a=Object.keys(o).some(c=>c.includes("context-mode"));if(r.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=o["context-mode"]?.enabled!==!1;r.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else r.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return s?.slots?.contextEngine==="context-mode"?r.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):r.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let n=e.plugins?.entries;return n&&Object.keys(n).some(o=>o.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=
|
|
10
|
-
`):null}function
|
|
2
|
+
var j$=Object.create;var il=Object.defineProperty;var z$=Object.getOwnPropertyDescriptor;var L$=Object.getOwnPropertyNames;var F$=Object.getPrototypeOf,U$=Object.prototype.hasOwnProperty;var v=(t,e)=>()=>(t&&(e=t(t=0)),e);var D=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Fe=(t,e)=>{for(var r in e)il(t,r,{get:e[r],enumerable:!0})},H$=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of L$(e))!U$.call(t,s)&&s!==r&&il(t,s,{get:()=>e[s],enumerable:!(n=z$(e,s))||n.enumerable});return t};var $o=(t,e,r)=>(r=t!=null?j$(F$(t)):{},H$(e||!t||!t.__esModule?il(r,"default",{value:t,enumerable:!0}):r,t));var ml=D((P2,qy)=>{"use strict";var pl={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let r="";return t<0?r+=`\x1B[${-t}D`:t>0&&(r+=`\x1B[${t}C`),e<0?r+=`\x1B[${-e}A`:e>0&&(r+=`\x1B[${e}B`),r},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"},X$={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},Q$={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 r=0;r<t;r++)e+=this.line+(r<t-1?pl.up():"");return t&&(e+=pl.left),e}};qy.exports={cursor:pl,scroll:X$,erase:Q$,beep:"\x07"}});var Xy=D((lU,vl)=>{var da=process||{},Jy=da.argv||[],la=da.env||{},wT=!(la.NO_COLOR||Jy.includes("--no-color"))&&(!!la.FORCE_COLOR||Jy.includes("--color")||da.platform==="win32"||(da.stdout||{}).isTTY&&la.TERM!=="dumb"||!!la.CI),ET=(t,e,r=t)=>n=>{let s=""+n,o=s.indexOf(e,t.length);return~o?t+$T(s,e,r,o)+e:t+s+e},$T=(t,e,r,n)=>{let s="",o=0;do s+=t.substring(o,n)+r,o=n+e.length,n=t.indexOf(e,o);while(~n);return s+t.substring(o)},Yy=(t=wT)=>{let e=t?ET:()=>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")}};vl.exports=Yy();vl.exports.createColors=Yy});import{execFileSync as Qy,execSync as Sl}from"node:child_process";import{existsSync as pa}from"node:fs";function PT(t){let e=t.split(/[\\/]/),r=e[e.length-1];return TT.test(r)}function nt(t){try{let e=_s?`where ${t}`:`command -v ${t}`;return Sl(e,{stdio:"pipe"}),!0}catch{return!1}}function bl(t){if(_s)try{let r=Sl(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(s=>s.trim()).filter(Boolean);if(r.length===0||r.filter(s=>!/\\Microsoft\\WindowsApps\\/i.test(s)).length===0)return!1}catch{return!1}else if(!nt(t))return!1;try{return Qy(t,["--version"],{shell:_s,stdio:"pipe",timeout:_s?5e3:1500}),!0}catch{return!1}}function e_(){if(nt("bun"))return!0;for(let t of t_())if(pa(t))return!0;return!1}function RT(){for(let e of t_())if(pa(e))return e;if(nt("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return _s?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function t_(){let t=process.env.HOME??process.env.USERPROFILE??"";if(_s){let e=process.env.LOCALAPPDATA??"",r=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...r?[`${r}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function CT(){let t=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];for(let e of t)if(pa(e))return e;try{let r=Sl("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean);for(let n of r){let s=n.toLowerCase();if(!(s.includes("system32")||s.includes("windowsapps")))return n}return null}catch{return null}}function tr(t,e=["--version"]){try{return Qy(t,e,{encoding:"utf-8",shell:process.platform==="win32",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function xs(){let e=e_()?RT():null,r=process.env.SHELL,n=r&&pa(r)&&PT(r)?r:null,s=process.platform==="win32";return{javascript:e??process.execPath,typescript:e||(nt("tsx")?"tsx":nt("ts-node")?"ts-node":null),python:bl("python3")?"python3":bl("python")?"python":bl("py")?"py":null,shell:n??(s?CT()??(nt("sh")?"sh":nt("powershell")?"powershell":"cmd.exe"):nt("bash")?"bash":"sh"),ruby:nt("ruby")?"ruby":null,go:nt("go")?"go":null,rust:nt("rustc")?"rustc":null,php:nt("php")?"php":null,perl:nt("perl")?"perl":null,r:nt("Rscript")?"Rscript":nt("r")?"r":null,elixir:nt("elixir")?"elixir":null}}function vs(){return e_()}function ma(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return e.push(` JavaScript: ${t.javascript} (${tr(t.javascript)})${r?" \u26A1":""}`),t.typescript?e.push(` TypeScript: ${t.typescript} (${tr(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${tr(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${tr(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${tr(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${tr(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${tr(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${tr(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${tr(t.perl)})`),t.r&&e.push(` R: ${t.r} (${tr(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${tr(t.elixir)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
|
|
3
|
+
`)}function fa(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"),e}function r_(t,e,r){switch(e){case"javascript":return t.javascript.endsWith("bun")?[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 t.typescript?.endsWith("bun")?[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 s=t.shell.toLowerCase();if(s.includes("bash")||s.endsWith("/sh")||s.endsWith("\\sh.exe")){let o=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${o}'`]}if(s.includes("powershell")||s.includes("pwsh"))return[t.shell,"-File",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]}}var TT,_s,ha=v(()=>{"use strict";TT=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i;_s=process.platform==="win32"});function OT(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 s of n)if(s&&typeof s=="object"){let o=s.command;typeof o=="string"&&e.push(o)}}}return e}function IT(t){let e=t.match(/(?:"([^"]+\.mjs)"|'([^']+\.mjs)'|(\S+\.mjs))/);return e?.[1]??e?.[2]??e?.[3]??null}function ga(t,e){let r=new Set,n=t.generateHookConfig(e);for(let s of Object.values(n))if(Array.isArray(s))for(let o of s)for(let i of OT(o)){let a=IT(i);a&&r.add(a)}return[...r]}var kl=v(()=>{"use strict"});import{resolve as Ro}from"node:path";import{homedir as wl}from"node:os";import{createRequire as AT}from"node:module";function qe(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Ro(wl(),e.replace(/^~[/\\]?/,"")):Ro(e):Ro(wl(),".claude")}function NT(t=process.env){return Ro(qe(t),"settings.json")}function El(t=process.env){let e=[],r=null,n=null;try{let i=AT(import.meta.url)("../adapters/detect.js");r=i.detectPlatform(),n=i.getSessionDirSegments}catch{}if(r&&n&&r.platform!=="claude-code"){let o=n(r.platform);o&&o.length>0&&e.push(Ro(wl(),...o,"settings.json"))}let s=NT(t);return e.includes(s)||e.push(s),e}var Kr=v(()=>{"use strict"});var n_,s_=v(()=>{"use strict";n_={"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",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code"}});import{join as Pl}from"node:path";import{accessSync as UT,copyFileSync as HT,constants as ZT,mkdirSync as BT}from"node:fs";import{homedir as o_}from"node:os";var Se,Pt=v(()=>{"use strict";Se=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=Pl(o_(),...this.sessionDirSegments,"context-mode","sessions");return BT(e,{recursive:!0}),e}getConfigDir(e){return Pl(o_(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(){return Pl(this.getConfigDir(),"memory")}backupSettings(){let e=this.getSettingsPath();try{UT(e,ZT.R_OK);let r=e+".bak";return HT(e,r),r}catch{return null}}}});var bs,Rl=v(()=>{"use strict";Pt();bs=class extends Se{parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,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 r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),e.updatedOutput&&(r.updatedMCPToolOutput=e.updatedOutput),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});function Ue(t){let e=process.execPath.replace(/\\/g,"/"),r=t.replace(/\\/g,"/");return`"${e}" "${r}"`}var Jr=v(()=>{"use strict"});function Co(t,e){let r=Ss[e],n=Cl(e);return t.hooks?.some(s=>s.command?.includes(r)||s.command?.includes(n))??!1}function Cl(t,e){if(e){let r=Ss[t];return Ue(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function Ol(t){let e=t.match(/"[^"]+"\s+"([^"]+\.mjs)"/);return e?e[1]:t.match(/node\s+"?([^"]+\.mjs)"?/)?.[1]??null}function c_(t){let e=Object.values(Ss);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var rr,qT,i_,VT,OU,Ss,a_,IU,u_=v(()=>{"use strict";Jr();rr={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},qT=["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"],i_=qT.join("|"),VT=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],OU=VT.join("|"),Ss={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},a_=[rr.PRE_TOOL_USE,rr.SESSION_START],IU=[rr.POST_TOOL_USE,rr.PRE_COMPACT,rr.USER_PROMPT_SUBMIT]});var Al={};Fe(Al,{ClaudeCodeAdapter:()=>Il});import{readFileSync as ya,writeFileSync as l_,existsSync as WT,readdirSync as GT,chmodSync as KT,accessSync as JT,mkdirSync as YT,constants as XT}from"node:fs";import{resolve as _a,join as ks}from"node:path";import{homedir as d_}from"node:os";var Il,Nl=v(()=>{"use strict";Rl();Kr();u_();Il=class extends bs{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 qe()}getSessionDir(){let e=ks(this.getConfigDir(),"context-mode","sessions");return YT(e,{recursive:!0}),e}getSettingsPath(){return ks(this.getConfigDir(),"settings.json")}generateHookConfig(e){let r=`node ${e}/hooks/pretooluse.mjs`;return{PreToolUse:["Bash","WebFetch","Read","Grep","Task","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"].map(s=>({matcher:s,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/posttooluse.mjs`}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/precompact.mjs`}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/userpromptsubmit.mjs`}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/sessionstart.mjs`}]}]}}readSettings(){try{let e=ya(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){l_(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
4
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),r;let s=n.hooks,o=this.readPluginHooks(e),i=this.checkHookType(s,o,rr.PRE_TOOL_USE);r.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(s,o,rr.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}readPluginHooks(e){let r=[ks(e,"hooks","hooks.json"),ks(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let s=ya(n,"utf-8"),o=JSON.parse(s);if(o.hooks)return o.hooks}catch{}}checkHookType(e,r,n){let s=e?.[n];if(s&&s.length>0&&s.some(i=>Co(i,n)))return!0;let o=r?.[n];return!!(o&&o.length>0&&o.some(i=>Co(i,n)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let r=e.enabledPlugins;if(!r)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let n=Object.keys(r).find(s=>s.startsWith("context-mode"));return n&&r[n]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${n}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let r=ks(this.getConfigDir(),"plugins","installed_plugins.json"),s=JSON.parse(ya(r,"utf-8")).plugins??{};for(let[o,i]of Object.entries(s)){if(!o.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(),qe(),_a(d_(),".claude"),_a(d_(),".config","claude")]));for(let r of e){let n=_a(r,"plugins","cache","context-mode","context-mode");try{let o=GT(n).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let d=0;d<3;d++)if((c[d]??0)!==(u[d]??0))return(c[d]??0)-(u[d]??0);return 0});if(o.length>0)return o[o.length-1]}catch{}}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},s=[];for(let a of Object.keys(n)){let c=n[a];if(!Array.isArray(c))continue;let u=c.filter(l=>{let m=l;if(!c_(m))return!0;let f=m.hooks??[];return f.every(h=>!h.command||!Ol(h.command))?!0:f.every(h=>{let g=h.command?Ol(h.command):null;return g?WT(g):!0})}),d=c.length-u.length;d>0&&(n[a]=u,s.push(`Removed ${d} stale ${a} hook(s)`))}let o=this.readPluginHooks(e);if(o&&a_.every(c=>this.checkHookType(void 0,o,c))){let c=Object.values(Ss),u=d=>d!=null&&(c.some(l=>d.includes(l))||d.includes("context-mode hook"));for(let d of Object.keys(n)){let l=n[d];if(!Array.isArray(l))continue;let m=0;for(let p of l){let h=p,g=h.hooks??[],_=g.length;h.hooks=g.filter(x=>!u(x.command)),m+=_-h.hooks.length}let f=l.filter(p=>{let h=p.hooks;return Array.isArray(h)&&h.length>0});(m>0||f.length!==l.length)&&(n[d]=f,m>0&&s.push(`Removed ${m} duplicate ${d} hook(s) \u2014 covered by plugin hooks.json`))}return r.hooks=n,this.writeSettings(r),s.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),s}let i=[rr.PRE_TOOL_USE,rr.SESSION_START];for(let a of i){let c=Cl(a,e);if(a===rr.PRE_TOOL_USE){let u={matcher:i_,hooks:[{type:"command",command:c}]},d=n.PreToolUse;if(d&&Array.isArray(d)){let l=d.findIndex(m=>Co(m,a));l>=0?(d[l]=u,s.push(`Updated existing ${a} hook entry`)):(d.push(u),s.push(`Added ${a} hook entry`)),n.PreToolUse=d}else n.PreToolUse=[u],s.push(`Created ${a} hooks section`)}else{let u={matcher:"",hooks:[{type:"command",command:c}]},d=n[a];if(d&&Array.isArray(d)){let l=d.findIndex(m=>Co(m,a));l>=0?(d[l]=u,s.push(`Updated existing ${a} hook entry`)):(d.push(u),s.push(`Added ${a} hook entry`)),n[a]=d}else n[a]=[u],s.push(`Created ${a} hooks section`)}}return r.hooks=n,this.writeSettings(r),s}setHookPermissions(e){let r=[];for(let[,n]of Object.entries(Ss)){let s=_a(e,"hooks",n);try{JT(s,XT.R_OK),KT(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=ks(this.getConfigDir(),"plugins","installed_plugins.json"),s=JSON.parse(ya(n,"utf-8"));for(let[o,i]of Object.entries(s.plugins||{}))if(o.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=r,a.lastUpdated=new Date().toISOString();l_(n,JSON.stringify(s,null,2)+`
|
|
5
|
+
`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function kn(t,e){let r=Dl[t];return e&&r?Ue(`${e}/hooks/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var $e,Dl,UU,HU,p_=v(()=>{"use strict";Jr();$e={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},Dl={[$e.BEFORE_AGENT]:"beforeagent.mjs",[$e.BEFORE_TOOL]:"beforetool.mjs",[$e.AFTER_TOOL]:"aftertool.mjs",[$e.PRE_COMPRESS]:"precompress.mjs",[$e.SESSION_START]:"sessionstart.mjs"},UU=[$e.BEFORE_TOOL,$e.SESSION_START],HU=[$e.AFTER_TOOL,$e.PRE_COMPRESS]});var f_={};Fe(f_,{GeminiCLIAdapter:()=>jl});import{readFileSync as Ml,writeFileSync as m_,mkdirSync as QT,accessSync as eP,chmodSync as tP,constants as rP}from"node:fs";import{resolve as Oo,join as nP}from"node:path";import{homedir as xa}from"node:os";var jl,h_=v(()=>{"use strict";Pt();p_();jl=class extends Se{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 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,isError:r.is_error,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",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),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 Oo(xa(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[$e.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:kn($e.BEFORE_AGENT,e)}]}],[$e.BEFORE_TOOL]:[{matcher:"run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode",hooks:[{type:"command",command:kn($e.BEFORE_TOOL,e)}]}],[$e.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:kn($e.AFTER_TOOL,e)}]}],[$e.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:kn($e.PRE_COMPRESS,e)}]}],[$e.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:kn($e.SESSION_START,e)}]}]}}readSettings(){try{let e=Ml(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=Oo(xa(),".gemini");QT(r,{recursive:!0}),m_(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
6
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let s=n.hooks,o=s?.[$e.BEFORE_TOOL];if(o&&o.length>0){let a=o.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.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 r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=s?.[$e.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.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 r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(s=>typeof s=="string"&&s.includes("context-mode")):Object.keys(r).some(s=>s.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=Oo(xa(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(Ml(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},s=[],o=[{name:$e.BEFORE_AGENT},{name:$e.BEFORE_TOOL},{name:$e.SESSION_START}];for(let i of o){let c={matcher:"",hooks:[{type:"command",command:kn(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let d=u.findIndex(l=>l.hooks?.some(f=>f.command?.includes("context-mode")));d>=0?(u[d]=c,s.push(`Updated existing ${i.name} hook entry`)):(u.push(c),s.push(`Added ${i.name} hook entry`)),n[i.name]=u}else n[i.name]=[c],s.push(`Created ${i.name} hooks section`)}return r.hooks=n,this.writeSettings(r),s}setHookPermissions(e){let r=[],n=nP(e,"hooks","gemini-cli");for(let s of Object.values(Dl)){let o=Oo(n,s);try{eP(o,rP.R_OK),tP(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=Oo(xa(),".gemini","extensions","context-mode","package.json"),s=JSON.parse(Ml(n,"utf-8"));s.version=r,s.installPath=e,s.lastUpdated=new Date().toISOString(),m_(n,JSON.stringify(s,null,2)+`
|
|
7
|
+
`,"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}`}}});var wn,KU,JU,g_=v(()=>{"use strict";wn={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},KU=[wn.BEFORE,wn.AFTER],JU=[wn.COMPACTING]});var __={};Fe(__,{OpenCodeAdapter:()=>zl});import{readFileSync as y_,writeFileSync as oP,mkdirSync as iP,copyFileSync as aP,accessSync as cP,constants as uP}from"node:fs";import{resolve as zt,join as Yr}from"node:path";import{homedir as Xr}from"node:os";function sP(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var zl,x_=v(()=>{"use strict";Pt();g_();zl=class extends Se{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 r=e;return{toolName:r.tool??"",toolInput:r.args??{},sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},toolOutput:r.output,isError:void 0,sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,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 r={};return e.updatedOutput&&(r.output=e.updatedOutput),e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return this.settingsPath??zt(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[zt("kilo.json"),zt("kilo.jsonc"),zt(".kilo","kilo.json"),zt(".kilo","kilo.jsonc"),zt(".kilocode","kilo.json"),zt(".kilocode","kilo.jsonc"),Yr(Xr(),".config","kilo","kilo.json"),Yr(Xr(),".config","kilo","kilo.jsonc")]:[zt("opencode.json"),zt("opencode.jsonc"),zt(".opencode","opencode.json"),zt(".opencode","opencode.jsonc"),Yr(Xr(),".config","opencode","opencode.json"),Yr(Xr(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=Yr(this.getConfigDir(),"context-mode","sessions");return iP(e,{recursive:!0}),e}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||Yr(Xr(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||Yr(Xr(),".config"),Yr(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[wn.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[wn.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[wn.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),r=new Set(e.filter(o=>o.includes(Xr()))),n=null,s;for(let o of e)try{let i=y_(o,"utf-8"),a=o.endsWith(".jsonc")?sP(i):i,c=JSON.parse(a);n||(n=c,s=o);let u=r.has(o);if(this.hasContextModePlugin(c)||u)return this.settingsPath=o,c}catch{continue}return n?(this.settingsPath=s,n):null}writeSettings(e){oP(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
8
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r;let s=this.hasContextModePlugin(n);return Array.isArray(n.plugin)?r.push({check:"Plugin registration",status:s?"pass":"fail",message:s?"context-mode found in plugin array":"context-mode not found in plugin array",fix:s?void 0:"context-mode upgrade"}):r.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),r}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=zt(Xr(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(y_(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[],s=r.plugin??[];return s.some(o=>o.includes("context-mode"))?n.push("context-mode already in plugin array"):(s.push("context-mode"),n.push("Added context-mode to plugin array")),r.plugin=s,this.writeSettings(r),n}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{cP(this.settingsPath,uP.R_OK);let r=this.settingsPath+".bak";return aP(this.settingsPath,r),r}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}hasContextModePlugin(e){let r=e.plugin;return Array.isArray(r)&&r.some(n=>typeof n=="string"&&n.includes("context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var En,nH,sH,v_=v(()=>{"use strict";En={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},nH=[En.TOOL_CALL_BEFORE,En.TOOL_CALL_AFTER],sH=[En.COMMAND_NEW]});var b_={};Fe(b_,{OpenClawAdapter:()=>Hl});import{readFileSync as Ll,writeFileSync as lP,copyFileSync as dP,accessSync as pP,constants as mP}from"node:fs";import{resolve as Rr,join as Fl}from"node:path";import{homedir as Ul}from"node:os";var Hl,S_=v(()=>{"use strict";Pt();v_();Hl=class extends Se{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 r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},toolOutput:r.output??r.tool_output,isError:r.isError??r.is_error,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",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),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 r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Rr("openclaw.json")}getConfigDir(e){return Rr(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(){return Fl(this.getConfigDir(),"memory")}generateHookConfig(e){return{[En.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[En.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[En.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Rr("openclaw.json"),Rr(".openclaw","openclaw.json"),Fl(Ul(),".openclaw","openclaw.json")];for(let r of e)try{let n=Ll(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=Rr("openclaw.json");lP(r,JSON.stringify(e,null,2)+`
|
|
9
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),r;let s=n.plugins,o=s?.entries;if(o){let a=Object.keys(o).some(c=>c.includes("context-mode"));if(r.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=o["context-mode"]?.enabled!==!1;r.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else r.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return s?.slots?.contextEngine==="context-mode"?r.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):r.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let n=e.plugins?.entries;return n&&Object.keys(n).some(o=>o.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=Rr(Ul(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(Ll(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=Rr("node_modules","context-mode","package.json"),r=JSON.parse(Ll(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[];r.plugins||(r.plugins={});let s=r.plugins;s.entries||(s.entries={});let o=s.entries;if(!o["context-mode"])o["context-mode"]={enabled:!0},n.push("Added context-mode to plugins.entries");else{let a=o["context-mode"];a.enabled===!1?(a.enabled=!0,n.push("Enabled context-mode plugin")):n.push("context-mode already configured in plugins.entries")}s.slots||(s.slots={});let i=s.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&n.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",n.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(r),n}backupSettings(){let e=[Rr("openclaw.json"),Rr(".openclaw","openclaw.json"),Fl(Ul(),".openclaw","openclaw.json")];for(let r of e)try{pP(r,mP.R_OK);let n=r+".bak";return dP(r,n),n}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}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 k_}from"node:os";import{resolve as Zl}from"node:path";function va(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?Zl(k_(),t.replace(/^~[/\\]?/,"")):Zl(t):Zl(k_(),".codex")}var Bl=v(()=>{"use strict"});var T_={};Fe(T_,{CodexAdapter:()=>Wl});import{readFileSync as ws,writeFileSync as w_,accessSync as fP,copyFileSync as hP,constants as gP,mkdirSync as ql}from"node:fs";import{resolve as yP,dirname as Vl,join as ba}from"node:path";import{fileURLToPath as _P}from"node:url";function E_(t,e){let r=t.split(/\r?\n/),n=!1,s=[];for(let o of r){let i=o.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(n)break;n=i[1]?.trim()===e;continue}n&&s.push(o)}return n?s.join(`
|
|
10
|
+
`):null}function $_(t){let e=E_(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function bP(t){let e=E_(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function SP(t){if($_(t))return{text:t,changed:!1};let e=t.includes(`\r
|
|
11
11
|
`)?`\r
|
|
12
12
|
`:`
|
|
13
13
|
`,r=t.split(/\r?\n/),n=r.findIndex(o=>/^\s*\[features\]\s*(?:#.*)?$/.test(o));if(n===-1){let o=t.length>0&&!t.endsWith(`
|
|
14
|
-
`)?e:"";return{text:`${t}${o}[features]${e}hooks = true${e}`,changed:!0}}let s=r.length;for(let o=n+1;o<r.length;o++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(r[o]??"")){s=o;break}for(let o=n+1;o<s;o++)if(/^\s*hooks\s*=/.test(r[o]??""))return r[o]="hooks = true",{text:r.join(e),changed:!0};return r.splice(n+1,0,"hooks = true"),{text:r.join(e),changed:!0}}var
|
|
14
|
+
`)?e:"";return{text:`${t}${o}[features]${e}hooks = true${e}`,changed:!0}}let s=r.length;for(let o=n+1;o<r.length;o++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(r[o]??"")){s=o;break}for(let o=n+1;o<s;o++)if(/^\s*hooks\s*=/.test(r[o]??""))return r[o]="hooks = true",{text:r.join(e),changed:!0};return r.splice(n+1,0,"hooks = true"),{text:r.join(e),changed:!0}}var xP,$n,vP,Wl,P_=v(()=>{"use strict";Pt();Bl();xP="local_shell|shell|shell_command|exec_command|container.exec|functions\\.exec_command|Bash|Shell|apply_patch|functions\\.apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__.*__ctx_execute|mcp__.*__ctx_execute_file|mcp__.*__ctx_batch_execute|mcp__.*__ctx_fetch_and_index|mcp__.*__ctx_search|mcp__.*__ctx_index",$n={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"},vP={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"]};Wl=class extends Se{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",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,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 va()}getSettingsPath(){return ba(this.getConfigDir(),"config.toml")}getSessionDir(){let e=ba(this.getConfigDir(),"context-mode","sessions");return ql(e,{recursive:!0}),e}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(){return ba(this.getConfigDir(),"memories")}generateHookConfig(e){return{PreToolUse:[{matcher:xP,hooks:[{type:"command",command:$n.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:$n.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:$n.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:$n.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:$n.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:$n.Stop}]}]}}readSettings(){try{return{_raw_toml:ws(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[];try{let o=ws(this.getSettingsPath(),"utf-8"),i=$_(o),a=!i&&bP(o);r.push({check:"Codex hooks feature flag",status:i?"pass":"fail",message:i?`[features].hooks enabled in ${this.getSettingsPath()}`:a?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...i?{}:{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 n=this.readHooksConfig();if(!n.ok)return n.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"}]):n.reason==="invalid_json"?r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${n.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()}: ${n.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}]);if(!n.config.hooks)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 s=this.generateHookConfig("");return r.concat(Object.entries(s).map(([o,i])=>{let a=n.config.hooks?.[o],c=i[0],u=Array.isArray(a)&&a.some(l=>this.isExpectedHookEntry(o,l,c)),d=o==="PreCompact"?"warn":"fail";return{check:`${o} hook`,status:u?"pass":d,message:u?`${o} hook configured in ${this.getHooksPath()}`:o==="PreCompact"?`${o} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${o} hook missing or not pointing to context-mode`,fix:u?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}))}checkPluginRegistration(){try{let e=ws(this.getSettingsPath(),"utf-8"),r=e.includes("context-mode"),n=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return r&&n?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:n?{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"not installed"}configureAllHooks(e){let r=this.readHooksConfig(),n=[],s;if(r.ok)s=r.config;else if(r.reason==="missing")s={hooks:{}};else if(r.reason==="invalid_json"){let d=this.backupFile(this.getHooksPath(),".broken");n.push(`Backed up malformed Codex hooks to ${d}`),s={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${r.error}`);let o=s.hooks&&typeof s.hooks=="object"&&!Array.isArray(s.hooks)?s.hooks:{},i=this.generateHookConfig(e);for(let[d,l]of Object.entries(i))this.upsertManagedHookEntry(o,d,l[0],n);n.length>0&&(s.hooks=o,this.writeHooksConfig(s),n.push(`Wrote native Codex hooks to ${this.getHooksPath()}`));let a=this.getSettingsPath(),c="";try{c=ws(a,"utf-8")}catch{c=""}let u=SP(c);if(u.changed){let d=u.text.includes(`\r
|
|
15
15
|
`)?`\r
|
|
16
16
|
`:`
|
|
17
17
|
`,l=u.text.endsWith(`
|
|
18
|
-
`)?u.text:`${u.text}${d}`;
|
|
18
|
+
`)?u.text:`${u.text}${d}`;ql(Vl(a),{recursive:!0}),w_(a,l,"utf-8"),n.push("Enabled Codex hooks feature flag")}return n}backupSettings(){let e=null;for(let r of[this.getHooksPath(),this.getSettingsPath()])try{fP(r,gP.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=yP(Vl(_P(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return ws(e,"utf-8")}catch{return`# context-mode
|
|
19
19
|
|
|
20
|
-
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 ba(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return
|
|
21
|
-
`,"utf-8")}upsertManagedHookEntry(e,r,n,s){let o=Array.isArray(e[r])?[...e[r]]:[],i=o.map((c,u)=>this.isManagedContextModeEntry(r,c)?u:-1).filter(c=>c>=0);if(i.length===0){o.push(n),e[r]=o,s.push(`Added ${r} hook`);return}let a=i[0];JSON.stringify(o[a])!==JSON.stringify(n)&&(o[a]=n,s.push(`Updated ${r} hook`));for(let c of i.slice(1).reverse())o.splice(c,1),s.push(`Removed duplicate ${r} context-mode hook`);e[r]=o}isExpectedHookEntry(e,r,n){return!r||typeof r!="object"||e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}isManagedContextModeEntry(e,r){return!r||typeof r!="object"?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(Array.isArray(r.hooks)?r.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),s=this.normalizeCommand(
|
|
22
|
-
`,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},s=n.hooks??{},{HOOK_TYPES:o,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[o.PRE_TOOL_USE,o.POST_TOOL_USE,o.PRE_COMPACT,o.SESSION_START];for(let u of c)i[u]&&(s[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=s,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=xP(e,"hooks",this.hookSubdir);for(let s of Object.values(this.hookModule.HOOK_SCRIPTS)){let o=Sa(n,s);try{gP(o,_P.R_OK),yP(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}}});function T_(t,e){let r=Vl[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?Fe(`${e}/hooks/vscode-copilot/${r}`):`context-mode hook vscode-copilot ${t.toLowerCase()}`}var zt,Vl,lH,dH,P_=v(()=>{"use strict";Kr();zt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Vl={[zt.PRE_TOOL_USE]:"pretooluse.mjs",[zt.POST_TOOL_USE]:"posttooluse.mjs",[zt.PRE_COMPACT]:"precompact.mjs",[zt.SESSION_START]:"sessionstart.mjs"},lH=[zt.PRE_TOOL_USE,zt.SESSION_START],dH=[zt.POST_TOOL_USE,zt.PRE_COMPACT]});var R_={};Le(R_,{VSCodeCopilotAdapter:()=>Kl});import{readFileSync as Wl,mkdirSync as vP,accessSync as bP,existsSync as SP,constants as kP}from"node:fs";import{resolve as ws,join as ka}from"node:path";import{homedir as Gl}from"node:os";var Kl,C_=v(()=>{"use strict";ql();P_();Kl=class extends ks{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:zt,HOOK_SCRIPTS:Vl,buildHookCommand:T_};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.cwd()}getSessionDir(){let e=ws(".github","context-mode","sessions"),r=ka(Gl(),".vscode","context-mode","sessions"),n=SP(ws(".github"))?e:r;return vP(n,{recursive:!0}),n}getConfigDir(e){return ws(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=ws(".github","hooks");try{bP(n,kP.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let s=ws(n,"context-mode.json");try{let o=Wl(s,"utf-8"),a=JSON.parse(o).hooks;a?.[zt.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?.[zt.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=ws(".vscode","mcp.json"),r=Wl(e,"utf-8"),s=JSON.parse(r).servers;return s&&Object.keys(s).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=[ka(Gl(),".vscode","extensions"),ka(Gl(),".vscode-insiders","extensions")];for(let r of e)try{let n=Wl(ka(r,"extensions.json"),"utf-8"),o=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(o&&typeof o.version=="string")return o.version}catch{continue}return"not installed"}}});function O_(t,e){let r=Jl[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?Fe(`${e}/hooks/jetbrains-copilot/${r}`):`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Lt,Jl,xH,vH,I_=v(()=>{"use strict";Kr();Lt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Jl={[Lt.PRE_TOOL_USE]:"pretooluse.mjs",[Lt.POST_TOOL_USE]:"posttooluse.mjs",[Lt.PRE_COMPACT]:"precompact.mjs",[Lt.SESSION_START]:"sessionstart.mjs"},xH=[Lt.PRE_TOOL_USE,Lt.SESSION_START],vH=[Lt.POST_TOOL_USE,Lt.PRE_COMPACT]});var A_={};Le(A_,{JetBrainsCopilotAdapter:()=>Yl});import{readFileSync as wP}from"node:fs";import{resolve as EP}from"node:path";var Yl,N_=v(()=>{"use strict";ql();I_();Yl=class extends ks{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Lt,HOOK_SCRIPTS:Jl,buildHookCommand:O_};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 EP(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=wP(this.getSettingsPath(),"utf-8"),o=JSON.parse(n).hooks;o?.[Lt.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"}),o?.[Lt.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 Oo(t,e){let r=Xl[e],n=Ft(e);if("command"in t){let o=t.command??"";return r!=null&&o.includes(r)||o.includes(n)}return t.hooks?.some(o=>{let i=o.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function Ft(t){return`context-mode hook cursor ${t.toLowerCase()}`}var _e,Xl,$P,Ql,D_,M_,j_=v(()=>{"use strict";_e={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Xl={[_e.PRE_TOOL_USE]:"pretooluse.mjs",[_e.POST_TOOL_USE]:"posttooluse.mjs",[_e.SESSION_START]:"sessionstart.mjs",[_e.STOP]:"stop.mjs",[_e.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},$P=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute"],Ql=$P.join("|"),D_=[_e.PRE_TOOL_USE],M_=[_e.POST_TOOL_USE]});var H_={};Le(H_,{CursorAdapter:()=>ed});import{readFileSync as wa,writeFileSync as TP,mkdirSync as PP,accessSync as z_,chmodSync as RP,constants as L_,existsSync as F_,readdirSync as CP}from"node:fs";import{execSync as OP}from"node:child_process";import{resolve as $n,join as Tn}from"node:path";import{homedir as Ea}from"node:os";var U_,ed,Z_=v(()=>{"use strict";Tt();Gr();j_();U_="/Library/Application Support/Cursor/hooks.json",ed=class extends Se{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",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,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 $n(".cursor","hooks.json")}getConfigDir(e){return $n(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[_e.PRE_TOOL_USE]:[{type:"command",command:Ft(_e.PRE_TOOL_USE),matcher:Ql,loop_limit:null,failClosed:!1}],[_e.POST_TOOL_USE]:[{type:"command",command:Ft(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[_e.SESSION_START]:[{type:"command",command:Ft(_e.SESSION_START),loop_limit:null,failClosed:!1}],[_e.STOP]:[{type:"command",command:Ft(_e.STOP),loop_limit:null,failClosed:!1}],[_e.AFTER_AGENT_RESPONSE]:[{type:"command",command:Ft(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=wa(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();PP($n(".cursor"),{recursive:!0}),TP(r,JSON.stringify(e,null,2)+`
|
|
23
|
-
`,"utf-8")}validateHooks(e){let r=[],n=this.loadNativeHookConfig();if(!n)r.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 o=n.config.hooks??{};r.push({check:"Native hook config",status:"pass",message:`Loaded ${n.path}`});for(let i of
|
|
20
|
+
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 ba(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return hP(e,n),n}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(ws(e,"utf-8"))}}catch(r){let n=r instanceof Error?r.message:String(r);return(typeof r=="object"&&r!==null&&"code"in r?String(r.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:r instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:n}:{ok:!1,reason:"read_error",error:n}}}writeHooksConfig(e){let r=this.getHooksPath();ql(Vl(r),{recursive:!0}),w_(r,JSON.stringify(e,null,2)+`
|
|
21
|
+
`,"utf-8")}upsertManagedHookEntry(e,r,n,s){let o=Array.isArray(e[r])?[...e[r]]:[],i=o.map((c,u)=>this.isManagedContextModeEntry(r,c)?u:-1).filter(c=>c>=0);if(i.length===0){o.push(n),e[r]=o,s.push(`Added ${r} hook`);return}let a=i[0];JSON.stringify(o[a])!==JSON.stringify(n)&&(o[a]=n,s.push(`Updated ${r} hook`));for(let c of i.slice(1).reverse())o.splice(c,1),s.push(`Removed duplicate ${r} context-mode hook`);e[r]=o}isExpectedHookEntry(e,r,n){return!r||typeof r!="object"||e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}isManagedContextModeEntry(e,r){return!r||typeof r!="object"?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(Array.isArray(r.hooks)?r.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),s=this.normalizeCommand($n[e]??""),o=vP[e]??[];return n.some(i=>i.includes(s)||o.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 R_,writeFileSync as kP,mkdirSync as wP,accessSync as EP,chmodSync as $P,constants as TP}from"node:fs";import{resolve as Sa,join as PP}from"node:path";var Es,Gl=v(()=>{"use strict";Pt();Es=class extends Se{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,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(){return Sa(".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:r,buildHookCommand:n}=this.hookModule;return{[r.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_TOOL_USE,e)}]}],[r.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.POST_TOOL_USE,e)}]}],[r.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_COMPACT,e)}]}],[r.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:n(r.SESSION_START,e)}]}]}}readSettings(){try{let e=R_(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=R_(Sa(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();wP(Sa(".github","hooks"),{recursive:!0}),kP(r,JSON.stringify(e,null,2)+`
|
|
22
|
+
`,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},s=n.hooks??{},{HOOK_TYPES:o,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[o.PRE_TOOL_USE,o.POST_TOOL_USE,o.PRE_COMPACT,o.SESSION_START];for(let u of c)i[u]&&(s[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=s,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=PP(e,"hooks",this.hookSubdir);for(let s of Object.values(this.hookModule.HOOK_SCRIPTS)){let o=Sa(n,s);try{EP(o,TP.R_OK),$P(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}}});function C_(t,e){let r=Kl[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?Ue(`${e}/hooks/vscode-copilot/${r}`):`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Lt,Kl,wH,EH,O_=v(()=>{"use strict";Jr();Lt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Kl={[Lt.PRE_TOOL_USE]:"pretooluse.mjs",[Lt.POST_TOOL_USE]:"posttooluse.mjs",[Lt.PRE_COMPACT]:"precompact.mjs",[Lt.SESSION_START]:"sessionstart.mjs"},wH=[Lt.PRE_TOOL_USE,Lt.SESSION_START],EH=[Lt.POST_TOOL_USE,Lt.PRE_COMPACT]});var I_={};Fe(I_,{VSCodeCopilotAdapter:()=>Xl});import{readFileSync as Jl,mkdirSync as RP,accessSync as CP,existsSync as OP,constants as IP}from"node:fs";import{resolve as $s,join as ka}from"node:path";import{homedir as Yl}from"node:os";var Xl,A_=v(()=>{"use strict";Gl();O_();Xl=class extends Es{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Lt,HOOK_SCRIPTS:Kl,buildHookCommand:C_};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.cwd()}getSessionDir(){let e=$s(".github","context-mode","sessions"),r=ka(Yl(),".vscode","context-mode","sessions"),n=OP($s(".github"))?e:r;return RP(n,{recursive:!0}),n}getConfigDir(e){return $s(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=$s(".github","hooks");try{CP(n,IP.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let s=$s(n,"context-mode.json");try{let o=Jl(s,"utf-8"),a=JSON.parse(o).hooks;a?.[Lt.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?.[Lt.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=$s(".vscode","mcp.json"),r=Jl(e,"utf-8"),s=JSON.parse(r).servers;return s&&Object.keys(s).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=[ka(Yl(),".vscode","extensions"),ka(Yl(),".vscode-insiders","extensions")];for(let r of e)try{let n=Jl(ka(r,"extensions.json"),"utf-8"),o=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(o&&typeof o.version=="string")return o.version}catch{continue}return"not installed"}}});function N_(t,e){let r=Ql[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?Ue(`${e}/hooks/jetbrains-copilot/${r}`):`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Ft,Ql,AH,NH,D_=v(()=>{"use strict";Jr();Ft={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Ql={[Ft.PRE_TOOL_USE]:"pretooluse.mjs",[Ft.POST_TOOL_USE]:"posttooluse.mjs",[Ft.PRE_COMPACT]:"precompact.mjs",[Ft.SESSION_START]:"sessionstart.mjs"},AH=[Ft.PRE_TOOL_USE,Ft.SESSION_START],NH=[Ft.POST_TOOL_USE,Ft.PRE_COMPACT]});var M_={};Fe(M_,{JetBrainsCopilotAdapter:()=>ed});import{readFileSync as AP}from"node:fs";import{resolve as NP}from"node:path";var ed,j_=v(()=>{"use strict";Gl();D_();ed=class extends Es{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Ft,HOOK_SCRIPTS:Ql,buildHookCommand:N_};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 NP(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=AP(this.getSettingsPath(),"utf-8"),o=JSON.parse(n).hooks;o?.[Ft.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"}),o?.[Ft.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 Io(t,e){let r=td[e],n=Ut(e);if("command"in t){let o=t.command??"";return r!=null&&o.includes(r)||o.includes(n)}return t.hooks?.some(o=>{let i=o.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function Ut(t){return`context-mode hook cursor ${t.toLowerCase()}`}var _e,td,DP,rd,z_,L_,F_=v(()=>{"use strict";_e={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},td={[_e.PRE_TOOL_USE]:"pretooluse.mjs",[_e.POST_TOOL_USE]:"posttooluse.mjs",[_e.SESSION_START]:"sessionstart.mjs",[_e.STOP]:"stop.mjs",[_e.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},DP=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute"],rd=DP.join("|"),z_=[_e.PRE_TOOL_USE],L_=[_e.POST_TOOL_USE]});var q_={};Fe(q_,{CursorAdapter:()=>nd});import{readFileSync as wa,writeFileSync as MP,mkdirSync as jP,accessSync as U_,chmodSync as zP,constants as H_,existsSync as Z_,readdirSync as LP}from"node:fs";import{execSync as FP}from"node:child_process";import{resolve as Tn,join as Pn}from"node:path";import{homedir as Ea}from"node:os";var B_,nd,V_=v(()=>{"use strict";Pt();Kr();F_();B_="/Library/Application Support/Cursor/hooks.json",nd=class extends Se{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",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,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 Tn(".cursor","hooks.json")}getConfigDir(e){return Tn(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[_e.PRE_TOOL_USE]:[{type:"command",command:Ut(_e.PRE_TOOL_USE),matcher:rd,loop_limit:null,failClosed:!1}],[_e.POST_TOOL_USE]:[{type:"command",command:Ut(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[_e.SESSION_START]:[{type:"command",command:Ut(_e.SESSION_START),loop_limit:null,failClosed:!1}],[_e.STOP]:[{type:"command",command:Ut(_e.STOP),loop_limit:null,failClosed:!1}],[_e.AFTER_AGENT_RESPONSE]:[{type:"command",command:Ut(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=wa(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();jP(Tn(".cursor"),{recursive:!0}),MP(r,JSON.stringify(e,null,2)+`
|
|
23
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.loadNativeHookConfig();if(!n)r.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 o=n.config.hooks??{};r.push({check:"Native hook config",status:"pass",message:`Loaded ${n.path}`});for(let i of z_){let a=o[i],c=Array.isArray(a)&&a.some(u=>Io(u,i));r.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${n.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of L_){let a=o[i],c=Array.isArray(a)&&a.some(u=>Io(u,i));r.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}Z_(B_)&&r.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()&&r.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let s=this.detectPluginInstalls();return s.length>0&&((n?Object.entries(n.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>Io(c,i))):!1)&&n?r.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${s[0]} alongside native hooks in ${n.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"}):r.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${s[0]}`})),r}detectPluginInstalls(){let e=[Pn(Ea(),".cursor","plugins","local"),Pn(Ea(),".cursor","plugins","cache")],r=[];for(let n of e){try{U_(n,H_.F_OK)}catch{continue}let s=[];try{s=LP(n)}catch{continue}for(let o of s){let i=Pn(n,o,".cursor-plugin","plugin.json");try{let a=wa(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&r.push(i)}catch{continue}}}return r}checkPluginRegistration(){let e=[Tn(".cursor","mcp.json"),Pn(Ea(),".cursor","mcp.json")];for(let n of e)try{let s=wa(n,"utf-8"),o=JSON.parse(s),i=o.mcpServers??o.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 ${n}`}}catch{continue}let r=this.detectPluginInstalls();return r.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${r[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return FP("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=this.readSettings()??{version:1,hooks:{}},n=r.hooks??{},s=[];return this.upsertHookEntry(n,_e.PRE_TOOL_USE,{type:"command",command:Ut(_e.PRE_TOOL_USE),matcher:rd,loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.POST_TOOL_USE,{type:"command",command:Ut(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.SESSION_START,{type:"command",command:Ut(_e.SESSION_START),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.STOP,{type:"command",command:Ut(_e.STOP),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.AFTER_AGENT_RESPONSE,{type:"command",command:Ut(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},s),r.version=1,r.hooks=n,this.writeSettings(r),s.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),s}setHookPermissions(e){let r=[],n=Pn(e,"hooks","cursor");for(let s of Object.values(td)){let o=Tn(n,s);try{U_(o,H_.R_OK),zP(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),Pn(Ea(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(B_),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 r=wa(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[Tn(".claude","settings.json"),Tn(".claude","settings.local.json"),Pn(qe(),"settings.json")].some(r=>Z_(r))}upsertHookEntry(e,r,n,s){let o=e[r],i=Array.isArray(o)?[...o]:[],a=i.findIndex(c=>Io(c,r));a>=0?(i[a]=n,s.push(`Updated existing ${r} hook entry`)):(i.push(n),s.push(`Added ${r} hook entry`)),e[r]=i}}});var G_={};Fe(G_,{AntigravityAdapter:()=>od});import{readFileSync as $a,writeFileSync as UP,mkdirSync as HP}from"node:fs";import{resolve as Ta,dirname as W_}from"node:path";import{fileURLToPath as ZP}from"node:url";import{homedir as sd}from"node:os";var od,K_=v(()=>{"use strict";Pt();od=class extends Se{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 Ta(sd(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Ta(sd(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=$a(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();HP(W_(r),{recursive:!0}),UP(r,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=$a(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=Ta(sd(),".gemini","extensions","context-mode","package.json");return JSON.parse($a(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Ta(W_(ZP(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return $a(e,"utf-8")}catch{return`# context-mode
|
|
24
24
|
|
|
25
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});function Pa(t,e){let r=
|
|
25
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});function Pa(t,e){let r=J_[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function Ts(t,e){let r=J_[t];return e&&r?Ue(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var Me,J_,BP,id,tZ,rZ,Y_=v(()=>{"use strict";Jr();Me={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},J_={[Me.PRE_TOOL_USE]:"pretooluse.mjs",[Me.POST_TOOL_USE]:"posttooluse.mjs",[Me.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Me.AGENT_SPAWN]:"agentspawn.mjs"},BP=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute"],id=BP.join("|"),tZ=[Me.PRE_TOOL_USE,Me.AGENT_SPAWN],rZ=[Me.POST_TOOL_USE,Me.USER_PROMPT_SUBMIT]});var tx={};Fe(tx,{KiroAdapter:()=>ad});import{readFileSync as Ps,writeFileSync as X_,mkdirSync as Q_}from"node:fs";import{resolve as Rn,dirname as ex}from"node:path";import{fileURLToPath as qP}from"node:url";import{homedir as Ra}from"node:os";var ad,rx=v(()=>{"use strict";Pt();Y_();ad=class extends Se{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 r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e,n=r.tool_response;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:typeof n=="string"?n:JSON.stringify(n??""),sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let r=e??{};return{source:r.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:r.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 Rn(Ra(),".kiro","settings","mcp.json")}getConfigDir(e){return Rn(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Me.PRE_TOOL_USE]:[{matcher:id,hooks:[{type:"command",command:Ts(Me.PRE_TOOL_USE,e)}]}],[Me.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:Ts(Me.POST_TOOL_USE,e)}]}],[Me.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:Ts(Me.AGENT_SPAWN,e)}]}],[Me.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:Ts(Me.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=Ps(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();Q_(ex(r),{recursive:!0}),X_(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=Rn(Ra(),".kiro","agents","default.json");try{let o=JSON.parse(Ps(n,"utf-8")).hooks??{};for(let i of[Me.PRE_TOOL_USE]){let c=(o[i]??[]).some(u=>Pa(u,i));r.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[Me.POST_TOOL_USE]){let c=(o[i]??[]).some(u=>Pa(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{r.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return r}checkPluginRegistration(){try{let e=Ps(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=Rn(Ra(),".kiro","extensions","context-mode","package.json");return JSON.parse(Ps(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=Rn(Ra(),".kiro","agents"),s=Rn(n,"default.json");try{Q_(n,{recursive:!0});let o={};try{o=JSON.parse(Ps(s,"utf-8"))}catch{}let i=o.hooks??{},a=[[Me.PRE_TOOL_USE,id],[Me.POST_TOOL_USE,"*"],[Me.AGENT_SPAWN,"*"],[Me.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let d=i[c]??[];d.some(l=>Pa(l,c))||(d.push({matcher:u,command:Ts(c,e)}),i[c]=d,r.push(`Added ${c} hook to ${s}`))}o.hooks=i,X_(s,JSON.stringify(o,null,2),"utf-8")}catch(o){r.push(`Failed to configure hooks: ${o.message}`)}return r}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Rn(ex(qP(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return Ps(e,"utf-8")}catch{return`# context-mode
|
|
26
26
|
|
|
27
|
-
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
|
|
27
|
+
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 ox={};Fe(ox,{ZedAdapter:()=>ud});import{readFileSync as cd,writeFileSync as VP,mkdirSync as WP}from"node:fs";import{resolve as nx,dirname as sx}from"node:path";import{fileURLToPath as GP}from"node:url";import{homedir as KP}from"node:os";var ud,ix=v(()=>{"use strict";Pt();ud=class extends Se{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 nx(KP(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=cd(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();WP(sx(r),{recursive:!0}),VP(r,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=cd(this.getSettingsPath(),"utf-8"),n=JSON.parse(e).context_servers!==void 0,s=e.includes("context-mode");return n&&s?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:n?{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,r){}getRoutingInstructions(){let e=nx(sx(GP(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return cd(e,"utf-8")}catch{return`# context-mode
|
|
28
28
|
|
|
29
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var
|
|
29
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var ux={};Fe(ux,{QwenCodeAdapter:()=>ld});import{readFileSync as JP,writeFileSync as YP,existsSync as XP}from"node:fs";import{resolve as ax,join as QP}from"node:path";import{homedir as cx}from"node:os";var ld,lx=v(()=>{"use strict";Rl();Jr();ld=class extends bs{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 ax(cx(),".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"].join("|"),hooks:[{type:"command",command:Ue(`${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:Ue(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Ue(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Ue(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Ue(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=JP(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){YP(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let r=[],s=this.readSettings()?.hooks??{};for(let o of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit"]){let i=Array.isArray(s[o])&&s[o].length>0;r.push({check:`${o} hook`,status:i?"pass":"fail",message:i?`${o} hook configured in ~/.qwen/settings.json`:`${o} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${o} hook to ~/.qwen/settings.json`}})}return r}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let r=e.mcpServers;return Object.keys(r).some(n=>n.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 r=e.hooks;if(!r)return"not installed";let n=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,s]of Object.entries(r))if(Array.isArray(s)){for(let o of s)if(o.hooks?.some(a=>a.command&&n.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},s=[];for(let i of Object.keys(n)){let a=n[i];if(!Array.isArray(a))continue;let c=a.filter(d=>{let m=d.hooks??[];return m.some(p=>p.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(p.command))?m.every(p=>{if(!p.command)return!0;let h=p.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=p.command.match(/node\s+"?([^"]+\.mjs)"?/),_=h||g;return _?XP(_[1]):!0}):!0}),u=a.length-c.length;u>0&&(n[i]=c,s.push(`Removed ${u} stale ${i} hook(s)`))}let o=[{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"].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 o){let u={matcher:c,hooks:[{type:"command",command:Ue(`${e}/hooks/${a}`)}]},d=n[i];if(d&&Array.isArray(d)){let l=d.findIndex(m=>m.hooks?.some(p=>p.command?.includes(a))??!1);l>=0?(d[l]=u,s.push(`Updated ${i} hook`)):(d.push(u),s.push(`Added ${i} hook`)),n[i]=d}else n[i]=[u],s.push(`Created ${i} hooks`)}return r.hooks=n,this.writeSettings(r),s}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructionsConfig(){return{instructionsPath:ax(QP(cx(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var dx={};Fe(dx,{OMPAdapter:()=>md});import{readFileSync as dd,writeFileSync as eR,mkdirSync as tR}from"node:fs";import{resolve as pd,dirname as rR}from"node:path";import{homedir as nR}from"node:os";var md,px=v(()=>{"use strict";Pt();md=class extends Se{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??pd(nR(),".omp","agent")}getSettingsPath(){return pd(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=dd(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();tR(rR(r),{recursive:!0}),eR(r,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=dd(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=pd(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(dd(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
|
|
30
30
|
|
|
31
|
-
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
|
|
31
|
+
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 mx={};Fe(mx,{PiAdapter:()=>yd});import{readFileSync as fd,writeFileSync as sR,mkdirSync as oR}from"node:fs";import{resolve as hd,dirname as iR}from"node:path";import{homedir as gd}from"node:os";var yd,fx=v(()=>{"use strict";Pt();yd=class extends Se{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 hd(gd(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=fd(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();oR(iR(r),{recursive:!0}),sR(r,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=hd(gd(),".pi","extensions","context-mode","package.json");try{return JSON.parse(fd(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=hd(gd(),".pi","extensions","context-mode","package.json");return JSON.parse(fd(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
|
|
32
32
|
|
|
33
|
-
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.`}}});var gd={};Le(gd,{PLATFORM_ENV_VARS:()=>px,detectPlatform:()=>gr,getAdapter:()=>Io,getSessionDirSegments:()=>hd});import{existsSync as Pt}from"node:fs";import{resolve as Rt}from"node:path";import{homedir as YP}from"node:os";function hd(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"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function gr(t){if(t?.name){let n=e_[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"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,s]of px)if(s.some(o=>process.env[o]))return{platform:n,confidence:"high",reason:`${s.join(" or ")} env var set`};let r=YP();return Pt(Rt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Pt(Rt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Pt(Rt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Pt(Rt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Pt(Rt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Pt(Rt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Pt(Rt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Pt(Rt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Pt(Rt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Pt(Rt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Pt(Rt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Pt(Rt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Pt(Rt(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 Io(t){let e=t??gr().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Ol(),Cl));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(p_(),d_));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(g_(),h_));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(x_(),__));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(E_(),w_));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(C_(),R_));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(N_(),A_));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(Z_(),H_));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(V_(),q_));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(Q_(),X_));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(nx(),rx));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(ax(),ix));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(ux(),cx));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(dx(),lx));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Ol(),Cl));return new r}}}var px,Ao=v(()=>{"use strict";t_();px=[["claude-code",["CLAUDE_PROJECT_DIR","CLAUDE_SESSION_ID"]],["antigravity",["ANTIGRAVITY_CLI_ALIAS"]],["cursor",["CURSOR_TRACE_ID","CURSOR_CLI"]],["kilo",["KILO","KILO_PID"]],["opencode",["OPENCODE","OPENCODE_PID"]],["zed",["ZED_SESSION_ID","ZED_TERM"]],["codex",["CODEX_THREAD_ID","CODEX_CI"]],["gemini-cli",["GEMINI_PROJECT_DIR","GEMINI_CLI"]],["vscode-copilot",["VSCODE_PID","VSCODE_CWD"]],["jetbrains-copilot",["IDEA_INITIAL_DIRECTORY"]],["qwen-code",["QWEN_PROJECT_DIR"]],["omp",["PI_CODING_AGENT_DIR"]],["pi",["PI_PROJECT_DIR"]]]});var ie,yd,M,yr,No=v(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ie||(ie={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(yd||(yd={}));M=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yr=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}}});var $,XP,xt,Ca=v(()=>{No();$=ie.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"]),XP=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),xt=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(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(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 s(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,ie.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};xt.create=t=>new xt(t)});var QP,Rr,_d=v(()=>{Ca();No();QP=(t,e)=>{let r;switch(t.code){case $.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case $.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ie.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${ie.joinValues(t.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ie.joinValues(t.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${ie.joinValues(t.options)}, received '${t.received}'`;break;case $.invalid_arguments:r="Invalid function arguments";break;case $.invalid_return_type:r="Invalid function return type";break;case $.invalid_date:r="Invalid date";break;case $.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}"`:ie.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case $.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 $.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 $.custom:r="Invalid input";break;case $.invalid_intersection_types:r="Intersection results could not be merged";break;case $.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case $.not_finite:r="Number must be finite";break;default:r=e.defaultError,ie.assertNever(t)}return{message:r}},Rr=QP});function eR(t){mx=t}function Ts(){return mx}var mx,Oa=v(()=>{_d();mx=Rr});function A(t,e){let r=Ts(),n=Do({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Rr?void 0:Rr].filter(s=>!!s)});t.common.issues.push(n)}var Do,tR,Ke,W,Rn,st,Ia,Aa,Xr,Ps,xd=v(()=>{Oa();_d();Do=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},tR=[];Ke=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 s of r){if(s.status==="aborted")return W;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return W;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},W=Object.freeze({status:"aborted"}),Rn=t=>({status:"dirty",value:t}),st=t=>({status:"valid",value:t}),Ia=t=>t.status==="aborted",Aa=t=>t.status==="dirty",Xr=t=>t.status==="valid",Ps=t=>typeof Promise<"u"&&t instanceof Promise});var fx=v(()=>{});var L,hx=v(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}))});function X(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=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:s}:{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:s}}function xx(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 _R(t){return new RegExp(`^${xx(t)}$`)}function vx(t){let e=`${_x}T${xx(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 xR(t,e){return!!((e==="v4"||!e)&&dR.test(t)||(e==="v6"||!e)&&mR.test(t))}function vR(t,e){if(!aR.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,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function bR(t,e){return!!((e==="v4"||!e)&&pR.test(t)||(e==="v6"||!e)&&fR.test(t))}function SR(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function Rs(t){if(t instanceof bt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=vt.create(Rs(n))}return new bt({...t._def,shape:()=>e})}else return t instanceof Ir?new Ir({...t._def,type:Rs(t.element)}):t instanceof vt?vt.create(Rs(t.unwrap())):t instanceof xr?xr.create(Rs(t.unwrap())):t instanceof _r?_r.create(t.items.map(e=>Rs(e))):t}function bd(t,e){let r=yr(t),n=yr(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){let s=ie.objectKeys(e),o=ie.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=bd(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===M.array&&n===M.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=bd(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function bx(t,e){return new Fn({values:t,typeName:R.ZodEnum,...X(e)})}function yx(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Sx(t,e={},r){return t?en.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=yx(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=yx(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):en.create()}var Ut,gx,ee,rR,nR,sR,oR,iR,aR,cR,uR,lR,vd,dR,pR,mR,fR,hR,gR,_x,yR,Qr,Cn,On,In,An,Cs,Nn,Dn,en,Or,rr,Os,Ir,bt,Mn,Cr,Na,jn,_r,Da,Is,As,Ma,zn,Ln,Fn,Un,tn,Ht,vt,xr,Hn,Zn,Ns,kR,Mo,jo,Bn,wR,R,ER,kx,wx,$R,TR,Ex,PR,RR,CR,OR,IR,AR,NR,DR,MR,Sd,jR,zR,LR,FR,UR,HR,ZR,BR,qR,VR,WR,GR,KR,JR,YR,XR,QR,eC,tC,rC,nC,sC,oC,iC,$x=v(()=>{Ca();Oa();hx();xd();No();Ut=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}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}},gx=(t,e)=>{if(Xr(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 xt(t.common.issues);return this._error=r,this._error}}};ee=class{get description(){return this._def.description}_getType(e){return yr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ke,ctx:{common:e.parent.common,data:e.data,parsedType:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ps(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:yr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return gx(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Xr(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=>Xr(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:yr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(Ps(s)?s:Promise.resolve(s));return gx(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:$.custom,...n(s)});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,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Ht({schema:this,typeName:R.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 vt.create(this,this._def)}nullable(){return xr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ir.create(this)}promise(){return tn.create(this,this._def)}or(e){return Mn.create([this,e],this._def)}and(e){return jn.create(this,e,this._def)}transform(e){return new Ht({...X(this._def),schema:this,typeName:R.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Hn({...X(this._def),innerType:this,defaultValue:r,typeName:R.ZodDefault})}brand(){return new Mo({typeName:R.ZodBranded,type:this,...X(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Zn({...X(this._def),innerType:this,catchValue:r,typeName:R.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return jo.create(this,e)}readonly(){return Bn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},rR=/^c[^\s-]{8,}$/i,nR=/^[0-9a-z]+$/,sR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,oR=/^[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,iR=/^[a-z0-9_-]{21}$/i,aR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cR=/^[-+]?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)?)??$/,uR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",dR=/^(?:(?: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])$/,pR=/^(?:(?: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])$/,mR=/^(([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]))$/,fR=/^(([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])$/,hR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,gR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_x="((\\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])))",yR=new RegExp(`^${_x}$`);Qr=class t extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let o=this._getOrReturnCtx(e);return A(o,{code:$.invalid_type,expected:M.string,received:o.parsedType}),W}let n=new Ke,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:$.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:$.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?A(s,{code:$.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&A(s,{code:$.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")uR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"email",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")vd||(vd=new RegExp(lR,"u")),vd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"emoji",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")oR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"uuid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")iR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"nanoid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")rR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")nR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid2",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")sR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ulid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),A(s,{validation:"url",code:$.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"regex",code:$.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),A(s,{code:$.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:$.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:$.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?vx(o).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:$.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?yR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:$.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?_R(o).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:$.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?cR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"duration",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?xR(e.data,o.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ip",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?vR(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"jwt",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?bR(e.data,o.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cidr",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?hR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?gR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64url",code:$.invalid_string,message:o.message}),n.dirty()):ie.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:$.invalid_string,...L.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.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,...L.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,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...L.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...L.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...L.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...L.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...L.errToObj(r)})}nonempty(e){return this.min(1,L.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}};Qr.create=t=>new Qr({checks:[],typeName:R.ZodString,coerce:t?.coerce??!1,...X(t)});Cn=class t extends ee{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)!==M.number){let o=this._getOrReturnCtx(e);return A(o,{code:$.invalid_type,expected:M.number,received:o.parsedType}),W}let n,s=new Ke;for(let o of this._def.checks)o.kind==="int"?ie.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:$.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:$.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:$.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?SR(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),A(n,{code:$.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:$.not_finite,message:o.message}),s.dirty()):ie.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.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"&&ie.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)}};Cn.create=t=>new Cn({checks:[],typeName:R.ZodNumber,coerce:t?.coerce||!1,...X(t)});On=class t extends ee{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)!==M.bigint)return this._getInvalidInput(e);let n,s=new Ke;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:$.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:$.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),A(n,{code:$.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ie.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return A(r,{code:$.invalid_type,expected:M.bigint,received:r.parsedType}),W}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.toString(s)}]})}_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:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.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}};On.create=t=>new On({checks:[],typeName:R.ZodBigInt,coerce:t?.coerce??!1,...X(t)});In=class extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let n=this._getOrReturnCtx(e);return A(n,{code:$.invalid_type,expected:M.boolean,received:n.parsedType}),W}return st(e.data)}};In.create=t=>new In({typeName:R.ZodBoolean,coerce:t?.coerce||!1,...X(t)});An=class t extends ee{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let o=this._getOrReturnCtx(e);return A(o,{code:$.invalid_type,expected:M.date,received:o.parsedType}),W}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return A(o,{code:$.invalid_date}),W}let n=new Ke,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:$.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:$.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ie.assertNever(o);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:L.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:L.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}};An.create=t=>new An({checks:[],coerce:t?.coerce||!1,typeName:R.ZodDate,...X(t)});Cs=class extends ee{_parse(e){if(this._getType(e)!==M.symbol){let n=this._getOrReturnCtx(e);return A(n,{code:$.invalid_type,expected:M.symbol,received:n.parsedType}),W}return st(e.data)}};Cs.create=t=>new Cs({typeName:R.ZodSymbol,...X(t)});Nn=class extends ee{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:$.invalid_type,expected:M.undefined,received:n.parsedType}),W}return st(e.data)}};Nn.create=t=>new Nn({typeName:R.ZodUndefined,...X(t)});Dn=class extends ee{_parse(e){if(this._getType(e)!==M.null){let n=this._getOrReturnCtx(e);return A(n,{code:$.invalid_type,expected:M.null,received:n.parsedType}),W}return st(e.data)}};Dn.create=t=>new Dn({typeName:R.ZodNull,...X(t)});en=class extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return st(e.data)}};en.create=t=>new en({typeName:R.ZodAny,...X(t)});Or=class extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return st(e.data)}};Or.create=t=>new Or({typeName:R.ZodUnknown,...X(t)});rr=class extends ee{_parse(e){let r=this._getOrReturnCtx(e);return A(r,{code:$.invalid_type,expected:M.never,received:r.parsedType}),W}};rr.create=t=>new rr({typeName:R.ZodNever,...X(t)});Os=class extends ee{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:$.invalid_type,expected:M.void,received:n.parsedType}),W}return st(e.data)}};Os.create=t=>new Os({typeName:R.ZodVoid,...X(t)});Ir=class t extends ee{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==M.array)return A(r,{code:$.invalid_type,expected:M.array,received:r.parsedType}),W;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(A(r,{code:i?$.too_big:$.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(A(r,{code:$.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(A(r,{code:$.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new Ut(r,i,r.path,a)))).then(i=>Ke.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new Ut(r,i,r.path,a)));return Ke.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:L.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:L.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:L.toString(r)}})}nonempty(e){return this.min(1,e)}};Ir.create=(t,e)=>new Ir({type:t,minLength:null,maxLength:null,exactLength:null,typeName:R.ZodArray,...X(e)});bt=class t extends ee{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=ie.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==M.object){let u=this._getOrReturnCtx(e);return A(u,{code:$.invalid_type,expected:M.object,received:u.parsedType}),W}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof rr&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let d=o[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new Ut(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof rr){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(u==="strict")a.length>0&&(A(s,{code:$.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 d of a){let l=s.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new Ut(s,l,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,m=await d.value;u.push({key:l,value:m,alwaysSet:d.alwaysSet})}return u}).then(u=>Ke.mergeObjectSync(n,u)):Ke.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return L.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:L.errToObj(e).message??s}:{message:s}}}:{}})}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:R.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 ie.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 ie.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Rs(this)}partial(e){let r={};for(let n of ie.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ie.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof vt;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return bx(ie.objectKeys(this.shape))}};bt.create=(t,e)=>new bt({shape:()=>t,unknownKeys:"strip",catchall:rr.create(),typeName:R.ZodObject,...X(e)});bt.strictCreate=(t,e)=>new bt({shape:()=>t,unknownKeys:"strict",catchall:rr.create(),typeName:R.ZodObject,...X(e)});bt.lazycreate=(t,e)=>new bt({shape:t,unknownKeys:"strip",catchall:rr.create(),typeName:R.ZodObject,...X(e)});Mn=class extends ee{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new xt(a.ctx.common.issues));return A(r,{code:$.invalid_union,unionErrors:i}),W}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new xt(c));return A(r,{code:$.invalid_union,unionErrors:a}),W}}get options(){return this._def.options}};Mn.create=(t,e)=>new Mn({options:t,typeName:R.ZodUnion,...X(e)});Cr=t=>t instanceof zn?Cr(t.schema):t instanceof Ht?Cr(t.innerType()):t instanceof Ln?[t.value]:t instanceof Fn?t.options:t instanceof Un?ie.objectValues(t.enum):t instanceof Hn?Cr(t._def.innerType):t instanceof Nn?[void 0]:t instanceof Dn?[null]:t instanceof vt?[void 0,...Cr(t.unwrap())]:t instanceof xr?[null,...Cr(t.unwrap())]:t instanceof Mo||t instanceof Bn?Cr(t.unwrap()):t instanceof Zn?Cr(t._def.innerType):[],Na=class t extends ee{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.object)return A(r,{code:$.invalid_type,expected:M.object,received:r.parsedType}),W;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(A(r,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=Cr(o.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(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:R.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...X(n)})}};jn=class extends ee{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(Ia(o)||Ia(i))return W;let a=bd(o.value,i.value);return a.valid?((Aa(o)||Aa(i))&&r.dirty(),{status:r.value,value:a.data}):(A(n,{code:$.invalid_intersection_types}),W)};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(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};jn.create=(t,e,r)=>new jn({left:t,right:e,typeName:R.ZodIntersection,...X(r)});_r=class t extends ee{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return A(n,{code:$.invalid_type,expected:M.array,received:n.parsedType}),W;if(n.data.length<this._def.items.length)return A(n,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&n.data.length>this._def.items.length&&(A(n,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ut(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>Ke.mergeArray(r,i)):Ke.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};_r.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _r({items:t,typeName:R.ZodTuple,rest:null,...X(e)})};Da=class t extends ee{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!==M.object)return A(n,{code:$.invalid_type,expected:M.object,received:n.parsedType}),W;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new Ut(n,a,n.path,a)),value:i._parse(new Ut(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ke.mergeObjectAsync(r,s):Ke.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ee?new t({keyType:e,valueType:r,typeName:R.ZodRecord,...X(n)}):new t({keyType:Qr.create(),valueType:e,typeName:R.ZodRecord,...X(r)})}},Is=class extends ee{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!==M.map)return A(n,{code:$.invalid_type,expected:M.map,received:n.parsedType}),W;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new Ut(n,a,n.path,[u,"key"])),value:o._parse(new Ut(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,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return W;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return W;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};Is.create=(t,e,r)=>new Is({valueType:e,keyType:t,typeName:R.ZodMap,...X(r)});As=class t extends ee{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return A(n,{code:$.invalid_type,expected:M.set,received:n.parsedType}),W;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(A(n,{code:$.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(A(n,{code:$.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let u=new Set;for(let d of c){if(d.status==="aborted")return W;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new Ut(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:L.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:L.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};As.create=(t,e)=>new As({valueType:t,minSize:null,maxSize:null,typeName:R.ZodSet,...X(e)});Ma=class t extends ee{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.function)return A(r,{code:$.invalid_type,expected:M.function,received:r.parsedType}),W;function n(a,c){return Do({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ts(),Rr].filter(u=>!!u),issueData:{code:$.invalid_arguments,argumentsError:c}})}function s(a,c){return Do({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ts(),Rr].filter(u=>!!u),issueData:{code:$.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof tn){let a=this;return st(async function(...c){let u=new xt([]),d=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(f=>{throw u.addIssue(s(l,f)),u})})}else{let a=this;return st(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new xt([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new xt([s(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:_r.create(e).rest(Or.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||_r.create([]).rest(Or.create()),returns:r||Or.create(),typeName:R.ZodFunction,...X(n)})}},zn=class extends ee{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})}};zn.create=(t,e)=>new zn({getter:t,typeName:R.ZodLazy,...X(e)});Ln=class extends ee{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return A(r,{received:r.data,code:$.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ln.create=(t,e)=>new Ln({value:t,typeName:R.ZodLiteral,...X(e)});Fn=class t extends ee{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return A(r,{expected:ie.joinValues(n),received:r.parsedType,code:$.invalid_type}),W}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 A(r,{received:r.data,code:$.invalid_enum_value,options:n}),W}return st(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})}};Fn.create=bx;Un=class extends ee{_parse(e){let r=ie.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let s=ie.objectValues(r);return A(n,{expected:ie.joinValues(s),received:n.parsedType,code:$.invalid_type}),W}if(this._cache||(this._cache=new Set(ie.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ie.objectValues(r);return A(n,{received:n.data,code:$.invalid_enum_value,options:s}),W}return st(e.data)}get enum(){return this._def.values}};Un.create=(t,e)=>new Un({values:t,typeName:R.ZodNativeEnum,...X(e)});tn=class extends ee{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return A(r,{code:$.invalid_type,expected:M.promise,received:r.parsedType}),W;let n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return st(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};tn.create=(t,e)=>new tn({type:t,typeName:R.ZodPromise,...X(e)});Ht=class extends ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===R.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{A(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return W;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?W:c.status==="dirty"?Rn(c.value):r.value==="dirty"?Rn(c.value):c});{if(r.value==="aborted")return W;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?W:a.status==="dirty"?Rn(a.value):r.value==="dirty"?Rn(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);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"?W:(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"?W:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Xr(i))return W;let a=s.transform(i.value,o);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=>Xr(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):W);ie.assertNever(s)}};Ht.create=(t,e,r)=>new Ht({schema:t,typeName:R.ZodEffects,effect:e,...X(r)});Ht.createWithPreprocess=(t,e,r)=>new Ht({schema:e,effect:{type:"preprocess",transform:t},typeName:R.ZodEffects,...X(r)});vt=class extends ee{_parse(e){return this._getType(e)===M.undefined?st(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};vt.create=(t,e)=>new vt({innerType:t,typeName:R.ZodOptional,...X(e)});xr=class extends ee{_parse(e){return this._getType(e)===M.null?st(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xr.create=(t,e)=>new xr({innerType:t,typeName:R.ZodNullable,...X(e)});Hn=class extends ee{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Hn.create=(t,e)=>new Hn({innerType:t,typeName:R.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});Zn=class extends ee{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ps(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new xt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new xt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Zn.create=(t,e)=>new Zn({innerType:t,typeName:R.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});Ns=class extends ee{_parse(e){if(this._getType(e)!==M.nan){let n=this._getOrReturnCtx(e);return A(n,{code:$.invalid_type,expected:M.nan,received:n.parsedType}),W}return{status:"valid",value:e.data}}};Ns.create=t=>new Ns({typeName:R.ZodNaN,...X(t)});kR=Symbol("zod_brand"),Mo=class extends ee{_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}},jo=class t extends ee{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?W:o.status==="dirty"?(r.dirty(),Rn(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?W:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:R.ZodPipeline})}},Bn=class extends ee{_parse(e){let r=this._def.innerType._parse(e),n=s=>(Xr(s)&&(s.value=Object.freeze(s.value)),s);return Ps(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Bn.create=(t,e)=>new Bn({innerType:t,typeName:R.ZodReadonly,...X(e)});wR={object:bt.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"})(R||(R={}));ER=(t,e={message:`Input not instance of ${t.name}`})=>Sx(r=>r instanceof t,e),kx=Qr.create,wx=Cn.create,$R=Ns.create,TR=On.create,Ex=In.create,PR=An.create,RR=Cs.create,CR=Nn.create,OR=Dn.create,IR=en.create,AR=Or.create,NR=rr.create,DR=Os.create,MR=Ir.create,Sd=bt.create,jR=bt.strictCreate,zR=Mn.create,LR=Na.create,FR=jn.create,UR=_r.create,HR=Da.create,ZR=Is.create,BR=As.create,qR=Ma.create,VR=zn.create,WR=Ln.create,GR=Fn.create,KR=Un.create,JR=tn.create,YR=Ht.create,XR=vt.create,QR=xr.create,eC=Ht.createWithPreprocess,tC=jo.create,rC=()=>kx().optional(),nC=()=>wx().optional(),sC=()=>Ex().optional(),oC={string:(t=>Qr.create({...t,coerce:!0})),number:(t=>Cn.create({...t,coerce:!0})),boolean:(t=>In.create({...t,coerce:!0})),bigint:(t=>On.create({...t,coerce:!0})),date:(t=>An.create({...t,coerce:!0}))},iC=W});var U={};Le(U,{BRAND:()=>kR,DIRTY:()=>Rn,EMPTY_PATH:()=>tR,INVALID:()=>W,NEVER:()=>iC,OK:()=>st,ParseStatus:()=>Ke,Schema:()=>ee,ZodAny:()=>en,ZodArray:()=>Ir,ZodBigInt:()=>On,ZodBoolean:()=>In,ZodBranded:()=>Mo,ZodCatch:()=>Zn,ZodDate:()=>An,ZodDefault:()=>Hn,ZodDiscriminatedUnion:()=>Na,ZodEffects:()=>Ht,ZodEnum:()=>Fn,ZodError:()=>xt,ZodFirstPartyTypeKind:()=>R,ZodFunction:()=>Ma,ZodIntersection:()=>jn,ZodIssueCode:()=>$,ZodLazy:()=>zn,ZodLiteral:()=>Ln,ZodMap:()=>Is,ZodNaN:()=>Ns,ZodNativeEnum:()=>Un,ZodNever:()=>rr,ZodNull:()=>Dn,ZodNullable:()=>xr,ZodNumber:()=>Cn,ZodObject:()=>bt,ZodOptional:()=>vt,ZodParsedType:()=>M,ZodPipeline:()=>jo,ZodPromise:()=>tn,ZodReadonly:()=>Bn,ZodRecord:()=>Da,ZodSchema:()=>ee,ZodSet:()=>As,ZodString:()=>Qr,ZodSymbol:()=>Cs,ZodTransformer:()=>Ht,ZodTuple:()=>_r,ZodType:()=>ee,ZodUndefined:()=>Nn,ZodUnion:()=>Mn,ZodUnknown:()=>Or,ZodVoid:()=>Os,addIssueToContext:()=>A,any:()=>IR,array:()=>MR,bigint:()=>TR,boolean:()=>Ex,coerce:()=>oC,custom:()=>Sx,date:()=>PR,datetimeRegex:()=>vx,defaultErrorMap:()=>Rr,discriminatedUnion:()=>LR,effect:()=>YR,enum:()=>GR,function:()=>qR,getErrorMap:()=>Ts,getParsedType:()=>yr,instanceof:()=>ER,intersection:()=>FR,isAborted:()=>Ia,isAsync:()=>Ps,isDirty:()=>Aa,isValid:()=>Xr,late:()=>wR,lazy:()=>VR,literal:()=>WR,makeIssue:()=>Do,map:()=>ZR,nan:()=>$R,nativeEnum:()=>KR,never:()=>NR,null:()=>OR,nullable:()=>QR,number:()=>wx,object:()=>Sd,objectUtil:()=>yd,oboolean:()=>sC,onumber:()=>nC,optional:()=>XR,ostring:()=>rC,pipeline:()=>tC,preprocess:()=>eC,promise:()=>JR,quotelessJson:()=>XP,record:()=>HR,set:()=>BR,setErrorMap:()=>eR,strictObject:()=>jR,string:()=>kx,symbol:()=>RR,transformer:()=>YR,tuple:()=>UR,undefined:()=>CR,union:()=>zR,unknown:()=>AR,util:()=>ie,void:()=>DR});var ja=v(()=>{Oa();xd();fx();No();$x();Ca()});var zo=v(()=>{ja()});function k(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 d in i.prototype)d in a||Object.defineProperty(a,d,{value:i.prototype[d].bind(a)});a._zod.constr=i,a._zod.def=c}let s=r?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function i(a){var c;let u=r?.Parent?new o:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();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 Ct(t){return t&&Object.assign(za,t),za}var cC,Ar,za,Ds=v(()=>{cC=Object.freeze({status:"aborted"});Ar=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},za={}});var ae={};Le(ae,{BIGINT_FORMAT_RANGES:()=>Px,Class:()=>wd,NUMBER_FORMAT_RANGES:()=>Od,aborted:()=>Vn,allowsEval:()=>Pd,assert:()=>mC,assertEqual:()=>uC,assertIs:()=>dC,assertNever:()=>pC,assertNotEqual:()=>lC,assignProp:()=>Td,cached:()=>Uo,captureStackTrace:()=>Fa,cleanEnum:()=>$C,cleanRegex:()=>Zo,clone:()=>Ot,createTransparentProxy:()=>xC,defineLazy:()=>ke,esc:()=>qn,escapeRegex:()=>rn,extend:()=>SC,finalizeIssue:()=>nr,floatSafeRemainder:()=>$d,getElementAtPath:()=>fC,getEnumValues:()=>Fo,getLengthableOrigin:()=>Bo,getParsedType:()=>_C,getSizableOrigin:()=>Rx,isObject:()=>Ms,isPlainObject:()=>js,issue:()=>Id,joinValues:()=>La,jsonStringifyReplacer:()=>Ed,merge:()=>kC,normalizeParams:()=>G,nullish:()=>Ho,numKeys:()=>yC,omit:()=>bC,optionalKeys:()=>Cd,partial:()=>wC,pick:()=>vC,prefixIssues:()=>vr,primitiveTypes:()=>Tx,promiseAllObject:()=>hC,propertyKeyTypes:()=>Rd,randomString:()=>gC,required:()=>EC,stringifyPrimitive:()=>Ua,unwrapMessage:()=>Lo});function uC(t){return t}function lC(t){return t}function dC(t){}function pC(t){throw new Error}function mC(t){}function Fo(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function La(t,e="|"){return t.map(r=>Ua(r)).join(e)}function Ed(t,e){return typeof e=="bigint"?e.toString():e}function Uo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ho(t){return t==null}function Zo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function $d(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function ke(t,e,r){Object.defineProperty(t,e,{get(){{let s=r();return t[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function Td(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function fC(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function hC(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let s={};for(let o=0;o<e.length;o++)s[e[o]]=n[o];return s})}function gC(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function qn(t){return JSON.stringify(t)}function Ms(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function js(t){if(Ms(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Ms(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function yC(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function rn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ot(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function G(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 xC(t){let e;return new Proxy({},{get(r,n,s){return e??(e=t()),Reflect.get(e,n,s)},set(r,n,s,o){return e??(e=t()),Reflect.set(e,n,s,o)},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,s){return e??(e=t()),Reflect.defineProperty(e,n,s)}})}function Ua(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Cd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function vC(t,e){let r={},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return Ot(t,{...t._zod.def,shape:r,checks:[]})}function bC(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return Ot(t,{...t._zod.def,shape:r,checks:[]})}function SC(t,e){if(!js(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 Td(this,"shape",n),n},checks:[]};return Ot(t,r)}function kC(t,e){return Ot(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Td(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function wC(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=t?new t({type:"optional",innerType:n[o]}):n[o])}else for(let o in n)s[o]=t?new t({type:"optional",innerType:n[o]}):n[o];return Ot(e,{...e._zod.def,shape:s,checks:[]})}function EC(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:n[o]}))}else for(let o in n)s[o]=new t({type:"nonoptional",innerType:n[o]});return Ot(e,{...e._zod.def,shape:s,checks:[]})}function Vn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function vr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Lo(t){return typeof t=="string"?t:t?.message}function nr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=Lo(t.inst?._zod.def?.error?.(t))??Lo(e?.error?.(t))??Lo(r.customError?.(t))??Lo(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Rx(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Bo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Id(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function $C(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Fa,Pd,_C,Rd,Tx,Od,Px,wd,br=v(()=>{Fa=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Pd=Uo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});_C=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}`)}},Rd=new Set(["string","number","symbol"]),Tx=new Set(["string","number","bigint","boolean","symbol","undefined"]);Od={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]},Px={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};wd=class{constructor(...e){}}});function Ad(t,e=r=>r.message){let r={},n=[];for(let s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function Nd(t,e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>s({issues:a}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({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 s(t),n}var Cx,Ha,qo,Dd=v(()=>{Ds();br();Cx=(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,Ed,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ha=k("$ZodError",Cx),qo=k("$ZodError",Cx,{Parent:Error})});var Md,jd,zd,Ld,Fd,Wn,Ud,Gn,Hd=v(()=>{Ds();Dd();br();Md=t=>(e,r,n,s)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Ar;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>nr(c,o,Ct())));throw Fa(a,s?.callee),a}return i.value},jd=Md(qo),zd=t=>async(e,r,n,s)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>nr(c,o,Ct())));throw Fa(a,s?.callee),a}return i.value},Ld=zd(qo),Fd=t=>(e,r,n)=>{let s=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Ar;return o.issues.length?{success:!1,error:new(t??Ha)(o.issues.map(i=>nr(i,s,Ct())))}:{success:!0,data:o.value}},Wn=Fd(qo),Ud=t=>async(e,r,n)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(i=>nr(i,s,Ct())))}:{success:!0,data:o.value}},Gn=Ud(qo)});function Fx(){return new RegExp(PC,"u")}function Jx(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 Yx(t){return new RegExp(`^${Jx(t)}$`)}function Xx(t){let e=Jx({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(`^${Gx}T(?:${n})$`)}var Ox,Ix,Ax,Nx,Dx,Mx,jx,zx,Zd,Lx,PC,Ux,Hx,Zx,Bx,qx,Bd,Vx,Wx,Gx,Kx,Qx,ev,tv,rv,nv,sv,ov,Ba=v(()=>{Ox=/^[cC][^\s-]{8,}$/,Ix=/^[0-9a-z]+$/,Ax=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Nx=/^[0-9a-vA-V]{20}$/,Dx=/^[A-Za-z0-9]{27}$/,Mx=/^[a-zA-Z0-9_-]{21}$/,jx=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,zx=/^([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})$/,Zd=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)$/,Lx=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,PC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Ux=/^(?:(?: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])$/,Hx=/^(([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})$/,Zx=/^((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])$/,Bx=/^(([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])$/,qx=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Bd=/^[A-Za-z0-9_-]*$/,Vx=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Wx=/^\+(?:[0-9]){6,14}[0-9]$/,Gx="(?:(?:\\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])))",Kx=new RegExp(`^${Gx}$`);Qx=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},ev=/^\d+$/,tv=/^-?\d+(?:\.\d+)?/i,rv=/true|false/i,nv=/null/i,sv=/^[^A-Z]*$/,ov=/^[^a-z]*$/});var Je,iv,qd,Vd,av,cv,uv,lv,dv,Vo,pv,mv,fv,hv,gv,yv,_v,qa=v(()=>{Ds();Ba();br();Je=k("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),iv={number:"number",bigint:"bigint",object:"date"},qd=k("$ZodCheckLessThan",(t,e)=>{Je.init(t,e);let r=iv[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?s.maximum=e.value:s.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})}}),Vd=k("$ZodCheckGreaterThan",(t,e)=>{Je.init(t,e);let r=iv[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?s.minimum=e.value:s.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})}}),av=k("$ZodCheckMultipleOf",(t,e)=>{Je.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):$d(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})}}),cv=k("$ZodCheckNumberFormat",(t,e)=>{Je.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,o]=Od[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=s,a.maximum=o,r&&(a.pattern=ev)}),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<s&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),a>o&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:t})}}),uv=k("$ZodCheckMaxLength",(t,e)=>{var r;Je.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Ho(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let s=n.value;if(s.length<=e.maximum)return;let i=Bo(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),lv=k("$ZodCheckMinLength",(t,e)=>{var r;Je.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Ho(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let s=n.value;if(s.length>=e.minimum)return;let i=Bo(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),dv=k("$ZodCheckLengthEquals",(t,e)=>{var r;Je.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Ho(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{let s=n.value,o=s.length;if(o===e.length)return;let i=Bo(s),a=o>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})}}),Vo=k("$ZodCheckStringFormat",(t,e)=>{var r,n;Je.init(t,e),t._zod.onattach.push(s=>{let o=s._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),pv=k("$ZodCheckRegex",(t,e)=>{Vo.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})}}),mv=k("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=sv),Vo.init(t,e)}),fv=k("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=ov),Vo.init(t,e)}),hv=k("$ZodCheckIncludes",(t,e)=>{Je.init(t,e);let r=rn(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{let o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),gv=k("$ZodCheckStartsWith",(t,e)=>{Je.init(t,e);let r=new RegExp(`^${rn(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.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})}}),yv=k("$ZodCheckEndsWith",(t,e)=>{Je.init(t,e);let r=new RegExp(`.*${rn(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.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})}}),_v=k("$ZodCheckOverwrite",(t,e)=>{Je.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Va,Wd=v(()=>{Va=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(`
|
|
33
|
+
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.`}}});var xd={};Fe(xd,{PLATFORM_ENV_VARS:()=>hx,detectPlatform:()=>nr,getAdapter:()=>Ao,getSessionDirSegments:()=>_d});import{existsSync as Rt}from"node:fs";import{resolve as Ct}from"node:path";import{homedir as aR}from"node:os";function _d(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"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function nr(t){if(t?.name){let n=n_[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"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,s]of hx)if(s.some(o=>process.env[o]))return{platform:n,confidence:"high",reason:`${s.join(" or ")} env var set`};let r=aR();return Rt(Ct(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Rt(Ct(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Rt(Ct(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Rt(Ct(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Rt(Ct(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Rt(Ct(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Rt(Ct(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Rt(Ct(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Rt(Ct(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Rt(Ct(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Rt(Ct(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Rt(Ct(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Rt(Ct(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 Ao(t){let e=t??nr().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Nl(),Al));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(h_(),f_));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(x_(),__));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(S_(),b_));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(P_(),T_));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(A_(),I_));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(j_(),M_));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(V_(),q_));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(K_(),G_));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(rx(),tx));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(ix(),ox));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(lx(),ux));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(px(),dx));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(fx(),mx));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Nl(),Al));return new r}}}var hx,No=v(()=>{"use strict";s_();hx=[["claude-code",["CLAUDE_PROJECT_DIR","CLAUDE_SESSION_ID"]],["antigravity",["ANTIGRAVITY_CLI_ALIAS"]],["cursor",["CURSOR_TRACE_ID","CURSOR_CLI"]],["kilo",["KILO","KILO_PID"]],["opencode",["OPENCODE","OPENCODE_PID"]],["zed",["ZED_SESSION_ID","ZED_TERM"]],["codex",["CODEX_THREAD_ID","CODEX_CI"]],["gemini-cli",["GEMINI_PROJECT_DIR","GEMINI_CLI"]],["vscode-copilot",["VSCODE_PID","VSCODE_CWD"]],["jetbrains-copilot",["IDEA_INITIAL_DIRECTORY"]],["qwen-code",["QWEN_PROJECT_DIR"]],["omp",["PI_CODING_AGENT_DIR"]],["pi",["PI_PROJECT_DIR"]]]});var ie,vd,M,_r,Do=v(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ie||(ie={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(vd||(vd={}));M=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),_r=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}}});var $,cR,xt,Ca=v(()=>{Do();$=ie.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"]),cR=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),xt=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(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(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 s(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,ie.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};xt.create=t=>new xt(t)});var uR,Cr,bd=v(()=>{Ca();Do();uR=(t,e)=>{let r;switch(t.code){case $.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case $.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ie.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${ie.joinValues(t.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ie.joinValues(t.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${ie.joinValues(t.options)}, received '${t.received}'`;break;case $.invalid_arguments:r="Invalid function arguments";break;case $.invalid_return_type:r="Invalid function return type";break;case $.invalid_date:r="Invalid date";break;case $.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}"`:ie.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case $.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 $.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 $.custom:r="Invalid input";break;case $.invalid_intersection_types:r="Intersection results could not be merged";break;case $.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case $.not_finite:r="Number must be finite";break;default:r=e.defaultError,ie.assertNever(t)}return{message:r}},Cr=uR});function lR(t){gx=t}function Rs(){return gx}var gx,Oa=v(()=>{bd();gx=Cr});function N(t,e){let r=Rs(),n=Mo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Cr?void 0:Cr].filter(s=>!!s)});t.common.issues.push(n)}var Mo,dR,Ke,W,Cn,st,Ia,Aa,Qr,Cs,Sd=v(()=>{Oa();bd();Mo=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},dR=[];Ke=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 s of r){if(s.status==="aborted")return W;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return W;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},W=Object.freeze({status:"aborted"}),Cn=t=>({status:"dirty",value:t}),st=t=>({status:"valid",value:t}),Ia=t=>t.status==="aborted",Aa=t=>t.status==="dirty",Qr=t=>t.status==="valid",Cs=t=>typeof Promise<"u"&&t instanceof Promise});var yx=v(()=>{});var L,_x=v(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}))});function X(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=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:s}:{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:s}}function Sx(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 PR(t){return new RegExp(`^${Sx(t)}$`)}function kx(t){let e=`${bx}T${Sx(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 RR(t,e){return!!((e==="v4"||!e)&&bR.test(t)||(e==="v6"||!e)&&kR.test(t))}function CR(t,e){if(!yR.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,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function OR(t,e){return!!((e==="v4"||!e)&&SR.test(t)||(e==="v6"||!e)&&wR.test(t))}function IR(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function Os(t){if(t instanceof bt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=vt.create(Os(n))}return new bt({...t._def,shape:()=>e})}else return t instanceof Ar?new Ar({...t._def,type:Os(t.element)}):t instanceof vt?vt.create(Os(t.unwrap())):t instanceof vr?vr.create(Os(t.unwrap())):t instanceof xr?xr.create(t.items.map(e=>Os(e))):t}function wd(t,e){let r=_r(t),n=_r(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){let s=ie.objectKeys(e),o=ie.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=wd(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===M.array&&n===M.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=wd(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function wx(t,e){return new Un({values:t,typeName:R.ZodEnum,...X(e)})}function vx(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Ex(t,e={},r){return t?tn.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=vx(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=vx(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):tn.create()}var Ht,xx,ee,pR,mR,fR,hR,gR,yR,_R,xR,vR,kd,bR,SR,kR,wR,ER,$R,bx,TR,en,On,In,An,Nn,Is,Dn,Mn,tn,Ir,sr,As,Ar,bt,jn,Or,Na,zn,xr,Da,Ns,Ds,Ma,Ln,Fn,Un,Hn,rn,Zt,vt,vr,Zn,Bn,Ms,AR,jo,zo,qn,NR,R,DR,$x,Tx,MR,jR,Px,zR,LR,FR,UR,HR,ZR,BR,qR,VR,Ed,WR,GR,KR,JR,YR,XR,QR,eC,tC,rC,nC,sC,oC,iC,aC,cC,uC,lC,dC,pC,mC,fC,hC,gC,Rx=v(()=>{Ca();Oa();_x();Sd();Do();Ht=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}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}},xx=(t,e)=>{if(Qr(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 xt(t.common.issues);return this._error=r,this._error}}};ee=class{get description(){return this._def.description}_getType(e){return _r(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:_r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ke,ctx:{common:e.parent.common,data:e.data,parsedType:_r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Cs(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:_r(e)},s=this._parseSync({data:e,path:n.path,parent:n});return xx(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:_r(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Qr(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=>Qr(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:_r(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(Cs(s)?s:Promise.resolve(s));return xx(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:$.custom,...n(s)});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,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Zt({schema:this,typeName:R.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 vt.create(this,this._def)}nullable(){return vr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ar.create(this)}promise(){return rn.create(this,this._def)}or(e){return jn.create([this,e],this._def)}and(e){return zn.create(this,e,this._def)}transform(e){return new Zt({...X(this._def),schema:this,typeName:R.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Zn({...X(this._def),innerType:this,defaultValue:r,typeName:R.ZodDefault})}brand(){return new jo({typeName:R.ZodBranded,type:this,...X(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Bn({...X(this._def),innerType:this,catchValue:r,typeName:R.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return zo.create(this,e)}readonly(){return qn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},pR=/^c[^\s-]{8,}$/i,mR=/^[0-9a-z]+$/,fR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,hR=/^[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,gR=/^[a-z0-9_-]{21}$/i,yR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,_R=/^[-+]?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)?)??$/,xR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,vR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",bR=/^(?:(?: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])$/,SR=/^(?:(?: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])$/,kR=/^(([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]))$/,wR=/^(([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])$/,ER=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$R=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,bx="((\\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])))",TR=new RegExp(`^${bx}$`);en=class t extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let o=this._getOrReturnCtx(e);return N(o,{code:$.invalid_type,expected:M.string,received:o.parsedType}),W}let n=new Ke,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:$.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:$.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?N(s,{code:$.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&N(s,{code:$.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")xR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"email",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")kd||(kd=new RegExp(vR,"u")),kd.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"emoji",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")hR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"uuid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")gR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"nanoid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")pR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cuid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")mR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cuid2",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")fR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"ulid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),N(s,{validation:"url",code:$.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"regex",code:$.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),N(s,{code:$.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),N(s,{code:$.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),N(s,{code:$.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?kx(o).test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:$.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?TR.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:$.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?PR(o).test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:$.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?_R.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"duration",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?RR(e.data,o.version)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"ip",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?CR(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"jwt",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?OR(e.data,o.version)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cidr",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?ER.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?$R.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64url",code:$.invalid_string,message:o.message}),n.dirty()):ie.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:$.invalid_string,...L.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.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,...L.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,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...L.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...L.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...L.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...L.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...L.errToObj(r)})}nonempty(e){return this.min(1,L.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}};en.create=t=>new en({checks:[],typeName:R.ZodString,coerce:t?.coerce??!1,...X(t)});On=class t extends ee{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)!==M.number){let o=this._getOrReturnCtx(e);return N(o,{code:$.invalid_type,expected:M.number,received:o.parsedType}),W}let n,s=new Ke;for(let o of this._def.checks)o.kind==="int"?ie.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:$.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:$.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:$.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?IR(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),N(n,{code:$.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:$.not_finite,message:o.message}),s.dirty()):ie.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.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"&&ie.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)}};On.create=t=>new On({checks:[],typeName:R.ZodNumber,coerce:t?.coerce||!1,...X(t)});In=class t extends ee{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)!==M.bigint)return this._getInvalidInput(e);let n,s=new Ke;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:$.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:$.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),N(n,{code:$.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ie.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return N(r,{code:$.invalid_type,expected:M.bigint,received:r.parsedType}),W}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.toString(s)}]})}_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:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.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}};In.create=t=>new In({checks:[],typeName:R.ZodBigInt,coerce:t?.coerce??!1,...X(t)});An=class extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let n=this._getOrReturnCtx(e);return N(n,{code:$.invalid_type,expected:M.boolean,received:n.parsedType}),W}return st(e.data)}};An.create=t=>new An({typeName:R.ZodBoolean,coerce:t?.coerce||!1,...X(t)});Nn=class t extends ee{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let o=this._getOrReturnCtx(e);return N(o,{code:$.invalid_type,expected:M.date,received:o.parsedType}),W}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return N(o,{code:$.invalid_date}),W}let n=new Ke,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:$.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:$.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ie.assertNever(o);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:L.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:L.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}};Nn.create=t=>new Nn({checks:[],coerce:t?.coerce||!1,typeName:R.ZodDate,...X(t)});Is=class extends ee{_parse(e){if(this._getType(e)!==M.symbol){let n=this._getOrReturnCtx(e);return N(n,{code:$.invalid_type,expected:M.symbol,received:n.parsedType}),W}return st(e.data)}};Is.create=t=>new Is({typeName:R.ZodSymbol,...X(t)});Dn=class extends ee{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:$.invalid_type,expected:M.undefined,received:n.parsedType}),W}return st(e.data)}};Dn.create=t=>new Dn({typeName:R.ZodUndefined,...X(t)});Mn=class extends ee{_parse(e){if(this._getType(e)!==M.null){let n=this._getOrReturnCtx(e);return N(n,{code:$.invalid_type,expected:M.null,received:n.parsedType}),W}return st(e.data)}};Mn.create=t=>new Mn({typeName:R.ZodNull,...X(t)});tn=class extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return st(e.data)}};tn.create=t=>new tn({typeName:R.ZodAny,...X(t)});Ir=class extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return st(e.data)}};Ir.create=t=>new Ir({typeName:R.ZodUnknown,...X(t)});sr=class extends ee{_parse(e){let r=this._getOrReturnCtx(e);return N(r,{code:$.invalid_type,expected:M.never,received:r.parsedType}),W}};sr.create=t=>new sr({typeName:R.ZodNever,...X(t)});As=class extends ee{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:$.invalid_type,expected:M.void,received:n.parsedType}),W}return st(e.data)}};As.create=t=>new As({typeName:R.ZodVoid,...X(t)});Ar=class t extends ee{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==M.array)return N(r,{code:$.invalid_type,expected:M.array,received:r.parsedType}),W;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(N(r,{code:i?$.too_big:$.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(N(r,{code:$.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(N(r,{code:$.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new Ht(r,i,r.path,a)))).then(i=>Ke.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new Ht(r,i,r.path,a)));return Ke.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:L.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:L.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:L.toString(r)}})}nonempty(e){return this.min(1,e)}};Ar.create=(t,e)=>new Ar({type:t,minLength:null,maxLength:null,exactLength:null,typeName:R.ZodArray,...X(e)});bt=class t extends ee{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=ie.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==M.object){let u=this._getOrReturnCtx(e);return N(u,{code:$.invalid_type,expected:M.object,received:u.parsedType}),W}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof sr&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let d=o[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new Ht(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof sr){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(u==="strict")a.length>0&&(N(s,{code:$.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 d of a){let l=s.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new Ht(s,l,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,m=await d.value;u.push({key:l,value:m,alwaysSet:d.alwaysSet})}return u}).then(u=>Ke.mergeObjectSync(n,u)):Ke.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return L.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:L.errToObj(e).message??s}:{message:s}}}:{}})}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:R.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 ie.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 ie.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Os(this)}partial(e){let r={};for(let n of ie.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ie.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof vt;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return wx(ie.objectKeys(this.shape))}};bt.create=(t,e)=>new bt({shape:()=>t,unknownKeys:"strip",catchall:sr.create(),typeName:R.ZodObject,...X(e)});bt.strictCreate=(t,e)=>new bt({shape:()=>t,unknownKeys:"strict",catchall:sr.create(),typeName:R.ZodObject,...X(e)});bt.lazycreate=(t,e)=>new bt({shape:t,unknownKeys:"strip",catchall:sr.create(),typeName:R.ZodObject,...X(e)});jn=class extends ee{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new xt(a.ctx.common.issues));return N(r,{code:$.invalid_union,unionErrors:i}),W}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new xt(c));return N(r,{code:$.invalid_union,unionErrors:a}),W}}get options(){return this._def.options}};jn.create=(t,e)=>new jn({options:t,typeName:R.ZodUnion,...X(e)});Or=t=>t instanceof Ln?Or(t.schema):t instanceof Zt?Or(t.innerType()):t instanceof Fn?[t.value]:t instanceof Un?t.options:t instanceof Hn?ie.objectValues(t.enum):t instanceof Zn?Or(t._def.innerType):t instanceof Dn?[void 0]:t instanceof Mn?[null]:t instanceof vt?[void 0,...Or(t.unwrap())]:t instanceof vr?[null,...Or(t.unwrap())]:t instanceof jo||t instanceof qn?Or(t.unwrap()):t instanceof Bn?Or(t._def.innerType):[],Na=class t extends ee{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.object)return N(r,{code:$.invalid_type,expected:M.object,received:r.parsedType}),W;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(N(r,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=Or(o.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(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:R.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...X(n)})}};zn=class extends ee{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(Ia(o)||Ia(i))return W;let a=wd(o.value,i.value);return a.valid?((Aa(o)||Aa(i))&&r.dirty(),{status:r.value,value:a.data}):(N(n,{code:$.invalid_intersection_types}),W)};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(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};zn.create=(t,e,r)=>new zn({left:t,right:e,typeName:R.ZodIntersection,...X(r)});xr=class t extends ee{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return N(n,{code:$.invalid_type,expected:M.array,received:n.parsedType}),W;if(n.data.length<this._def.items.length)return N(n,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&n.data.length>this._def.items.length&&(N(n,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ht(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>Ke.mergeArray(r,i)):Ke.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};xr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xr({items:t,typeName:R.ZodTuple,rest:null,...X(e)})};Da=class t extends ee{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!==M.object)return N(n,{code:$.invalid_type,expected:M.object,received:n.parsedType}),W;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new Ht(n,a,n.path,a)),value:i._parse(new Ht(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ke.mergeObjectAsync(r,s):Ke.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ee?new t({keyType:e,valueType:r,typeName:R.ZodRecord,...X(n)}):new t({keyType:en.create(),valueType:e,typeName:R.ZodRecord,...X(r)})}},Ns=class extends ee{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!==M.map)return N(n,{code:$.invalid_type,expected:M.map,received:n.parsedType}),W;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new Ht(n,a,n.path,[u,"key"])),value:o._parse(new Ht(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,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return W;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return W;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};Ns.create=(t,e,r)=>new Ns({valueType:e,keyType:t,typeName:R.ZodMap,...X(r)});Ds=class t extends ee{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return N(n,{code:$.invalid_type,expected:M.set,received:n.parsedType}),W;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(N(n,{code:$.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(N(n,{code:$.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let u=new Set;for(let d of c){if(d.status==="aborted")return W;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new Ht(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:L.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:L.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Ds.create=(t,e)=>new Ds({valueType:t,minSize:null,maxSize:null,typeName:R.ZodSet,...X(e)});Ma=class t extends ee{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.function)return N(r,{code:$.invalid_type,expected:M.function,received:r.parsedType}),W;function n(a,c){return Mo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Rs(),Cr].filter(u=>!!u),issueData:{code:$.invalid_arguments,argumentsError:c}})}function s(a,c){return Mo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Rs(),Cr].filter(u=>!!u),issueData:{code:$.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof rn){let a=this;return st(async function(...c){let u=new xt([]),d=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(f=>{throw u.addIssue(s(l,f)),u})})}else{let a=this;return st(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new xt([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new xt([s(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:xr.create(e).rest(Ir.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||xr.create([]).rest(Ir.create()),returns:r||Ir.create(),typeName:R.ZodFunction,...X(n)})}},Ln=class extends ee{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})}};Ln.create=(t,e)=>new Ln({getter:t,typeName:R.ZodLazy,...X(e)});Fn=class extends ee{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return N(r,{received:r.data,code:$.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:e.data}}get value(){return this._def.value}};Fn.create=(t,e)=>new Fn({value:t,typeName:R.ZodLiteral,...X(e)});Un=class t extends ee{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return N(r,{expected:ie.joinValues(n),received:r.parsedType,code:$.invalid_type}),W}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 N(r,{received:r.data,code:$.invalid_enum_value,options:n}),W}return st(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})}};Un.create=wx;Hn=class extends ee{_parse(e){let r=ie.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let s=ie.objectValues(r);return N(n,{expected:ie.joinValues(s),received:n.parsedType,code:$.invalid_type}),W}if(this._cache||(this._cache=new Set(ie.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ie.objectValues(r);return N(n,{received:n.data,code:$.invalid_enum_value,options:s}),W}return st(e.data)}get enum(){return this._def.values}};Hn.create=(t,e)=>new Hn({values:t,typeName:R.ZodNativeEnum,...X(e)});rn=class extends ee{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return N(r,{code:$.invalid_type,expected:M.promise,received:r.parsedType}),W;let n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return st(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};rn.create=(t,e)=>new rn({type:t,typeName:R.ZodPromise,...X(e)});Zt=class extends ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===R.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{N(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return W;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?W:c.status==="dirty"?Cn(c.value):r.value==="dirty"?Cn(c.value):c});{if(r.value==="aborted")return W;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?W:a.status==="dirty"?Cn(a.value):r.value==="dirty"?Cn(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);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"?W:(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"?W:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Qr(i))return W;let a=s.transform(i.value,o);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=>Qr(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):W);ie.assertNever(s)}};Zt.create=(t,e,r)=>new Zt({schema:t,typeName:R.ZodEffects,effect:e,...X(r)});Zt.createWithPreprocess=(t,e,r)=>new Zt({schema:e,effect:{type:"preprocess",transform:t},typeName:R.ZodEffects,...X(r)});vt=class extends ee{_parse(e){return this._getType(e)===M.undefined?st(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};vt.create=(t,e)=>new vt({innerType:t,typeName:R.ZodOptional,...X(e)});vr=class extends ee{_parse(e){return this._getType(e)===M.null?st(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};vr.create=(t,e)=>new vr({innerType:t,typeName:R.ZodNullable,...X(e)});Zn=class extends ee{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Zn.create=(t,e)=>new Zn({innerType:t,typeName:R.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});Bn=class extends ee{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Cs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new xt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new xt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Bn.create=(t,e)=>new Bn({innerType:t,typeName:R.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});Ms=class extends ee{_parse(e){if(this._getType(e)!==M.nan){let n=this._getOrReturnCtx(e);return N(n,{code:$.invalid_type,expected:M.nan,received:n.parsedType}),W}return{status:"valid",value:e.data}}};Ms.create=t=>new Ms({typeName:R.ZodNaN,...X(t)});AR=Symbol("zod_brand"),jo=class extends ee{_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}},zo=class t extends ee{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?W:o.status==="dirty"?(r.dirty(),Cn(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?W:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:R.ZodPipeline})}},qn=class extends ee{_parse(e){let r=this._def.innerType._parse(e),n=s=>(Qr(s)&&(s.value=Object.freeze(s.value)),s);return Cs(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};qn.create=(t,e)=>new qn({innerType:t,typeName:R.ZodReadonly,...X(e)});NR={object:bt.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"})(R||(R={}));DR=(t,e={message:`Input not instance of ${t.name}`})=>Ex(r=>r instanceof t,e),$x=en.create,Tx=On.create,MR=Ms.create,jR=In.create,Px=An.create,zR=Nn.create,LR=Is.create,FR=Dn.create,UR=Mn.create,HR=tn.create,ZR=Ir.create,BR=sr.create,qR=As.create,VR=Ar.create,Ed=bt.create,WR=bt.strictCreate,GR=jn.create,KR=Na.create,JR=zn.create,YR=xr.create,XR=Da.create,QR=Ns.create,eC=Ds.create,tC=Ma.create,rC=Ln.create,nC=Fn.create,sC=Un.create,oC=Hn.create,iC=rn.create,aC=Zt.create,cC=vt.create,uC=vr.create,lC=Zt.createWithPreprocess,dC=zo.create,pC=()=>$x().optional(),mC=()=>Tx().optional(),fC=()=>Px().optional(),hC={string:(t=>en.create({...t,coerce:!0})),number:(t=>On.create({...t,coerce:!0})),boolean:(t=>An.create({...t,coerce:!0})),bigint:(t=>In.create({...t,coerce:!0})),date:(t=>Nn.create({...t,coerce:!0}))},gC=W});var U={};Fe(U,{BRAND:()=>AR,DIRTY:()=>Cn,EMPTY_PATH:()=>dR,INVALID:()=>W,NEVER:()=>gC,OK:()=>st,ParseStatus:()=>Ke,Schema:()=>ee,ZodAny:()=>tn,ZodArray:()=>Ar,ZodBigInt:()=>In,ZodBoolean:()=>An,ZodBranded:()=>jo,ZodCatch:()=>Bn,ZodDate:()=>Nn,ZodDefault:()=>Zn,ZodDiscriminatedUnion:()=>Na,ZodEffects:()=>Zt,ZodEnum:()=>Un,ZodError:()=>xt,ZodFirstPartyTypeKind:()=>R,ZodFunction:()=>Ma,ZodIntersection:()=>zn,ZodIssueCode:()=>$,ZodLazy:()=>Ln,ZodLiteral:()=>Fn,ZodMap:()=>Ns,ZodNaN:()=>Ms,ZodNativeEnum:()=>Hn,ZodNever:()=>sr,ZodNull:()=>Mn,ZodNullable:()=>vr,ZodNumber:()=>On,ZodObject:()=>bt,ZodOptional:()=>vt,ZodParsedType:()=>M,ZodPipeline:()=>zo,ZodPromise:()=>rn,ZodReadonly:()=>qn,ZodRecord:()=>Da,ZodSchema:()=>ee,ZodSet:()=>Ds,ZodString:()=>en,ZodSymbol:()=>Is,ZodTransformer:()=>Zt,ZodTuple:()=>xr,ZodType:()=>ee,ZodUndefined:()=>Dn,ZodUnion:()=>jn,ZodUnknown:()=>Ir,ZodVoid:()=>As,addIssueToContext:()=>N,any:()=>HR,array:()=>VR,bigint:()=>jR,boolean:()=>Px,coerce:()=>hC,custom:()=>Ex,date:()=>zR,datetimeRegex:()=>kx,defaultErrorMap:()=>Cr,discriminatedUnion:()=>KR,effect:()=>aC,enum:()=>sC,function:()=>tC,getErrorMap:()=>Rs,getParsedType:()=>_r,instanceof:()=>DR,intersection:()=>JR,isAborted:()=>Ia,isAsync:()=>Cs,isDirty:()=>Aa,isValid:()=>Qr,late:()=>NR,lazy:()=>rC,literal:()=>nC,makeIssue:()=>Mo,map:()=>QR,nan:()=>MR,nativeEnum:()=>oC,never:()=>BR,null:()=>UR,nullable:()=>uC,number:()=>Tx,object:()=>Ed,objectUtil:()=>vd,oboolean:()=>fC,onumber:()=>mC,optional:()=>cC,ostring:()=>pC,pipeline:()=>dC,preprocess:()=>lC,promise:()=>iC,quotelessJson:()=>cR,record:()=>XR,set:()=>eC,setErrorMap:()=>lR,strictObject:()=>WR,string:()=>$x,symbol:()=>LR,transformer:()=>aC,tuple:()=>YR,undefined:()=>FR,union:()=>GR,unknown:()=>ZR,util:()=>ie,void:()=>qR});var ja=v(()=>{Oa();Sd();yx();Do();Rx();Ca()});var Lo=v(()=>{ja()});function k(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 d in i.prototype)d in a||Object.defineProperty(a,d,{value:i.prototype[d].bind(a)});a._zod.constr=i,a._zod.def=c}let s=r?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function i(a){var c;let u=r?.Parent?new o:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();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 Ot(t){return t&&Object.assign(za,t),za}var _C,Nr,za,js=v(()=>{_C=Object.freeze({status:"aborted"});Nr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},za={}});var ae={};Fe(ae,{BIGINT_FORMAT_RANGES:()=>Ox,Class:()=>Td,NUMBER_FORMAT_RANGES:()=>Nd,aborted:()=>Wn,allowsEval:()=>Od,assert:()=>kC,assertEqual:()=>xC,assertIs:()=>bC,assertNever:()=>SC,assertNotEqual:()=>vC,assignProp:()=>Cd,cached:()=>Ho,captureStackTrace:()=>Fa,cleanEnum:()=>MC,cleanRegex:()=>Bo,clone:()=>It,createTransparentProxy:()=>RC,defineLazy:()=>ke,esc:()=>Vn,escapeRegex:()=>nn,extend:()=>IC,finalizeIssue:()=>or,floatSafeRemainder:()=>Rd,getElementAtPath:()=>wC,getEnumValues:()=>Uo,getLengthableOrigin:()=>qo,getParsedType:()=>PC,getSizableOrigin:()=>Ix,isObject:()=>zs,isPlainObject:()=>Ls,issue:()=>Dd,joinValues:()=>La,jsonStringifyReplacer:()=>Pd,merge:()=>AC,normalizeParams:()=>G,nullish:()=>Zo,numKeys:()=>TC,omit:()=>OC,optionalKeys:()=>Ad,partial:()=>NC,pick:()=>CC,prefixIssues:()=>br,primitiveTypes:()=>Cx,promiseAllObject:()=>EC,propertyKeyTypes:()=>Id,randomString:()=>$C,required:()=>DC,stringifyPrimitive:()=>Ua,unwrapMessage:()=>Fo});function xC(t){return t}function vC(t){return t}function bC(t){}function SC(t){throw new Error}function kC(t){}function Uo(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function La(t,e="|"){return t.map(r=>Ua(r)).join(e)}function Pd(t,e){return typeof e=="bigint"?e.toString():e}function Ho(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Zo(t){return t==null}function Bo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Rd(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function ke(t,e,r){Object.defineProperty(t,e,{get(){{let s=r();return t[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function Cd(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function wC(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function EC(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let s={};for(let o=0;o<e.length;o++)s[e[o]]=n[o];return s})}function $C(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Vn(t){return JSON.stringify(t)}function zs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ls(t){if(zs(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(zs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function TC(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function nn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function It(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function G(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 RC(t){let e;return new Proxy({},{get(r,n,s){return e??(e=t()),Reflect.get(e,n,s)},set(r,n,s,o){return e??(e=t()),Reflect.set(e,n,s,o)},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,s){return e??(e=t()),Reflect.defineProperty(e,n,s)}})}function Ua(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Ad(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function CC(t,e){let r={},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return It(t,{...t._zod.def,shape:r,checks:[]})}function OC(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return It(t,{...t._zod.def,shape:r,checks:[]})}function IC(t,e){if(!Ls(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 Cd(this,"shape",n),n},checks:[]};return It(t,r)}function AC(t,e){return It(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Cd(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function NC(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=t?new t({type:"optional",innerType:n[o]}):n[o])}else for(let o in n)s[o]=t?new t({type:"optional",innerType:n[o]}):n[o];return It(e,{...e._zod.def,shape:s,checks:[]})}function DC(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:n[o]}))}else for(let o in n)s[o]=new t({type:"nonoptional",innerType:n[o]});return It(e,{...e._zod.def,shape:s,checks:[]})}function Wn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function br(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Fo(t){return typeof t=="string"?t:t?.message}function or(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=Fo(t.inst?._zod.def?.error?.(t))??Fo(e?.error?.(t))??Fo(r.customError?.(t))??Fo(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Ix(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function qo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Dd(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function MC(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Fa,Od,PC,Id,Cx,Nd,Ox,Td,Sr=v(()=>{Fa=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Od=Ho(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});PC=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}`)}},Id=new Set(["string","number","symbol"]),Cx=new Set(["string","number","bigint","boolean","symbol","undefined"]);Nd={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]},Ox={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Td=class{constructor(...e){}}});function Md(t,e=r=>r.message){let r={},n=[];for(let s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function jd(t,e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>s({issues:a}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({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 s(t),n}var Ax,Ha,Vo,zd=v(()=>{js();Sr();Ax=(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,Pd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ha=k("$ZodError",Ax),Vo=k("$ZodError",Ax,{Parent:Error})});var Ld,Fd,Ud,Hd,Zd,Gn,Bd,Kn,qd=v(()=>{js();zd();Sr();Ld=t=>(e,r,n,s)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Nr;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>or(c,o,Ot())));throw Fa(a,s?.callee),a}return i.value},Fd=Ld(Vo),Ud=t=>async(e,r,n,s)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>or(c,o,Ot())));throw Fa(a,s?.callee),a}return i.value},Hd=Ud(Vo),Zd=t=>(e,r,n)=>{let s=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Nr;return o.issues.length?{success:!1,error:new(t??Ha)(o.issues.map(i=>or(i,s,Ot())))}:{success:!0,data:o.value}},Gn=Zd(Vo),Bd=t=>async(e,r,n)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(i=>or(i,s,Ot())))}:{success:!0,data:o.value}},Kn=Bd(Vo)});function Zx(){return new RegExp(zC,"u")}function Qx(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 ev(t){return new RegExp(`^${Qx(t)}$`)}function tv(t){let e=Qx({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(`^${Yx}T(?:${n})$`)}var Nx,Dx,Mx,jx,zx,Lx,Fx,Ux,Vd,Hx,zC,Bx,qx,Vx,Wx,Gx,Wd,Kx,Jx,Yx,Xx,rv,nv,sv,ov,iv,av,cv,Ba=v(()=>{Nx=/^[cC][^\s-]{8,}$/,Dx=/^[0-9a-z]+$/,Mx=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,jx=/^[0-9a-vA-V]{20}$/,zx=/^[A-Za-z0-9]{27}$/,Lx=/^[a-zA-Z0-9_-]{21}$/,Fx=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ux=/^([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})$/,Vd=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)$/,Hx=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,zC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Bx=/^(?:(?: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])$/,qx=/^(([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})$/,Vx=/^((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])$/,Wx=/^(([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])$/,Gx=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Wd=/^[A-Za-z0-9_-]*$/,Kx=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Jx=/^\+(?:[0-9]){6,14}[0-9]$/,Yx="(?:(?:\\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])))",Xx=new RegExp(`^${Yx}$`);rv=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},nv=/^\d+$/,sv=/^-?\d+(?:\.\d+)?/i,ov=/true|false/i,iv=/null/i,av=/^[^A-Z]*$/,cv=/^[^a-z]*$/});var Je,uv,Gd,Kd,lv,dv,pv,mv,fv,Wo,hv,gv,yv,_v,xv,vv,bv,qa=v(()=>{js();Ba();Sr();Je=k("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),uv={number:"number",bigint:"bigint",object:"date"},Gd=k("$ZodCheckLessThan",(t,e)=>{Je.init(t,e);let r=uv[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?s.maximum=e.value:s.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})}}),Kd=k("$ZodCheckGreaterThan",(t,e)=>{Je.init(t,e);let r=uv[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?s.minimum=e.value:s.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})}}),lv=k("$ZodCheckMultipleOf",(t,e)=>{Je.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):Rd(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})}}),dv=k("$ZodCheckNumberFormat",(t,e)=>{Je.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,o]=Nd[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=s,a.maximum=o,r&&(a.pattern=nv)}),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<s&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),a>o&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:t})}}),pv=k("$ZodCheckMaxLength",(t,e)=>{var r;Je.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Zo(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let s=n.value;if(s.length<=e.maximum)return;let i=qo(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),mv=k("$ZodCheckMinLength",(t,e)=>{var r;Je.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Zo(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let s=n.value;if(s.length>=e.minimum)return;let i=qo(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),fv=k("$ZodCheckLengthEquals",(t,e)=>{var r;Je.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Zo(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{let s=n.value,o=s.length;if(o===e.length)return;let i=qo(s),a=o>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})}}),Wo=k("$ZodCheckStringFormat",(t,e)=>{var r,n;Je.init(t,e),t._zod.onattach.push(s=>{let o=s._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),hv=k("$ZodCheckRegex",(t,e)=>{Wo.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})}}),gv=k("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=av),Wo.init(t,e)}),yv=k("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=cv),Wo.init(t,e)}),_v=k("$ZodCheckIncludes",(t,e)=>{Je.init(t,e);let r=nn(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{let o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),xv=k("$ZodCheckStartsWith",(t,e)=>{Je.init(t,e);let r=new RegExp(`^${nn(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.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})}}),vv=k("$ZodCheckEndsWith",(t,e)=>{Je.init(t,e);let r=new RegExp(`.*${nn(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.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})}}),bv=k("$ZodCheckOverwrite",(t,e)=>{Je.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Va,Jd=v(()=>{Va=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(`
|
|
34
34
|
`).filter(i=>i),s=Math.min(...n.map(i=>i.length-i.trimStart().length)),o=n.map(i=>i.slice(s)).map(i=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,r=this?.args,s=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,s.join(`
|
|
35
|
-
`))}}});var
|
|
36
|
-
if (${
|
|
35
|
+
`))}}});var kv,Yd=v(()=>{kv={major:4,minor:0,patch:0}});function jv(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function LC(t){if(!Wd.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return jv(r)}function FC(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let s=JSON.parse(atob(n));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}function wv(t,e,r){t.issues.length&&e.issues.push(...br(r,t.issues)),e.value[r]=t.value}function Wa(t,e,r){t.issues.length&&e.issues.push(...br(r,t.issues)),e.value[r]=t.value}function Ev(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...br(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function $v(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(o=>or(o,n,Ot())))}),e}function Xd(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(Ls(t)&&Ls(e)){let r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),s={...t,...e};for(let o of n){let i=Xd(t[o],e[o]);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};s[o]=i.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let s=t[n],o=e[n],i=Xd(s,o);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Tv(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Wn(t))return t;let n=Xd(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function Pv(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Rv(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 Cv(t,e,r){return Wn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function Ov(t){return t.value=Object.freeze(t.value),t}function Iv(t,e,r,n){if(!t){let s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push(Dd(s))}}var xe,Go,we,Qd,ep,tp,rp,np,sp,op,ip,ap,cp,up,Av,Nv,Dv,Mv,lp,dp,pp,mp,fp,hp,gp,yp,Ga,_p,xp,vp,bp,Sp,kp,Ka,Ja,wp,Ep,$p,Tp,Pp,Rp,Cp,Op,Ip,Ap,Np,Dp,Mp,jp,zp,zv=v(()=>{qa();js();Jd();qd();Ba();Sr();Yd();Sr();xe=k("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=kv;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let s of n)for(let o of s._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let s=(o,i,a)=>{let c=Wn(o),u;for(let d of i){if(d._zod.def.when){if(!d._zod.def.when(o))continue}else if(c)continue;let l=o.issues.length,m=d._zod.check(o);if(m instanceof Promise&&a?.async===!1)throw new Nr;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,o.issues.length!==l&&(c||(c=Wn(o,l)))});else{if(o.issues.length===l)continue;c||(c=Wn(o,l))}}return u?u.then(()=>o):o};t._zod.run=(o,i)=>{let a=t._zod.parse(o,i);if(a instanceof Promise){if(i.async===!1)throw new Nr;return a.then(c=>s(c,n,i))}return s(a,n,i)}}t["~standard"]={validate:s=>{try{let o=Gn(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Kn(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Go=k("$ZodString",(t,e)=>{xe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??rv(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),we=k("$ZodStringFormat",(t,e)=>{Wo.init(t,e),Go.init(t,e)}),Qd=k("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Ux),we.init(t,e)}),ep=k("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Vd(n))}else e.pattern??(e.pattern=Vd());we.init(t,e)}),tp=k("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Hx),we.init(t,e)}),rp=k("$ZodURL",(t,e)=>{we.init(t,e),t._zod.check=r=>{try{let n=r.value,s=new URL(n),o=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Kx.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),np=k("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Zx()),we.init(t,e)}),sp=k("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Lx),we.init(t,e)}),op=k("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Nx),we.init(t,e)}),ip=k("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Dx),we.init(t,e)}),ap=k("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Mx),we.init(t,e)}),cp=k("$ZodXID",(t,e)=>{e.pattern??(e.pattern=jx),we.init(t,e)}),up=k("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=zx),we.init(t,e)}),Av=k("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=tv(e)),we.init(t,e)}),Nv=k("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Xx),we.init(t,e)}),Dv=k("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=ev(e)),we.init(t,e)}),Mv=k("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Fx),we.init(t,e)}),lp=k("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Bx),we.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),dp=k("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=qx),we.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),pp=k("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Vx),we.init(t,e)}),mp=k("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Wx),we.init(t,e),t._zod.check=r=>{let[n,s]=r.value.split("/");try{if(!s)throw new Error;let o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});fp=k("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Gx),we.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{jv(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});hp=k("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Wd),we.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{LC(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),gp=k("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Jx),we.init(t,e)});yp=k("$ZodJWT",(t,e)=>{we.init(t,e),t._zod.check=r=>{FC(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ga=k("$ZodNumber",(t,e)=>{xe.init(t,e),t._zod.pattern=t._zod.bag.pattern??sv,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let s=r.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return r;let o=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...o?{received:o}:{}}),r}}),_p=k("$ZodNumber",(t,e)=>{dv.init(t,e),Ga.init(t,e)}),xp=k("$ZodBoolean",(t,e)=>{xe.init(t,e),t._zod.pattern=ov,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let s=r.value;return typeof s=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),r}}),vp=k("$ZodNull",(t,e)=>{xe.init(t,e),t._zod.pattern=iv,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let s=r.value;return s===null||r.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),r}}),bp=k("$ZodUnknown",(t,e)=>{xe.init(t,e),t._zod.parse=r=>r}),Sp=k("$ZodNever",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});kp=k("$ZodArray",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),r;r.value=Array(s.length);let o=[];for(let i=0;i<s.length;i++){let a=s[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?o.push(c.then(u=>wv(u,r,i))):wv(c,r,i)}return o.length?Promise.all(o).then(()=>r):r}});Ka=k("$ZodObject",(t,e)=>{xe.init(t,e);let r=Ho(()=>{let l=Object.keys(e.shape);for(let f of l)if(!(e.shape[f]instanceof xe))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let m=Ad(e.shape);return{shape:e.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set(m)}});ke(t._zod,"propValues",()=>{let l=e.shape,m={};for(let f in l){let p=l[f]._zod;if(p.values){m[f]??(m[f]=new Set);for(let h of p.values)m[f].add(h)}}return m});let n=l=>{let m=new Va(["shape","payload","ctx"]),f=r.value,p=x=>{let y=Vn(x);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};m.write("const input = payload.value;");let h=Object.create(null),g=0;for(let x of f.keys)h[x]=`key_${g++}`;m.write("const newResult = {}");for(let x of f.keys)if(f.optionalKeys.has(x)){let y=h[x];m.write(`const ${y} = ${p(x)};`);let b=Vn(x);m.write(`
|
|
36
|
+
if (${y}.issues.length) {
|
|
37
37
|
if (input[${b}] === undefined) {
|
|
38
38
|
if (${b} in input) {
|
|
39
39
|
newResult[${b}] = undefined;
|
|
40
40
|
}
|
|
41
41
|
} else {
|
|
42
42
|
payload.issues = payload.issues.concat(
|
|
43
|
-
${
|
|
43
|
+
${y}.issues.map((iss) => ({
|
|
44
44
|
...iss,
|
|
45
45
|
path: iss.path ? [${b}, ...iss.path] : [${b}],
|
|
46
46
|
}))
|
|
47
47
|
);
|
|
48
48
|
}
|
|
49
|
-
} else if (${
|
|
49
|
+
} else if (${y}.value === undefined) {
|
|
50
50
|
if (${b} in input) newResult[${b}] = undefined;
|
|
51
51
|
} else {
|
|
52
|
-
newResult[${b}] = ${
|
|
52
|
+
newResult[${b}] = ${y}.value;
|
|
53
53
|
}
|
|
54
|
-
`)}else{let
|
|
55
|
-
if (${
|
|
54
|
+
`)}else{let y=h[x];m.write(`const ${y} = ${p(x)};`),m.write(`
|
|
55
|
+
if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
|
|
56
56
|
...iss,
|
|
57
|
-
path: iss.path ? [${
|
|
58
|
-
})));`),m.write(`newResult[${qn(x)}] = ${_}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let y=m.compile();return(x,_)=>y(l,x,_)},s,o=Ms,i=!za.jitless,c=i&&Pd.value,u=e.catchall,d;t._zod.parse=(l,m)=>{d??(d=r.value);let f=l.value;if(!o(f))return l.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),l;let p=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)s||(s=n(e.shape)),l=s(l,m);else{l.value={};let _=d.shape;for(let b of d.keys){let w=_[b],I=w._zod.run({value:f[b],issues:[]},m),C=w._zod.optin==="optional"&&w._zod.optout==="optional";I instanceof Promise?p.push(I.then(T=>C?Sv(T,l,b,f):Wa(T,l,b))):C?Sv(I,l,b,f):Wa(I,l,b)}}if(!u)return p.length?Promise.all(p).then(()=>l):l;let h=[],g=d.keySet,y=u._zod,x=y.def.type;for(let _ of Object.keys(f)){if(g.has(_))continue;if(x==="never"){h.push(_);continue}let b=y.run({value:f[_],issues:[]},m);b instanceof Promise?p.push(b.then(w=>Wa(w,l,_))):Wa(b,l,_)}return h.length&&l.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),p.length?Promise.all(p).then(()=>l):l}});Ja=k("$ZodUnion",(t,e)=>{xe.init(t,e),ke(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ke(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ke(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ke(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=>Zo(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1,o=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)o.push(a),s=!0;else{if(a.issues.length===0)return a;o.push(a)}}return s?Promise.all(o).then(i=>kv(i,r,t,n)):kv(o,r,t,n)}}),bp=k("$ZodDiscriminatedUnion",(t,e)=>{Ja.init(t,e);let r=t._zod.parse;ke(t._zod,"propValues",()=>{let s={};for(let o of e.options){let i=o._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[a,c]of Object.entries(i)){s[a]||(s[a]=new Set);for(let u of c)s[a].add(u)}}return s});let n=Uo(()=>{let s=e.options,o=new Map;for(let i of s){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(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,i)}}return o});t._zod.parse=(s,o)=>{let i=s.value;if(!Ms(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),s;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(s,o):e.unionFallback?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),s)}}),Sp=k("$ZodIntersection",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value,o=e.left._zod.run({value:s,issues:[]},n),i=e.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([c,u])=>wv(r,c,u)):wv(r,o,i)}});kp=k("$ZodRecord",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!js(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;let o=[];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:s[c],issues:[]},n);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&r.issues.push(...vr(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...vr(c,u.issues)),r.value[c]=u.value)}let a;for(let c in s)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(s)){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=>nr(u,n,Ct())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:s[i],issues:[]},n);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&r.issues.push(...vr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...vr(i,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),wp=k("$ZodEnum",(t,e)=>{xe.init(t,e);let r=Fo(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Rd.has(typeof n)).map(n=>typeof n=="string"?rn(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:t}),n}}),Ep=k("$ZodLiteral",(t,e)=>{xe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?rn(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}}),$p=k("$ZodTransform",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(r.value=i,r));if(s instanceof Promise)throw new Ar;return r.value=s,r}}),Tp=k("$ZodOptional",(t,e)=>{xe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Zo(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)}),Pp=k("$ZodNullable",(t,e)=>{xe.init(t,e),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Zo(r.source)}|null)$`):void 0}),ke(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)}),Rp=k("$ZodDefault",(t,e)=>{xe.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Ev(o,e)):Ev(s,e)}});Cp=k("$ZodPrefault",(t,e)=>{xe.init(t,e),t._zod.optin="optional",ke(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))}),Op=k("$ZodNonOptional",(t,e)=>{xe.init(t,e),ke(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 s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>$v(o,t)):$v(s,t)}});Ip=k("$ZodCatch",(t,e)=>{xe.init(t,e),t._zod.optin="optional",ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(i=>nr(i,n,Ct()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>nr(o,n,Ct()))},input:r.value}),r.issues=[]),r)}}),Ap=k("$ZodPipe",(t,e)=>{xe.init(t,e),ke(t._zod,"values",()=>e.in._zod.values),ke(t._zod,"optin",()=>e.in._zod.optin),ke(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>Tv(o,e,n)):Tv(s,e,n)}});Np=k("$ZodReadonly",(t,e)=>{xe.init(t,e),ke(t._zod,"propValues",()=>e.innerType._zod.propValues),ke(t._zod,"values",()=>e.innerType._zod.values),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(Pv):Pv(s)}});Dp=k("$ZodCustom",(t,e)=>{Je.init(t,e),xe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(o=>Rv(o,r,n,t));Rv(s,r,n,t)}})});function Mv(){return{localeError:IC()}}var OC,IC,jv=v(()=>{br();OC=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},IC=()=>{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 ${OC(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ua(n.values[0])}`:`Invalid option: expected one of ${La(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",o=e(n.origin);return o?`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",o=e(n.origin);return o?`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${o.unit}`:`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.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":""}: ${La(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 Ya=v(()=>{});function zv(){return new Go}var Go,nn,jp=v(()=>{Go=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)}};nn=zv()});function zp(t,e){return new t({type:"string",...G(e)})}function Lp(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...G(e)})}function Xa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...G(e)})}function Fp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...G(e)})}function Up(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...G(e)})}function Hp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...G(e)})}function Zp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...G(e)})}function Bp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...G(e)})}function qp(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...G(e)})}function Vp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...G(e)})}function Wp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...G(e)})}function Gp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...G(e)})}function Kp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...G(e)})}function Jp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...G(e)})}function Yp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...G(e)})}function Xp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...G(e)})}function Qp(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...G(e)})}function em(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...G(e)})}function tm(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...G(e)})}function rm(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...G(e)})}function nm(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...G(e)})}function sm(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...G(e)})}function om(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...G(e)})}function Lv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...G(e)})}function Fv(t,e){return new t({type:"string",format:"date",check:"string_format",...G(e)})}function Uv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...G(e)})}function Hv(t,e){return new t({type:"string",format:"duration",check:"string_format",...G(e)})}function im(t,e){return new t({type:"number",checks:[],...G(e)})}function am(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...G(e)})}function cm(t,e){return new t({type:"boolean",...G(e)})}function um(t,e){return new t({type:"null",...G(e)})}function lm(t){return new t({type:"unknown"})}function dm(t,e){return new t({type:"never",...G(e)})}function Qa(t,e){return new qd({check:"less_than",...G(e),value:t,inclusive:!1})}function Ko(t,e){return new qd({check:"less_than",...G(e),value:t,inclusive:!0})}function ec(t,e){return new Vd({check:"greater_than",...G(e),value:t,inclusive:!1})}function Jo(t,e){return new Vd({check:"greater_than",...G(e),value:t,inclusive:!0})}function tc(t,e){return new av({check:"multiple_of",...G(e),value:t})}function rc(t,e){return new uv({check:"max_length",...G(e),maximum:t})}function zs(t,e){return new lv({check:"min_length",...G(e),minimum:t})}function nc(t,e){return new dv({check:"length_equals",...G(e),length:t})}function pm(t,e){return new pv({check:"string_format",format:"regex",...G(e),pattern:t})}function mm(t){return new mv({check:"string_format",format:"lowercase",...G(t)})}function fm(t){return new fv({check:"string_format",format:"uppercase",...G(t)})}function hm(t,e){return new hv({check:"string_format",format:"includes",...G(e),includes:t})}function gm(t,e){return new gv({check:"string_format",format:"starts_with",...G(e),prefix:t})}function ym(t,e){return new yv({check:"string_format",format:"ends_with",...G(e),suffix:t})}function Kn(t){return new _v({check:"overwrite",tx:t})}function _m(t){return Kn(e=>e.normalize(t))}function xm(){return Kn(t=>t.trim())}function vm(){return Kn(t=>t.toLowerCase())}function bm(){return Kn(t=>t.toUpperCase())}function Zv(t,e,r){return new t({type:"array",element:e,...G(r)})}function Sm(t,e,r){let n=G(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function km(t,e,r){return new t({type:"custom",check:"custom",fn:e,...G(r)})}var Bv=v(()=>{qa();br()});var qv=v(()=>{});function wm(t,e){if(t instanceof Go){let n=new sc(e),s={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let o={},i={registry:t,uri:e?.uri,defs:s};for(let a of t._idmap.entries()){let[c,u]=a;o[c]=n.emit(u,{...e,external:i})}if(Object.keys(s).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[a]:s}}return{schemas:o}}let r=new sc(e);return r.process(t),r.emit(t,e)}function Be(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let s=t._zod.def;switch(s.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 Be(s.element,r);case"object":{for(let o in s.shape)if(Be(s.shape[o],r))return!0;return!1}case"union":{for(let o of s.options)if(Be(o,r))return!0;return!1}case"intersection":return Be(s.left,r)||Be(s.right,r);case"tuple":{for(let o of s.items)if(Be(o,r))return!0;return!!(s.rest&&Be(s.rest,r))}case"record":return Be(s.keyType,r)||Be(s.valueType,r);case"map":return Be(s.keyType,r)||Be(s.valueType,r);case"set":return Be(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Be(s.innerType,r);case"lazy":return Be(s.getter(),r);case"default":return Be(s.innerType,r);case"prefault":return Be(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Be(s.in,r)||Be(s.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${s.type}`)}var sc,Vv=v(()=>{jp();br();sc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??nn,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 s=e._zod.def,o={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 l={...r,schemaPath:[...r.schemaPath,e],path:r.path},m=e._zod.parent;if(m)a.ref=m,this.process(m,l),this.seen.get(m).isParent=!0;else{let f=a.schema;switch(s.type){case"string":{let p=f;p.type="string";let{minimum:h,maximum:g,format:y,patterns:x,contentEncoding:_}=e._zod.bag;if(typeof h=="number"&&(p.minLength=h),typeof g=="number"&&(p.maxLength=g),y&&(p.format=o[y]??y,p.format===""&&delete p.format),_&&(p.contentEncoding=_),x&&x.size>0){let b=[...x];b.length===1?p.pattern=b[0].source:b.length>1&&(a.schema.allOf=[...b.map(w=>({...this.target==="draft-7"?{type:"string"}:{},pattern:w.source}))])}break}case"number":{let p=f,{minimum:h,maximum:g,format:y,multipleOf:x,exclusiveMaximum:_,exclusiveMinimum:b}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof b=="number"&&(p.exclusiveMinimum=b),typeof h=="number"&&(p.minimum=h,typeof b=="number"&&(b>=h?delete p.minimum:delete p.exclusiveMinimum)),typeof _=="number"&&(p.exclusiveMaximum=_),typeof g=="number"&&(p.maximum=g,typeof _=="number"&&(_<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof x=="number"&&(p.multipleOf=x);break}case"boolean":{let p=f;p.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":{f.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":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=f,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(p.minItems=h),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(s.element,{...l,path:[...l.path,"items"]});break}case"object":{let p=f;p.type="object",p.properties={};let h=s.shape;for(let x in h)p.properties[x]=this.process(h[x],{...l,path:[...l.path,"properties",x]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(x=>{let _=s.shape[x]._zod;return this.io==="input"?_.optin===void 0:_.optout===void 0}));y.size>0&&(p.required=Array.from(y)),s.catchall?._zod.def.type==="never"?p.additionalProperties=!1:s.catchall?s.catchall&&(p.additionalProperties=this.process(s.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=f;p.anyOf=s.options.map((h,g)=>this.process(h,{...l,path:[...l.path,"anyOf",g]}));break}case"intersection":{let p=f,h=this.process(s.left,{...l,path:[...l.path,"allOf",0]}),g=this.process(s.right,{...l,path:[...l.path,"allOf",1]}),y=_=>"allOf"in _&&Object.keys(_).length===1,x=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];p.allOf=x;break}case"tuple":{let p=f;p.type="array";let h=s.items.map((x,_)=>this.process(x,{...l,path:[...l.path,"prefixItems",_]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,s.rest){let x=this.process(s.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?p.items=x:p.additionalItems=x}s.rest&&(p.items=this.process(s.rest,{...l,path:[...l.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{let p=f;p.type="object",p.propertyNames=this.process(s.keyType,{...l,path:[...l.path,"propertyNames"]}),p.additionalProperties=this.process(s.valueType,{...l,path:[...l.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 p=f,h=Fo(s.entries);h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),p.enum=h;break}case"literal":{let p=f,h=[];for(let g of s.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");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];p.type=g===null?"null":typeof g,p.const=g}else h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),h.every(g=>typeof g=="boolean")&&(p.type="string"),h.every(g=>g===null)&&(p.type="null"),p.enum=h;break}case"file":{let p=f,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:x}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),x?x.length===1?(h.contentMediaType=x[0],Object.assign(p,h)):p.anyOf=x.map(_=>({...h,contentMediaType:_})):Object.assign(p,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(s.innerType,l);f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"success":{let p=f;p.type="boolean";break}case"default":{this.process(s.innerType,l),a.ref=s.innerType,f.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,l),a.ref=s.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,l),a.ref=s.innerType;let p;try{p=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=f,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=h.source;break}case"pipe":{let p=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(p,l),a.ref=p;break}case"readonly":{this.process(s.innerType,l),a.ref=s.innerType,f.readOnly=!0;break}case"promise":{this.process(s.innerType,l),a.ref=s.innerType;break}case"optional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,l),a.ref=p;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"&&Be(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},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=d=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(d[0])?.id,g=n.external.uri??(x=>x);if(h)return{ref:g(h)};let y=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=y,{defId:y,ref:`${g("__shared")}#/${l}/${y}`}}if(d[1]===s)return{ref:"#"};let f=`#/${l}/`,p=d[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:f+p}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:m,defId:f}=o(d);l.def={...l.schema},f&&(l.defId=f);let p=l.schema;for(let h in p)delete p[h];p.$ref=m};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
|
|
57
|
+
path: iss.path ? [${Vn(x)}, ...iss.path] : [${Vn(x)}]
|
|
58
|
+
})));`),m.write(`newResult[${Vn(x)}] = ${y}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let _=m.compile();return(x,y)=>_(l,x,y)},s,o=zs,i=!za.jitless,c=i&&Od.value,u=e.catchall,d;t._zod.parse=(l,m)=>{d??(d=r.value);let f=l.value;if(!o(f))return l.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),l;let p=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)s||(s=n(e.shape)),l=s(l,m);else{l.value={};let y=d.shape;for(let b of d.keys){let w=y[b],O=w._zod.run({value:f[b],issues:[]},m),C=w._zod.optin==="optional"&&w._zod.optout==="optional";O instanceof Promise?p.push(O.then(T=>C?Ev(T,l,b,f):Wa(T,l,b))):C?Ev(O,l,b,f):Wa(O,l,b)}}if(!u)return p.length?Promise.all(p).then(()=>l):l;let h=[],g=d.keySet,_=u._zod,x=_.def.type;for(let y of Object.keys(f)){if(g.has(y))continue;if(x==="never"){h.push(y);continue}let b=_.run({value:f[y],issues:[]},m);b instanceof Promise?p.push(b.then(w=>Wa(w,l,y))):Wa(b,l,y)}return h.length&&l.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),p.length?Promise.all(p).then(()=>l):l}});Ja=k("$ZodUnion",(t,e)=>{xe.init(t,e),ke(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ke(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ke(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ke(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=>Bo(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1,o=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)o.push(a),s=!0;else{if(a.issues.length===0)return a;o.push(a)}}return s?Promise.all(o).then(i=>$v(i,r,t,n)):$v(o,r,t,n)}}),wp=k("$ZodDiscriminatedUnion",(t,e)=>{Ja.init(t,e);let r=t._zod.parse;ke(t._zod,"propValues",()=>{let s={};for(let o of e.options){let i=o._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[a,c]of Object.entries(i)){s[a]||(s[a]=new Set);for(let u of c)s[a].add(u)}}return s});let n=Ho(()=>{let s=e.options,o=new Map;for(let i of s){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(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,i)}}return o});t._zod.parse=(s,o)=>{let i=s.value;if(!zs(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),s;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(s,o):e.unionFallback?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),s)}}),Ep=k("$ZodIntersection",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value,o=e.left._zod.run({value:s,issues:[]},n),i=e.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([c,u])=>Tv(r,c,u)):Tv(r,o,i)}});$p=k("$ZodRecord",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Ls(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;let o=[];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:s[c],issues:[]},n);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&r.issues.push(...br(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...br(c,u.issues)),r.value[c]=u.value)}let a;for(let c in s)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(s)){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=>or(u,n,Ot())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:s[i],issues:[]},n);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&r.issues.push(...br(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...br(i,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),Tp=k("$ZodEnum",(t,e)=>{xe.init(t,e);let r=Uo(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Id.has(typeof n)).map(n=>typeof n=="string"?nn(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:t}),n}}),Pp=k("$ZodLiteral",(t,e)=>{xe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?nn(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}}),Rp=k("$ZodTransform",(t,e)=>{xe.init(t,e),t._zod.parse=(r,n)=>{let s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(r.value=i,r));if(s instanceof Promise)throw new Nr;return r.value=s,r}}),Cp=k("$ZodOptional",(t,e)=>{xe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Bo(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)}),Op=k("$ZodNullable",(t,e)=>{xe.init(t,e),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Bo(r.source)}|null)$`):void 0}),ke(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)}),Ip=k("$ZodDefault",(t,e)=>{xe.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Pv(o,e)):Pv(s,e)}});Ap=k("$ZodPrefault",(t,e)=>{xe.init(t,e),t._zod.optin="optional",ke(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))}),Np=k("$ZodNonOptional",(t,e)=>{xe.init(t,e),ke(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 s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Rv(o,t)):Rv(s,t)}});Dp=k("$ZodCatch",(t,e)=>{xe.init(t,e),t._zod.optin="optional",ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(i=>or(i,n,Ot()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>or(o,n,Ot()))},input:r.value}),r.issues=[]),r)}}),Mp=k("$ZodPipe",(t,e)=>{xe.init(t,e),ke(t._zod,"values",()=>e.in._zod.values),ke(t._zod,"optin",()=>e.in._zod.optin),ke(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>Cv(o,e,n)):Cv(s,e,n)}});jp=k("$ZodReadonly",(t,e)=>{xe.init(t,e),ke(t._zod,"propValues",()=>e.innerType._zod.propValues),ke(t._zod,"values",()=>e.innerType._zod.values),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(Ov):Ov(s)}});zp=k("$ZodCustom",(t,e)=>{Je.init(t,e),xe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(o=>Iv(o,r,n,t));Iv(s,r,n,t)}})});function Lv(){return{localeError:HC()}}var UC,HC,Fv=v(()=>{Sr();UC=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},HC=()=>{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 ${UC(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ua(n.values[0])}`:`Invalid option: expected one of ${La(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",o=e(n.origin);return o?`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",o=e(n.origin);return o?`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${o.unit}`:`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.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":""}: ${La(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 Ya=v(()=>{});function Uv(){return new Ko}var Ko,sn,Fp=v(()=>{Ko=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)}};sn=Uv()});function Up(t,e){return new t({type:"string",...G(e)})}function Hp(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...G(e)})}function Xa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...G(e)})}function Zp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...G(e)})}function Bp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...G(e)})}function qp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...G(e)})}function Vp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...G(e)})}function Wp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...G(e)})}function Gp(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...G(e)})}function Kp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...G(e)})}function Jp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...G(e)})}function Yp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...G(e)})}function Xp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...G(e)})}function Qp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...G(e)})}function em(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...G(e)})}function tm(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...G(e)})}function rm(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...G(e)})}function nm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...G(e)})}function sm(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...G(e)})}function om(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...G(e)})}function im(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...G(e)})}function am(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...G(e)})}function cm(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...G(e)})}function Hv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...G(e)})}function Zv(t,e){return new t({type:"string",format:"date",check:"string_format",...G(e)})}function Bv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...G(e)})}function qv(t,e){return new t({type:"string",format:"duration",check:"string_format",...G(e)})}function um(t,e){return new t({type:"number",checks:[],...G(e)})}function lm(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...G(e)})}function dm(t,e){return new t({type:"boolean",...G(e)})}function pm(t,e){return new t({type:"null",...G(e)})}function mm(t){return new t({type:"unknown"})}function fm(t,e){return new t({type:"never",...G(e)})}function Qa(t,e){return new Gd({check:"less_than",...G(e),value:t,inclusive:!1})}function Jo(t,e){return new Gd({check:"less_than",...G(e),value:t,inclusive:!0})}function ec(t,e){return new Kd({check:"greater_than",...G(e),value:t,inclusive:!1})}function Yo(t,e){return new Kd({check:"greater_than",...G(e),value:t,inclusive:!0})}function tc(t,e){return new lv({check:"multiple_of",...G(e),value:t})}function rc(t,e){return new pv({check:"max_length",...G(e),maximum:t})}function Fs(t,e){return new mv({check:"min_length",...G(e),minimum:t})}function nc(t,e){return new fv({check:"length_equals",...G(e),length:t})}function hm(t,e){return new hv({check:"string_format",format:"regex",...G(e),pattern:t})}function gm(t){return new gv({check:"string_format",format:"lowercase",...G(t)})}function ym(t){return new yv({check:"string_format",format:"uppercase",...G(t)})}function _m(t,e){return new _v({check:"string_format",format:"includes",...G(e),includes:t})}function xm(t,e){return new xv({check:"string_format",format:"starts_with",...G(e),prefix:t})}function vm(t,e){return new vv({check:"string_format",format:"ends_with",...G(e),suffix:t})}function Jn(t){return new bv({check:"overwrite",tx:t})}function bm(t){return Jn(e=>e.normalize(t))}function Sm(){return Jn(t=>t.trim())}function km(){return Jn(t=>t.toLowerCase())}function wm(){return Jn(t=>t.toUpperCase())}function Vv(t,e,r){return new t({type:"array",element:e,...G(r)})}function Em(t,e,r){let n=G(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function $m(t,e,r){return new t({type:"custom",check:"custom",fn:e,...G(r)})}var Wv=v(()=>{qa();Sr()});var Gv=v(()=>{});function Tm(t,e){if(t instanceof Ko){let n=new sc(e),s={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let o={},i={registry:t,uri:e?.uri,defs:s};for(let a of t._idmap.entries()){let[c,u]=a;o[c]=n.emit(u,{...e,external:i})}if(Object.keys(s).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[a]:s}}return{schemas:o}}let r=new sc(e);return r.process(t),r.emit(t,e)}function Ve(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let s=t._zod.def;switch(s.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 Ve(s.element,r);case"object":{for(let o in s.shape)if(Ve(s.shape[o],r))return!0;return!1}case"union":{for(let o of s.options)if(Ve(o,r))return!0;return!1}case"intersection":return Ve(s.left,r)||Ve(s.right,r);case"tuple":{for(let o of s.items)if(Ve(o,r))return!0;return!!(s.rest&&Ve(s.rest,r))}case"record":return Ve(s.keyType,r)||Ve(s.valueType,r);case"map":return Ve(s.keyType,r)||Ve(s.valueType,r);case"set":return Ve(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ve(s.innerType,r);case"lazy":return Ve(s.getter(),r);case"default":return Ve(s.innerType,r);case"prefault":return Ve(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ve(s.in,r)||Ve(s.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${s.type}`)}var sc,Kv=v(()=>{Fp();Sr();sc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??sn,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 s=e._zod.def,o={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 l={...r,schemaPath:[...r.schemaPath,e],path:r.path},m=e._zod.parent;if(m)a.ref=m,this.process(m,l),this.seen.get(m).isParent=!0;else{let f=a.schema;switch(s.type){case"string":{let p=f;p.type="string";let{minimum:h,maximum:g,format:_,patterns:x,contentEncoding:y}=e._zod.bag;if(typeof h=="number"&&(p.minLength=h),typeof g=="number"&&(p.maxLength=g),_&&(p.format=o[_]??_,p.format===""&&delete p.format),y&&(p.contentEncoding=y),x&&x.size>0){let b=[...x];b.length===1?p.pattern=b[0].source:b.length>1&&(a.schema.allOf=[...b.map(w=>({...this.target==="draft-7"?{type:"string"}:{},pattern:w.source}))])}break}case"number":{let p=f,{minimum:h,maximum:g,format:_,multipleOf:x,exclusiveMaximum:y,exclusiveMinimum:b}=e._zod.bag;typeof _=="string"&&_.includes("int")?p.type="integer":p.type="number",typeof b=="number"&&(p.exclusiveMinimum=b),typeof h=="number"&&(p.minimum=h,typeof b=="number"&&(b>=h?delete p.minimum:delete p.exclusiveMinimum)),typeof y=="number"&&(p.exclusiveMaximum=y),typeof g=="number"&&(p.maximum=g,typeof y=="number"&&(y<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof x=="number"&&(p.multipleOf=x);break}case"boolean":{let p=f;p.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":{f.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":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=f,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(p.minItems=h),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(s.element,{...l,path:[...l.path,"items"]});break}case"object":{let p=f;p.type="object",p.properties={};let h=s.shape;for(let x in h)p.properties[x]=this.process(h[x],{...l,path:[...l.path,"properties",x]});let g=new Set(Object.keys(h)),_=new Set([...g].filter(x=>{let y=s.shape[x]._zod;return this.io==="input"?y.optin===void 0:y.optout===void 0}));_.size>0&&(p.required=Array.from(_)),s.catchall?._zod.def.type==="never"?p.additionalProperties=!1:s.catchall?s.catchall&&(p.additionalProperties=this.process(s.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=f;p.anyOf=s.options.map((h,g)=>this.process(h,{...l,path:[...l.path,"anyOf",g]}));break}case"intersection":{let p=f,h=this.process(s.left,{...l,path:[...l.path,"allOf",0]}),g=this.process(s.right,{...l,path:[...l.path,"allOf",1]}),_=y=>"allOf"in y&&Object.keys(y).length===1,x=[..._(h)?h.allOf:[h],..._(g)?g.allOf:[g]];p.allOf=x;break}case"tuple":{let p=f;p.type="array";let h=s.items.map((x,y)=>this.process(x,{...l,path:[...l.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,s.rest){let x=this.process(s.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?p.items=x:p.additionalItems=x}s.rest&&(p.items=this.process(s.rest,{...l,path:[...l.path,"items"]}));let{minimum:g,maximum:_}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof _=="number"&&(p.maxItems=_);break}case"record":{let p=f;p.type="object",p.propertyNames=this.process(s.keyType,{...l,path:[...l.path,"propertyNames"]}),p.additionalProperties=this.process(s.valueType,{...l,path:[...l.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 p=f,h=Uo(s.entries);h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),p.enum=h;break}case"literal":{let p=f,h=[];for(let g of s.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");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];p.type=g===null?"null":typeof g,p.const=g}else h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),h.every(g=>typeof g=="boolean")&&(p.type="string"),h.every(g=>g===null)&&(p.type="null"),p.enum=h;break}case"file":{let p=f,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:_,mime:x}=e._zod.bag;g!==void 0&&(h.minLength=g),_!==void 0&&(h.maxLength=_),x?x.length===1?(h.contentMediaType=x[0],Object.assign(p,h)):p.anyOf=x.map(y=>({...h,contentMediaType:y})):Object.assign(p,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(s.innerType,l);f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"success":{let p=f;p.type="boolean";break}case"default":{this.process(s.innerType,l),a.ref=s.innerType,f.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,l),a.ref=s.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,l),a.ref=s.innerType;let p;try{p=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=f,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=h.source;break}case"pipe":{let p=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(p,l),a.ref=p;break}case"readonly":{this.process(s.innerType,l),a.ref=s.innerType,f.readOnly=!0;break}case"promise":{this.process(s.innerType,l),a.ref=s.innerType;break}case"optional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,l),a.ref=p;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"&&Ve(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},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=d=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(d[0])?.id,g=n.external.uri??(x=>x);if(h)return{ref:g(h)};let _=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=_,{defId:_,ref:`${g("__shared")}#/${l}/${_}`}}if(d[1]===s)return{ref:"#"};let f=`#/${l}/`,p=d[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:f+p}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:m,defId:f}=o(d);l.def={...l.schema},f&&(l.defId=f);let p=l.schema;for(let h in p)delete p[h];p.$ref=m};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
|
|
59
59
|
|
|
60
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of this.seen.entries()){let l=d[1];if(e===d[0]){i(d);continue}if(n.external){let f=n.external.registry.get(d[0])?.id;if(e!==d[0]&&f){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let m=this.seen.get(d),f=m.def??m.schema,p={...f};if(m.ref===null)return;let h=m.ref;if(m.ref=null,h){a(h,l);let g=this.seen.get(h).schema;g.$ref&&l.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,p))}m.isParent||this.override({zodSchema:d,jsonSchema:f,path:m.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[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 d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,s.def);let u=n.external?.defs??{};for(let d of this.seen.entries()){let l=d[1];l.def&&l.defId&&(u[l.defId]=l.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 Wv=v(()=>{});var dt=v(()=>{Ds();Hd();Dd();Dv();qa();Gd();br();Ba();Ya();jp();Wd();qv();Bv();Vv();Wv()});var Em=v(()=>{dt()});function $m(t,e){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},...ae.normalizeParams(e)};return new fO(r)}var mO,fO,Gv=v(()=>{dt();dt();Em();mO=k("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");xe.init(t,e),t.def=e,t.parse=(r,n)=>jd(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Wn(t,r,n),t.parseAsync=async(r,n)=>Ld(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Gn(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)=>Ot(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),fO=k("ZodMiniObject",(t,e)=>{Ka.init(t,e),mO.init(t,e),ae.defineLazy(t,"shape",()=>e.shape)})});var Kv=v(()=>{});var Jv=v(()=>{});var Yv=v(()=>{});var Xv=v(()=>{dt();Em();Gv();Kv();dt();Ya();Jv();Yv()});var Qv=v(()=>{Xv()});var Tm=v(()=>{Qv()});function Zt(t){return!!t._zod}function Yn(t){let e=Object.values(t);if(e.length===0)return $m({});let r=e.every(Zt),n=e.every(s=>!Zt(s));if(r)return $m(t);if(n)return Sd(t);throw new Error("Mixed Zod versions detected in object shape.")}function sn(t,e){return Zt(t)?Wn(t,e):t.safeParse(e)}async function oc(t,e){return Zt(t)?await Gn(t,e):await t.safeParseAsync(e)}function on(t){if(!t)return;let e;if(Zt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ls(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(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return Yn(t)}}if(Zt(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 ic(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 tb(t){return t.description}function rb(t){if(Zt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function ac(t){if(Zt(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.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 Yo=v(()=>{zo();Tm()});var Pm=v(()=>{dt()});var Xo={};Le(Xo,{ZodISODate:()=>sb,ZodISODateTime:()=>nb,ZodISODuration:()=>ib,ZodISOTime:()=>ob,date:()=>Cm,datetime:()=>Rm,duration:()=>Im,time:()=>Om});function Rm(t){return Lv(nb,t)}function Cm(t){return Fv(sb,t)}function Om(t){return Uv(ob,t)}function Im(t){return Hv(ib,t)}var nb,sb,ob,ib,Am=v(()=>{dt();Nm();nb=k("ZodISODateTime",(t,e)=>{Cv.init(t,e),Ie.init(t,e)});sb=k("ZodISODate",(t,e)=>{Ov.init(t,e),Ie.init(t,e)});ob=k("ZodISOTime",(t,e)=>{Iv.init(t,e),Ie.init(t,e)});ib=k("ZodISODuration",(t,e)=>{Av.init(t,e),Ie.init(t,e)})});var ab,eq,Qo,Dm=v(()=>{dt();dt();ab=(t,e)=>{Ha.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Nd(t,r)},flatten:{value:r=>Ad(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},eq=k("ZodError",ab),Qo=k("ZodError",ab,{Parent:Error})});var cb,ub,lb,db,Mm=v(()=>{dt();Dm();cb=Md(Qo),ub=zd(Qo),lb=Fd(Qo),db=Ud(Qo)});function S(t){return zp(wO,t)}function ge(t){return im(gb,t)}function mb(t){return am(HO,t)}function We(t){return cm(ZO,t)}function yb(t){return um(BO,t)}function Ae(){return lm(qO)}function WO(t){return dm(VO,t)}function ce(t,e){return Zv(GO,t,e)}function j(t,e){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},...ae.normalizeParams(e)};return new _b(r)}function pt(t,e){return new _b({type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},catchall:Ae(),...ae.normalizeParams(e)})}function Te(t,e){return new xb({type:"union",options:t,...ae.normalizeParams(e)})}function Lm(t,e,r){return new KO({type:"union",options:e,discriminator:t,...ae.normalizeParams(r)})}function uc(t,e){return new JO({type:"intersection",left:t,right:e})}function Ee(t,e,r){return new YO({type:"record",keyType:t,valueType:e,...ae.normalizeParams(r)})}function St(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new jm({type:"enum",entries:r,...ae.normalizeParams(e)})}function H(t,e){return new XO({type:"literal",values:Array.isArray(t)?t:[t],...ae.normalizeParams(e)})}function vb(t){return new QO({type:"transform",transform:t})}function Ne(t){return new bb({type:"optional",innerType:t})}function fb(t){return new eI({type:"nullable",innerType:t})}function rI(t,e){return new tI({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function sI(t,e){return new nI({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function oI(t,e){return new Sb({type:"nonoptional",innerType:t,...ae.normalizeParams(e)})}function aI(t,e){return new iI({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function zm(t,e){return new cI({type:"pipe",in:t,out:e})}function lI(t){return new uI({type:"readonly",innerType:t})}function dI(t){let e=new Je({check:"custom"});return e._zod.check=t,e}function wb(t,e){return Sm(kb,t??(()=>!0),e)}function pI(t,e={}){return km(kb,t,e)}function mI(t){let e=dI(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ae.issue(n,r.value,e._zod.def));else{let s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(ae.issue(s))}},t(r.value,r)));return e}function Fm(t,e){return zm(vb(t),e)}var je,hb,wO,Ie,EO,pb,cc,$O,TO,PO,RO,CO,OO,IO,AO,NO,DO,MO,jO,zO,LO,FO,UO,gb,HO,ZO,BO,qO,VO,GO,_b,xb,KO,JO,YO,jm,XO,QO,bb,eI,tI,nI,Sb,iI,cI,uI,kb,Nm=v(()=>{dt();dt();Pm();Am();Mm();je=k("ZodType",(t,e)=>(xe.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)=>Ot(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>cb(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>lb(t,r,n),t.parseAsync=async(r,n)=>ub(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>db(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(pI(r,n)),t.superRefine=r=>t.check(mI(r)),t.overwrite=r=>t.check(Kn(r)),t.optional=()=>Ne(t),t.nullable=()=>fb(t),t.nullish=()=>Ne(fb(t)),t.nonoptional=r=>oI(t,r),t.array=()=>ce(t),t.or=r=>Te([t,r]),t.and=r=>uc(t,r),t.transform=r=>zm(t,vb(r)),t.default=r=>rI(t,r),t.prefault=r=>sI(t,r),t.catch=r=>aI(t,r),t.pipe=r=>zm(t,r),t.readonly=()=>lI(t),t.describe=r=>{let n=t.clone();return nn.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return nn.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return nn.get(t);let n=t.clone();return nn.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),hb=k("_ZodString",(t,e)=>{Wo.init(t,e),je.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(pm(...n)),t.includes=(...n)=>t.check(hm(...n)),t.startsWith=(...n)=>t.check(gm(...n)),t.endsWith=(...n)=>t.check(ym(...n)),t.min=(...n)=>t.check(zs(...n)),t.max=(...n)=>t.check(rc(...n)),t.length=(...n)=>t.check(nc(...n)),t.nonempty=(...n)=>t.check(zs(1,...n)),t.lowercase=n=>t.check(mm(n)),t.uppercase=n=>t.check(fm(n)),t.trim=()=>t.check(xm()),t.normalize=(...n)=>t.check(_m(...n)),t.toLowerCase=()=>t.check(vm()),t.toUpperCase=()=>t.check(bm())}),wO=k("ZodString",(t,e)=>{Wo.init(t,e),hb.init(t,e),t.email=r=>t.check(Lp(EO,r)),t.url=r=>t.check(Bp($O,r)),t.jwt=r=>t.check(om(UO,r)),t.emoji=r=>t.check(qp(TO,r)),t.guid=r=>t.check(Xa(pb,r)),t.uuid=r=>t.check(Fp(cc,r)),t.uuidv4=r=>t.check(Up(cc,r)),t.uuidv6=r=>t.check(Hp(cc,r)),t.uuidv7=r=>t.check(Zp(cc,r)),t.nanoid=r=>t.check(Vp(PO,r)),t.guid=r=>t.check(Xa(pb,r)),t.cuid=r=>t.check(Wp(RO,r)),t.cuid2=r=>t.check(Gp(CO,r)),t.ulid=r=>t.check(Kp(OO,r)),t.base64=r=>t.check(rm(zO,r)),t.base64url=r=>t.check(nm(LO,r)),t.xid=r=>t.check(Jp(IO,r)),t.ksuid=r=>t.check(Yp(AO,r)),t.ipv4=r=>t.check(Xp(NO,r)),t.ipv6=r=>t.check(Qp(DO,r)),t.cidrv4=r=>t.check(em(MO,r)),t.cidrv6=r=>t.check(tm(jO,r)),t.e164=r=>t.check(sm(FO,r)),t.datetime=r=>t.check(Rm(r)),t.date=r=>t.check(Cm(r)),t.time=r=>t.check(Om(r)),t.duration=r=>t.check(Im(r))});Ie=k("ZodStringFormat",(t,e)=>{we.init(t,e),hb.init(t,e)}),EO=k("ZodEmail",(t,e)=>{Xd.init(t,e),Ie.init(t,e)}),pb=k("ZodGUID",(t,e)=>{Jd.init(t,e),Ie.init(t,e)}),cc=k("ZodUUID",(t,e)=>{Yd.init(t,e),Ie.init(t,e)}),$O=k("ZodURL",(t,e)=>{Qd.init(t,e),Ie.init(t,e)}),TO=k("ZodEmoji",(t,e)=>{ep.init(t,e),Ie.init(t,e)}),PO=k("ZodNanoID",(t,e)=>{tp.init(t,e),Ie.init(t,e)}),RO=k("ZodCUID",(t,e)=>{rp.init(t,e),Ie.init(t,e)}),CO=k("ZodCUID2",(t,e)=>{np.init(t,e),Ie.init(t,e)}),OO=k("ZodULID",(t,e)=>{sp.init(t,e),Ie.init(t,e)}),IO=k("ZodXID",(t,e)=>{op.init(t,e),Ie.init(t,e)}),AO=k("ZodKSUID",(t,e)=>{ip.init(t,e),Ie.init(t,e)}),NO=k("ZodIPv4",(t,e)=>{ap.init(t,e),Ie.init(t,e)}),DO=k("ZodIPv6",(t,e)=>{cp.init(t,e),Ie.init(t,e)}),MO=k("ZodCIDRv4",(t,e)=>{up.init(t,e),Ie.init(t,e)}),jO=k("ZodCIDRv6",(t,e)=>{lp.init(t,e),Ie.init(t,e)}),zO=k("ZodBase64",(t,e)=>{dp.init(t,e),Ie.init(t,e)}),LO=k("ZodBase64URL",(t,e)=>{pp.init(t,e),Ie.init(t,e)}),FO=k("ZodE164",(t,e)=>{mp.init(t,e),Ie.init(t,e)}),UO=k("ZodJWT",(t,e)=>{fp.init(t,e),Ie.init(t,e)}),gb=k("ZodNumber",(t,e)=>{Ga.init(t,e),je.init(t,e),t.gt=(n,s)=>t.check(ec(n,s)),t.gte=(n,s)=>t.check(Jo(n,s)),t.min=(n,s)=>t.check(Jo(n,s)),t.lt=(n,s)=>t.check(Qa(n,s)),t.lte=(n,s)=>t.check(Ko(n,s)),t.max=(n,s)=>t.check(Ko(n,s)),t.int=n=>t.check(mb(n)),t.safe=n=>t.check(mb(n)),t.positive=n=>t.check(ec(0,n)),t.nonnegative=n=>t.check(Jo(0,n)),t.negative=n=>t.check(Qa(0,n)),t.nonpositive=n=>t.check(Ko(0,n)),t.multipleOf=(n,s)=>t.check(tc(n,s)),t.step=(n,s)=>t.check(tc(n,s)),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});HO=k("ZodNumberFormat",(t,e)=>{hp.init(t,e),gb.init(t,e)});ZO=k("ZodBoolean",(t,e)=>{gp.init(t,e),je.init(t,e)});BO=k("ZodNull",(t,e)=>{yp.init(t,e),je.init(t,e)});qO=k("ZodUnknown",(t,e)=>{_p.init(t,e),je.init(t,e)});VO=k("ZodNever",(t,e)=>{xp.init(t,e),je.init(t,e)});GO=k("ZodArray",(t,e)=>{vp.init(t,e),je.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(zs(r,n)),t.nonempty=r=>t.check(zs(1,r)),t.max=(r,n)=>t.check(rc(r,n)),t.length=(r,n)=>t.check(nc(r,n)),t.unwrap=()=>t.element});_b=k("ZodObject",(t,e)=>{Ka.init(t,e),je.init(t,e),ae.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>St(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ae()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ae()}),t.strict=()=>t.clone({...t._zod.def,catchall:WO()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ae.extend(t,r),t.merge=r=>ae.merge(t,r),t.pick=r=>ae.pick(t,r),t.omit=r=>ae.omit(t,r),t.partial=(...r)=>ae.partial(bb,t,r[0]),t.required=(...r)=>ae.required(Sb,t,r[0])});xb=k("ZodUnion",(t,e)=>{Ja.init(t,e),je.init(t,e),t.options=e.options});KO=k("ZodDiscriminatedUnion",(t,e)=>{xb.init(t,e),bp.init(t,e)});JO=k("ZodIntersection",(t,e)=>{Sp.init(t,e),je.init(t,e)});YO=k("ZodRecord",(t,e)=>{kp.init(t,e),je.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});jm=k("ZodEnum",(t,e)=>{wp.init(t,e),je.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new jm({...e,checks:[],...ae.normalizeParams(s),entries:o})},t.exclude=(n,s)=>{let o={...e.entries};for(let i of n)if(r.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new jm({...e,checks:[],...ae.normalizeParams(s),entries:o})}});XO=k("ZodLiteral",(t,e)=>{Ep.init(t,e),je.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]}})});QO=k("ZodTransform",(t,e)=>{$p.init(t,e),je.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(ae.issue(o,r.value,e));else{let i=o;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(ae.issue(i))}};let s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});bb=k("ZodOptional",(t,e)=>{Tp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});eI=k("ZodNullable",(t,e)=>{Pp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});tI=k("ZodDefault",(t,e)=>{Rp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});nI=k("ZodPrefault",(t,e)=>{Cp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});Sb=k("ZodNonOptional",(t,e)=>{Op.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});iI=k("ZodCatch",(t,e)=>{Ip.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});cI=k("ZodPipe",(t,e)=>{Ap.init(t,e),je.init(t,e),t.in=e.in,t.out=e.out});uI=k("ZodReadonly",(t,e)=>{Np.init(t,e),je.init(t,e)});kb=k("ZodCustom",(t,e)=>{Dp.init(t,e),je.init(t,e)})});var Eb=v(()=>{});var $b=v(()=>{});var Tb=v(()=>{dt();Nm();Pm();Dm();Mm();Eb();dt();jv();Ya();Am();$b();Ct(Mv())});var Pb=v(()=>{Tb()});var Rb=v(()=>{Pb()});function Vb(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Wb(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Hm,Cb,an,dc,qe,Ob,Ib,gq,gI,yI,Zm,It,ei,Ab,Ye,Bt,qt,Xe,pc,Nb,Bm,Db,Mb,qm,ti,q,Vm,jb,zb,yq,mc,_I,fc,xI,ri,Fs,Lb,vI,bI,SI,kI,wI,EI,Wm,$I,TI,Gm,hc,PI,RI,gc,CI,ni,si,OI,oi,Us,II,ii,yc,_c,xc,_q,vc,bc,Sc,Fb,Ub,Hb,Km,Zb,ai,Hs,Bb,AI,Zs,NI,Bs,DI,Jm,MI,kc,jI,zI,LI,FI,UI,HI,ZI,BI,qI,VI,qs,WI,GI,wc,Ym,Xm,Qm,KI,JI,YI,ef,XI,QI,eA,tA,rA,qb,Ec,nA,$c,xq,sA,Vs,oA,vq,ci,iA,tf,aA,cA,uA,lA,dA,pA,mA,lc,fA,hA,gA,ui,rf,yA,_A,xA,vA,bA,SA,kA,wA,EA,$A,TA,PA,RA,CA,OA,IA,AA,NA,Ws,DA,MA,jA,Tc,zA,LA,FA,nf,UA,bq,Sq,kq,wq,Eq,$q,F,Um,Xn=v(()=>{Rb();Hm="2025-11-25",Cb=[Hm,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],an="io.modelcontextprotocol/related-task",dc="2.0",qe=wb(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Ob=Te([S(),ge().int()]),Ib=S(),gq=pt({ttl:ge().optional(),pollInterval:ge().optional()}),gI=j({ttl:ge().optional()}),yI=j({taskId:S()}),Zm=pt({progressToken:Ob.optional(),[an]:yI.optional()}),It=j({_meta:Zm.optional()}),ei=It.extend({task:gI.optional()}),Ab=t=>ei.safeParse(t).success,Ye=j({method:S(),params:It.loose().optional()}),Bt=j({_meta:Zm.optional()}),qt=j({method:S(),params:Bt.loose().optional()}),Xe=pt({_meta:Zm.optional()}),pc=Te([S(),ge().int()]),Nb=j({jsonrpc:H(dc),id:pc,...Ye.shape}).strict(),Bm=t=>Nb.safeParse(t).success,Db=j({jsonrpc:H(dc),...qt.shape}).strict(),Mb=t=>Db.safeParse(t).success,qm=j({jsonrpc:H(dc),id:pc,result:Xe}).strict(),ti=t=>qm.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"})(q||(q={}));Vm=j({jsonrpc:H(dc),id:pc.optional(),error:j({code:ge().int(),message:S(),data:Ae().optional()})}).strict(),jb=t=>Vm.safeParse(t).success,zb=Te([Nb,Db,qm,Vm]),yq=Te([qm,Vm]),mc=Xe.strict(),_I=Bt.extend({requestId:pc.optional(),reason:S().optional()}),fc=qt.extend({method:H("notifications/cancelled"),params:_I}),xI=j({src:S(),mimeType:S().optional(),sizes:ce(S()).optional(),theme:St(["light","dark"]).optional()}),ri=j({icons:ce(xI).optional()}),Fs=j({name:S(),title:S().optional()}),Lb=Fs.extend({...Fs.shape,...ri.shape,version:S(),websiteUrl:S().optional(),description:S().optional()}),vI=uc(j({applyDefaults:We().optional()}),Ee(S(),Ae())),bI=Fm(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,uc(j({form:vI.optional(),url:qe.optional()}),Ee(S(),Ae()).optional())),SI=pt({list:qe.optional(),cancel:qe.optional(),requests:pt({sampling:pt({createMessage:qe.optional()}).optional(),elicitation:pt({create:qe.optional()}).optional()}).optional()}),kI=pt({list:qe.optional(),cancel:qe.optional(),requests:pt({tools:pt({call:qe.optional()}).optional()}).optional()}),wI=j({experimental:Ee(S(),qe).optional(),sampling:j({context:qe.optional(),tools:qe.optional()}).optional(),elicitation:bI.optional(),roots:j({listChanged:We().optional()}).optional(),tasks:SI.optional(),extensions:Ee(S(),qe).optional()}),EI=It.extend({protocolVersion:S(),capabilities:wI,clientInfo:Lb}),Wm=Ye.extend({method:H("initialize"),params:EI}),$I=j({experimental:Ee(S(),qe).optional(),logging:qe.optional(),completions:qe.optional(),prompts:j({listChanged:We().optional()}).optional(),resources:j({subscribe:We().optional(),listChanged:We().optional()}).optional(),tools:j({listChanged:We().optional()}).optional(),tasks:kI.optional(),extensions:Ee(S(),qe).optional()}),TI=Xe.extend({protocolVersion:S(),capabilities:$I,serverInfo:Lb,instructions:S().optional()}),Gm=qt.extend({method:H("notifications/initialized"),params:Bt.optional()}),hc=Ye.extend({method:H("ping"),params:It.optional()}),PI=j({progress:ge(),total:Ne(ge()),message:Ne(S())}),RI=j({...Bt.shape,...PI.shape,progressToken:Ob}),gc=qt.extend({method:H("notifications/progress"),params:RI}),CI=It.extend({cursor:Ib.optional()}),ni=Ye.extend({params:CI.optional()}),si=Xe.extend({nextCursor:Ib.optional()}),OI=St(["working","input_required","completed","failed","cancelled"]),oi=j({taskId:S(),status:OI,ttl:Te([ge(),yb()]),createdAt:S(),lastUpdatedAt:S(),pollInterval:Ne(ge()),statusMessage:Ne(S())}),Us=Xe.extend({task:oi}),II=Bt.merge(oi),ii=qt.extend({method:H("notifications/tasks/status"),params:II}),yc=Ye.extend({method:H("tasks/get"),params:It.extend({taskId:S()})}),_c=Xe.merge(oi),xc=Ye.extend({method:H("tasks/result"),params:It.extend({taskId:S()})}),_q=Xe.loose(),vc=ni.extend({method:H("tasks/list")}),bc=si.extend({tasks:ce(oi)}),Sc=Ye.extend({method:H("tasks/cancel"),params:It.extend({taskId:S()})}),Fb=Xe.merge(oi),Ub=j({uri:S(),mimeType:Ne(S()),_meta:Ee(S(),Ae()).optional()}),Hb=Ub.extend({text:S()}),Km=S().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Zb=Ub.extend({blob:Km}),ai=St(["user","assistant"]),Hs=j({audience:ce(ai).optional(),priority:ge().min(0).max(1).optional(),lastModified:Xo.datetime({offset:!0}).optional()}),Bb=j({...Fs.shape,...ri.shape,uri:S(),description:Ne(S()),mimeType:Ne(S()),size:Ne(ge()),annotations:Hs.optional(),_meta:Ne(pt({}))}),AI=j({...Fs.shape,...ri.shape,uriTemplate:S(),description:Ne(S()),mimeType:Ne(S()),annotations:Hs.optional(),_meta:Ne(pt({}))}),Zs=ni.extend({method:H("resources/list")}),NI=si.extend({resources:ce(Bb)}),Bs=ni.extend({method:H("resources/templates/list")}),DI=si.extend({resourceTemplates:ce(AI)}),Jm=It.extend({uri:S()}),MI=Jm,kc=Ye.extend({method:H("resources/read"),params:MI}),jI=Xe.extend({contents:ce(Te([Hb,Zb]))}),zI=qt.extend({method:H("notifications/resources/list_changed"),params:Bt.optional()}),LI=Jm,FI=Ye.extend({method:H("resources/subscribe"),params:LI}),UI=Jm,HI=Ye.extend({method:H("resources/unsubscribe"),params:UI}),ZI=Bt.extend({uri:S()}),BI=qt.extend({method:H("notifications/resources/updated"),params:ZI}),qI=j({name:S(),description:Ne(S()),required:Ne(We())}),VI=j({...Fs.shape,...ri.shape,description:Ne(S()),arguments:Ne(ce(qI)),_meta:Ne(pt({}))}),qs=ni.extend({method:H("prompts/list")}),WI=si.extend({prompts:ce(VI)}),GI=It.extend({name:S(),arguments:Ee(S(),S()).optional()}),wc=Ye.extend({method:H("prompts/get"),params:GI}),Ym=j({type:H("text"),text:S(),annotations:Hs.optional(),_meta:Ee(S(),Ae()).optional()}),Xm=j({type:H("image"),data:Km,mimeType:S(),annotations:Hs.optional(),_meta:Ee(S(),Ae()).optional()}),Qm=j({type:H("audio"),data:Km,mimeType:S(),annotations:Hs.optional(),_meta:Ee(S(),Ae()).optional()}),KI=j({type:H("tool_use"),name:S(),id:S(),input:Ee(S(),Ae()),_meta:Ee(S(),Ae()).optional()}),JI=j({type:H("resource"),resource:Te([Hb,Zb]),annotations:Hs.optional(),_meta:Ee(S(),Ae()).optional()}),YI=Bb.extend({type:H("resource_link")}),ef=Te([Ym,Xm,Qm,YI,JI]),XI=j({role:ai,content:ef}),QI=Xe.extend({description:S().optional(),messages:ce(XI)}),eA=qt.extend({method:H("notifications/prompts/list_changed"),params:Bt.optional()}),tA=j({title:S().optional(),readOnlyHint:We().optional(),destructiveHint:We().optional(),idempotentHint:We().optional(),openWorldHint:We().optional()}),rA=j({taskSupport:St(["required","optional","forbidden"]).optional()}),qb=j({...Fs.shape,...ri.shape,description:S().optional(),inputSchema:j({type:H("object"),properties:Ee(S(),qe).optional(),required:ce(S()).optional()}).catchall(Ae()),outputSchema:j({type:H("object"),properties:Ee(S(),qe).optional(),required:ce(S()).optional()}).catchall(Ae()).optional(),annotations:tA.optional(),execution:rA.optional(),_meta:Ee(S(),Ae()).optional()}),Ec=ni.extend({method:H("tools/list")}),nA=si.extend({tools:ce(qb)}),$c=Xe.extend({content:ce(ef).default([]),structuredContent:Ee(S(),Ae()).optional(),isError:We().optional()}),xq=$c.or(Xe.extend({toolResult:Ae()})),sA=ei.extend({name:S(),arguments:Ee(S(),Ae()).optional()}),Vs=Ye.extend({method:H("tools/call"),params:sA}),oA=qt.extend({method:H("notifications/tools/list_changed"),params:Bt.optional()}),vq=j({autoRefresh:We().default(!0),debounceMs:ge().int().nonnegative().default(300)}),ci=St(["debug","info","notice","warning","error","critical","alert","emergency"]),iA=It.extend({level:ci}),tf=Ye.extend({method:H("logging/setLevel"),params:iA}),aA=Bt.extend({level:ci,logger:S().optional(),data:Ae()}),cA=qt.extend({method:H("notifications/message"),params:aA}),uA=j({name:S().optional()}),lA=j({hints:ce(uA).optional(),costPriority:ge().min(0).max(1).optional(),speedPriority:ge().min(0).max(1).optional(),intelligencePriority:ge().min(0).max(1).optional()}),dA=j({mode:St(["auto","required","none"]).optional()}),pA=j({type:H("tool_result"),toolUseId:S().describe("The unique identifier for the corresponding tool call."),content:ce(ef).default([]),structuredContent:j({}).loose().optional(),isError:We().optional(),_meta:Ee(S(),Ae()).optional()}),mA=Lm("type",[Ym,Xm,Qm]),lc=Lm("type",[Ym,Xm,Qm,KI,pA]),fA=j({role:ai,content:Te([lc,ce(lc)]),_meta:Ee(S(),Ae()).optional()}),hA=ei.extend({messages:ce(fA),modelPreferences:lA.optional(),systemPrompt:S().optional(),includeContext:St(["none","thisServer","allServers"]).optional(),temperature:ge().optional(),maxTokens:ge().int(),stopSequences:ce(S()).optional(),metadata:qe.optional(),tools:ce(qb).optional(),toolChoice:dA.optional()}),gA=Ye.extend({method:H("sampling/createMessage"),params:hA}),ui=Xe.extend({model:S(),stopReason:Ne(St(["endTurn","stopSequence","maxTokens"]).or(S())),role:ai,content:mA}),rf=Xe.extend({model:S(),stopReason:Ne(St(["endTurn","stopSequence","maxTokens","toolUse"]).or(S())),role:ai,content:Te([lc,ce(lc)])}),yA=j({type:H("boolean"),title:S().optional(),description:S().optional(),default:We().optional()}),_A=j({type:H("string"),title:S().optional(),description:S().optional(),minLength:ge().optional(),maxLength:ge().optional(),format:St(["email","uri","date","date-time"]).optional(),default:S().optional()}),xA=j({type:St(["number","integer"]),title:S().optional(),description:S().optional(),minimum:ge().optional(),maximum:ge().optional(),default:ge().optional()}),vA=j({type:H("string"),title:S().optional(),description:S().optional(),enum:ce(S()),default:S().optional()}),bA=j({type:H("string"),title:S().optional(),description:S().optional(),oneOf:ce(j({const:S(),title:S()})),default:S().optional()}),SA=j({type:H("string"),title:S().optional(),description:S().optional(),enum:ce(S()),enumNames:ce(S()).optional(),default:S().optional()}),kA=Te([vA,bA]),wA=j({type:H("array"),title:S().optional(),description:S().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:j({type:H("string"),enum:ce(S())}),default:ce(S()).optional()}),EA=j({type:H("array"),title:S().optional(),description:S().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:j({anyOf:ce(j({const:S(),title:S()}))}),default:ce(S()).optional()}),$A=Te([wA,EA]),TA=Te([SA,kA,$A]),PA=Te([TA,yA,_A,xA]),RA=ei.extend({mode:H("form").optional(),message:S(),requestedSchema:j({type:H("object"),properties:Ee(S(),PA),required:ce(S()).optional()})}),CA=ei.extend({mode:H("url"),message:S(),elicitationId:S(),url:S().url()}),OA=Te([RA,CA]),IA=Ye.extend({method:H("elicitation/create"),params:OA}),AA=Bt.extend({elicitationId:S()}),NA=qt.extend({method:H("notifications/elicitation/complete"),params:AA}),Ws=Xe.extend({action:St(["accept","decline","cancel"]),content:Fm(t=>t===null?void 0:t,Ee(S(),Te([S(),ge(),We(),ce(S())])).optional())}),DA=j({type:H("ref/resource"),uri:S()}),MA=j({type:H("ref/prompt"),name:S()}),jA=It.extend({ref:Te([MA,DA]),argument:j({name:S(),value:S()}),context:j({arguments:Ee(S(),S()).optional()}).optional()}),Tc=Ye.extend({method:H("completion/complete"),params:jA});zA=Xe.extend({completion:pt({values:ce(S()).max(100),total:Ne(ge().int()),hasMore:Ne(We())})}),LA=j({uri:S().startsWith("file://"),name:S().optional(),_meta:Ee(S(),Ae()).optional()}),FA=Ye.extend({method:H("roots/list"),params:It.optional()}),nf=Xe.extend({roots:ce(LA)}),UA=qt.extend({method:H("notifications/roots/list_changed"),params:Bt.optional()}),bq=Te([hc,Wm,Tc,tf,wc,qs,Zs,Bs,kc,FI,HI,Vs,Ec,yc,xc,vc,Sc]),Sq=Te([fc,gc,Gm,UA,ii]),kq=Te([mc,ui,rf,Ws,nf,_c,bc,Us]),wq=Te([hc,gA,IA,FA,yc,xc,vc,Sc]),Eq=Te([fc,gc,cA,BI,zI,oA,eA,ii,NA]),$q=Te([mc,TI,zA,QI,WI,NI,DI,jI,$c,nA,_c,bc,Us]),F=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===q.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new Um(s.elicitations,r)}return new t(e,r,n)}},Um=class extends F{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(q.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function cn(t){return t==="completed"||t==="failed"||t==="cancelled"}var Gb=v(()=>{});var Jb,Kb,Yb,Pc=v(()=>{Jb=Symbol("Let zodToJsonSchema decide on which parser to use"),Kb={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"},Yb=t=>typeof t=="string"?{...Kb,name:t}:{...Kb,...t}});var Xb,sf=v(()=>{Pc();Xb=t=>{let e=Yb(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,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function of(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ue(t,e,r,n,s){t[e]=r,of(t,e,n,s)}var un=v(()=>{});var Rc,Cc=v(()=>{Rc=(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 De(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Rc(e,t.currentPath):e.join("/")}}var Vt=v(()=>{Cc()});function Qb(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==R.ZodAny&&(r.items=J(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ue(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ue(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ue(r,"minItems",t.exactLength.value,t.exactLength.message,e),ue(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var af=v(()=>{zo();un();He()});function eS(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?ue(r,"minimum",n.value,n.message,e):ue(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ue(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ue(r,"maximum",n.value,n.message,e):ue(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ue(r,"maximum",n.value,n.message,e));break;case"multipleOf":ue(r,"multipleOf",n.value,n.message,e);break}return r}var cf=v(()=>{un()});function tS(){return{type:"boolean"}}var uf=v(()=>{});function Oc(t,e){return J(t.type._def,e)}var Ic=v(()=>{He()});var rS,lf=v(()=>{He();rS=(t,e)=>J(t.innerType._def,e)});function df(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>df(t,e,s))};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 HA(t,e)}}var HA,pf=v(()=>{un();HA=(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":ue(r,"minimum",n.value,n.message,e);break;case"max":ue(r,"maximum",n.value,n.message,e);break}return r}});function nS(t,e){return{...J(t.innerType._def,e),default:t.defaultValue()}}var mf=v(()=>{He()});function sS(t,e){return e.effectStrategy==="input"?J(t.schema._def,e):De(e)}var ff=v(()=>{He();Vt()});function oS(t){return{type:"string",enum:Array.from(t.values)}}var hf=v(()=>{});function iS(t,e){let r=[J(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),J(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(o=>{if(ZA(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}var ZA,gf=v(()=>{He();ZA=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function aS(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 yf=v(()=>{});function Ac(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ue(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ue(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":or(r,"email",n.message,e);break;case"format:idn-email":or(r,"idn-email",n.message,e);break;case"pattern:zod":mt(r,sr.email,n.message,e);break}break;case"url":or(r,"uri",n.message,e);break;case"uuid":or(r,"uuid",n.message,e);break;case"regex":mt(r,n.regex,n.message,e);break;case"cuid":mt(r,sr.cuid,n.message,e);break;case"cuid2":mt(r,sr.cuid2,n.message,e);break;case"startsWith":mt(r,RegExp(`^${xf(n.value,e)}`),n.message,e);break;case"endsWith":mt(r,RegExp(`${xf(n.value,e)}$`),n.message,e);break;case"datetime":or(r,"date-time",n.message,e);break;case"date":or(r,"date",n.message,e);break;case"time":or(r,"time",n.message,e);break;case"duration":or(r,"duration",n.message,e);break;case"length":ue(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ue(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{mt(r,RegExp(xf(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&or(r,"ipv4",n.message,e),n.version!=="v4"&&or(r,"ipv6",n.message,e);break}case"base64url":mt(r,sr.base64url,n.message,e);break;case"jwt":mt(r,sr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&mt(r,sr.ipv4Cidr,n.message,e),n.version!=="v4"&&mt(r,sr.ipv6Cidr,n.message,e);break}case"emoji":mt(r,sr.emoji(),n.message,e);break;case"ulid":{mt(r,sr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{or(r,"binary",n.message,e);break}case"contentEncoding:base64":{ue(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{mt(r,sr.base64,n.message,e);break}}break}case"nanoid":mt(r,sr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function xf(t,e){return e.patternStrategy==="escape"?qA(t):t}function qA(t){let e="";for(let r=0;r<t.length;r++)BA.has(t[r])||(e+="\\"),e+=t[r];return e}function or(t,e,r,n){t.format||t.anyOf?.some(s=>s.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}}})):ue(t,"format",e,r,n)}function mt(t,e,r,n){t.pattern||t.allOf?.some(s=>s.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:cS(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ue(t,"pattern",cS(e,n),r,n)}function cS(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,s="",o=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],a=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
|
60
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of this.seen.entries()){let l=d[1];if(e===d[0]){i(d);continue}if(n.external){let f=n.external.registry.get(d[0])?.id;if(e!==d[0]&&f){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let m=this.seen.get(d),f=m.def??m.schema,p={...f};if(m.ref===null)return;let h=m.ref;if(m.ref=null,h){a(h,l);let g=this.seen.get(h).schema;g.$ref&&l.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,p))}m.isParent||this.override({zodSchema:d,jsonSchema:f,path:m.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[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 d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,s.def);let u=n.external?.defs??{};for(let d of this.seen.entries()){let l=d[1];l.def&&l.defId&&(u[l.defId]=l.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 Jv=v(()=>{});var dt=v(()=>{js();qd();zd();zv();qa();Yd();Sr();Ba();Ya();Fp();Jd();Gv();Wv();Kv();Jv()});var Pm=v(()=>{dt()});function Rm(t,e){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},...ae.normalizeParams(e)};return new wO(r)}var kO,wO,Yv=v(()=>{dt();dt();Pm();kO=k("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");xe.init(t,e),t.def=e,t.parse=(r,n)=>Fd(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Gn(t,r,n),t.parseAsync=async(r,n)=>Hd(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Kn(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)=>It(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),wO=k("ZodMiniObject",(t,e)=>{Ka.init(t,e),kO.init(t,e),ae.defineLazy(t,"shape",()=>e.shape)})});var Xv=v(()=>{});var Qv=v(()=>{});var eb=v(()=>{});var tb=v(()=>{dt();Pm();Yv();Xv();dt();Ya();Qv();eb()});var rb=v(()=>{tb()});var Cm=v(()=>{rb()});function Bt(t){return!!t._zod}function Xn(t){let e=Object.values(t);if(e.length===0)return Rm({});let r=e.every(Bt),n=e.every(s=>!Bt(s));if(r)return Rm(t);if(n)return Ed(t);throw new Error("Mixed Zod versions detected in object shape.")}function on(t,e){return Bt(t)?Gn(t,e):t.safeParse(e)}async function oc(t,e){return Bt(t)?await Kn(t,e):await t.safeParseAsync(e)}function an(t){if(!t)return;let e;if(Bt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Us(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(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return Xn(t)}}if(Bt(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 ic(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 sb(t){return t.description}function ob(t){if(Bt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function ac(t){if(Bt(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.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 Xo=v(()=>{Lo();Cm()});var Om=v(()=>{dt()});var Qo={};Fe(Qo,{ZodISODate:()=>ab,ZodISODateTime:()=>ib,ZodISODuration:()=>ub,ZodISOTime:()=>cb,date:()=>Am,datetime:()=>Im,duration:()=>Dm,time:()=>Nm});function Im(t){return Hv(ib,t)}function Am(t){return Zv(ab,t)}function Nm(t){return Bv(cb,t)}function Dm(t){return qv(ub,t)}var ib,ab,cb,ub,Mm=v(()=>{dt();jm();ib=k("ZodISODateTime",(t,e)=>{Av.init(t,e),Ie.init(t,e)});ab=k("ZodISODate",(t,e)=>{Nv.init(t,e),Ie.init(t,e)});cb=k("ZodISOTime",(t,e)=>{Dv.init(t,e),Ie.init(t,e)});ub=k("ZodISODuration",(t,e)=>{Mv.init(t,e),Ie.init(t,e)})});var lb,fq,ei,zm=v(()=>{dt();dt();lb=(t,e)=>{Ha.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>jd(t,r)},flatten:{value:r=>Md(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},fq=k("ZodError",lb),ei=k("ZodError",lb,{Parent:Error})});var db,pb,mb,fb,Lm=v(()=>{dt();zm();db=Ld(ei),pb=Ud(ei),mb=Zd(ei),fb=Bd(ei)});function S(t){return Up(NO,t)}function ge(t){return um(xb,t)}function gb(t){return lm(XO,t)}function Ge(t){return dm(QO,t)}function vb(t){return pm(eI,t)}function Ae(){return mm(tI)}function nI(t){return fm(rI,t)}function ce(t,e){return Vv(sI,t,e)}function j(t,e){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},...ae.normalizeParams(e)};return new bb(r)}function pt(t,e){return new bb({type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},catchall:Ae(),...ae.normalizeParams(e)})}function Te(t,e){return new Sb({type:"union",options:t,...ae.normalizeParams(e)})}function Hm(t,e,r){return new oI({type:"union",options:e,discriminator:t,...ae.normalizeParams(r)})}function uc(t,e){return new iI({type:"intersection",left:t,right:e})}function Ee(t,e,r){return new aI({type:"record",keyType:t,valueType:e,...ae.normalizeParams(r)})}function St(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Fm({type:"enum",entries:r,...ae.normalizeParams(e)})}function H(t,e){return new cI({type:"literal",values:Array.isArray(t)?t:[t],...ae.normalizeParams(e)})}function kb(t){return new uI({type:"transform",transform:t})}function Ne(t){return new wb({type:"optional",innerType:t})}function yb(t){return new lI({type:"nullable",innerType:t})}function pI(t,e){return new dI({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function fI(t,e){return new mI({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function hI(t,e){return new Eb({type:"nonoptional",innerType:t,...ae.normalizeParams(e)})}function yI(t,e){return new gI({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Um(t,e){return new _I({type:"pipe",in:t,out:e})}function vI(t){return new xI({type:"readonly",innerType:t})}function bI(t){let e=new Je({check:"custom"});return e._zod.check=t,e}function Tb(t,e){return Em($b,t??(()=>!0),e)}function SI(t,e={}){return $m($b,t,e)}function kI(t){let e=bI(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ae.issue(n,r.value,e._zod.def));else{let s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(ae.issue(s))}},t(r.value,r)));return e}function Zm(t,e){return Um(kb(t),e)}var je,_b,NO,Ie,DO,hb,cc,MO,jO,zO,LO,FO,UO,HO,ZO,BO,qO,VO,WO,GO,KO,JO,YO,xb,XO,QO,eI,tI,rI,sI,bb,Sb,oI,iI,aI,Fm,cI,uI,wb,lI,dI,mI,Eb,gI,_I,xI,$b,jm=v(()=>{dt();dt();Om();Mm();Lm();je=k("ZodType",(t,e)=>(xe.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)=>It(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>db(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>mb(t,r,n),t.parseAsync=async(r,n)=>pb(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>fb(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(SI(r,n)),t.superRefine=r=>t.check(kI(r)),t.overwrite=r=>t.check(Jn(r)),t.optional=()=>Ne(t),t.nullable=()=>yb(t),t.nullish=()=>Ne(yb(t)),t.nonoptional=r=>hI(t,r),t.array=()=>ce(t),t.or=r=>Te([t,r]),t.and=r=>uc(t,r),t.transform=r=>Um(t,kb(r)),t.default=r=>pI(t,r),t.prefault=r=>fI(t,r),t.catch=r=>yI(t,r),t.pipe=r=>Um(t,r),t.readonly=()=>vI(t),t.describe=r=>{let n=t.clone();return sn.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return sn.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return sn.get(t);let n=t.clone();return sn.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),_b=k("_ZodString",(t,e)=>{Go.init(t,e),je.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(hm(...n)),t.includes=(...n)=>t.check(_m(...n)),t.startsWith=(...n)=>t.check(xm(...n)),t.endsWith=(...n)=>t.check(vm(...n)),t.min=(...n)=>t.check(Fs(...n)),t.max=(...n)=>t.check(rc(...n)),t.length=(...n)=>t.check(nc(...n)),t.nonempty=(...n)=>t.check(Fs(1,...n)),t.lowercase=n=>t.check(gm(n)),t.uppercase=n=>t.check(ym(n)),t.trim=()=>t.check(Sm()),t.normalize=(...n)=>t.check(bm(...n)),t.toLowerCase=()=>t.check(km()),t.toUpperCase=()=>t.check(wm())}),NO=k("ZodString",(t,e)=>{Go.init(t,e),_b.init(t,e),t.email=r=>t.check(Hp(DO,r)),t.url=r=>t.check(Wp(MO,r)),t.jwt=r=>t.check(cm(YO,r)),t.emoji=r=>t.check(Gp(jO,r)),t.guid=r=>t.check(Xa(hb,r)),t.uuid=r=>t.check(Zp(cc,r)),t.uuidv4=r=>t.check(Bp(cc,r)),t.uuidv6=r=>t.check(qp(cc,r)),t.uuidv7=r=>t.check(Vp(cc,r)),t.nanoid=r=>t.check(Kp(zO,r)),t.guid=r=>t.check(Xa(hb,r)),t.cuid=r=>t.check(Jp(LO,r)),t.cuid2=r=>t.check(Yp(FO,r)),t.ulid=r=>t.check(Xp(UO,r)),t.base64=r=>t.check(om(GO,r)),t.base64url=r=>t.check(im(KO,r)),t.xid=r=>t.check(Qp(HO,r)),t.ksuid=r=>t.check(em(ZO,r)),t.ipv4=r=>t.check(tm(BO,r)),t.ipv6=r=>t.check(rm(qO,r)),t.cidrv4=r=>t.check(nm(VO,r)),t.cidrv6=r=>t.check(sm(WO,r)),t.e164=r=>t.check(am(JO,r)),t.datetime=r=>t.check(Im(r)),t.date=r=>t.check(Am(r)),t.time=r=>t.check(Nm(r)),t.duration=r=>t.check(Dm(r))});Ie=k("ZodStringFormat",(t,e)=>{we.init(t,e),_b.init(t,e)}),DO=k("ZodEmail",(t,e)=>{tp.init(t,e),Ie.init(t,e)}),hb=k("ZodGUID",(t,e)=>{Qd.init(t,e),Ie.init(t,e)}),cc=k("ZodUUID",(t,e)=>{ep.init(t,e),Ie.init(t,e)}),MO=k("ZodURL",(t,e)=>{rp.init(t,e),Ie.init(t,e)}),jO=k("ZodEmoji",(t,e)=>{np.init(t,e),Ie.init(t,e)}),zO=k("ZodNanoID",(t,e)=>{sp.init(t,e),Ie.init(t,e)}),LO=k("ZodCUID",(t,e)=>{op.init(t,e),Ie.init(t,e)}),FO=k("ZodCUID2",(t,e)=>{ip.init(t,e),Ie.init(t,e)}),UO=k("ZodULID",(t,e)=>{ap.init(t,e),Ie.init(t,e)}),HO=k("ZodXID",(t,e)=>{cp.init(t,e),Ie.init(t,e)}),ZO=k("ZodKSUID",(t,e)=>{up.init(t,e),Ie.init(t,e)}),BO=k("ZodIPv4",(t,e)=>{lp.init(t,e),Ie.init(t,e)}),qO=k("ZodIPv6",(t,e)=>{dp.init(t,e),Ie.init(t,e)}),VO=k("ZodCIDRv4",(t,e)=>{pp.init(t,e),Ie.init(t,e)}),WO=k("ZodCIDRv6",(t,e)=>{mp.init(t,e),Ie.init(t,e)}),GO=k("ZodBase64",(t,e)=>{fp.init(t,e),Ie.init(t,e)}),KO=k("ZodBase64URL",(t,e)=>{hp.init(t,e),Ie.init(t,e)}),JO=k("ZodE164",(t,e)=>{gp.init(t,e),Ie.init(t,e)}),YO=k("ZodJWT",(t,e)=>{yp.init(t,e),Ie.init(t,e)}),xb=k("ZodNumber",(t,e)=>{Ga.init(t,e),je.init(t,e),t.gt=(n,s)=>t.check(ec(n,s)),t.gte=(n,s)=>t.check(Yo(n,s)),t.min=(n,s)=>t.check(Yo(n,s)),t.lt=(n,s)=>t.check(Qa(n,s)),t.lte=(n,s)=>t.check(Jo(n,s)),t.max=(n,s)=>t.check(Jo(n,s)),t.int=n=>t.check(gb(n)),t.safe=n=>t.check(gb(n)),t.positive=n=>t.check(ec(0,n)),t.nonnegative=n=>t.check(Yo(0,n)),t.negative=n=>t.check(Qa(0,n)),t.nonpositive=n=>t.check(Jo(0,n)),t.multipleOf=(n,s)=>t.check(tc(n,s)),t.step=(n,s)=>t.check(tc(n,s)),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});XO=k("ZodNumberFormat",(t,e)=>{_p.init(t,e),xb.init(t,e)});QO=k("ZodBoolean",(t,e)=>{xp.init(t,e),je.init(t,e)});eI=k("ZodNull",(t,e)=>{vp.init(t,e),je.init(t,e)});tI=k("ZodUnknown",(t,e)=>{bp.init(t,e),je.init(t,e)});rI=k("ZodNever",(t,e)=>{Sp.init(t,e),je.init(t,e)});sI=k("ZodArray",(t,e)=>{kp.init(t,e),je.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Fs(r,n)),t.nonempty=r=>t.check(Fs(1,r)),t.max=(r,n)=>t.check(rc(r,n)),t.length=(r,n)=>t.check(nc(r,n)),t.unwrap=()=>t.element});bb=k("ZodObject",(t,e)=>{Ka.init(t,e),je.init(t,e),ae.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>St(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ae()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ae()}),t.strict=()=>t.clone({...t._zod.def,catchall:nI()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ae.extend(t,r),t.merge=r=>ae.merge(t,r),t.pick=r=>ae.pick(t,r),t.omit=r=>ae.omit(t,r),t.partial=(...r)=>ae.partial(wb,t,r[0]),t.required=(...r)=>ae.required(Eb,t,r[0])});Sb=k("ZodUnion",(t,e)=>{Ja.init(t,e),je.init(t,e),t.options=e.options});oI=k("ZodDiscriminatedUnion",(t,e)=>{Sb.init(t,e),wp.init(t,e)});iI=k("ZodIntersection",(t,e)=>{Ep.init(t,e),je.init(t,e)});aI=k("ZodRecord",(t,e)=>{$p.init(t,e),je.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Fm=k("ZodEnum",(t,e)=>{Tp.init(t,e),je.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Fm({...e,checks:[],...ae.normalizeParams(s),entries:o})},t.exclude=(n,s)=>{let o={...e.entries};for(let i of n)if(r.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new Fm({...e,checks:[],...ae.normalizeParams(s),entries:o})}});cI=k("ZodLiteral",(t,e)=>{Pp.init(t,e),je.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]}})});uI=k("ZodTransform",(t,e)=>{Rp.init(t,e),je.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(ae.issue(o,r.value,e));else{let i=o;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(ae.issue(i))}};let s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});wb=k("ZodOptional",(t,e)=>{Cp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});lI=k("ZodNullable",(t,e)=>{Op.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});dI=k("ZodDefault",(t,e)=>{Ip.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});mI=k("ZodPrefault",(t,e)=>{Ap.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});Eb=k("ZodNonOptional",(t,e)=>{Np.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});gI=k("ZodCatch",(t,e)=>{Dp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});_I=k("ZodPipe",(t,e)=>{Mp.init(t,e),je.init(t,e),t.in=e.in,t.out=e.out});xI=k("ZodReadonly",(t,e)=>{jp.init(t,e),je.init(t,e)});$b=k("ZodCustom",(t,e)=>{zp.init(t,e),je.init(t,e)})});var Pb=v(()=>{});var Rb=v(()=>{});var Cb=v(()=>{dt();jm();Om();zm();Lm();Pb();dt();Fv();Ya();Mm();Rb();Ot(Lv())});var Ob=v(()=>{Cb()});var Ib=v(()=>{Ob()});function Kb(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Jb(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var qm,Ab,cn,dc,We,Nb,Db,Cq,$I,TI,Vm,At,ti,Mb,Ye,qt,Vt,Xe,pc,jb,Wm,zb,Lb,Gm,ri,q,Km,Fb,Ub,Oq,mc,PI,fc,RI,ni,Hs,Hb,CI,OI,II,AI,NI,DI,Jm,MI,jI,Ym,hc,zI,LI,gc,FI,si,oi,UI,ii,Zs,HI,ai,yc,_c,xc,Iq,vc,bc,Sc,Zb,Bb,qb,Xm,Vb,ci,Bs,Wb,ZI,qs,BI,Vs,qI,Qm,VI,kc,WI,GI,KI,JI,YI,XI,QI,eA,tA,rA,Ws,nA,sA,wc,ef,tf,rf,oA,iA,aA,nf,cA,uA,lA,dA,pA,Gb,Ec,mA,$c,Aq,fA,Gs,hA,Nq,ui,gA,sf,yA,_A,xA,vA,bA,SA,kA,lc,wA,EA,$A,li,of,TA,PA,RA,CA,OA,IA,AA,NA,DA,MA,jA,zA,LA,FA,UA,HA,ZA,BA,Ks,qA,VA,WA,Tc,GA,KA,JA,af,YA,Dq,Mq,jq,zq,Lq,Fq,F,Bm,Qn=v(()=>{Ib();qm="2025-11-25",Ab=[qm,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],cn="io.modelcontextprotocol/related-task",dc="2.0",We=Tb(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Nb=Te([S(),ge().int()]),Db=S(),Cq=pt({ttl:ge().optional(),pollInterval:ge().optional()}),$I=j({ttl:ge().optional()}),TI=j({taskId:S()}),Vm=pt({progressToken:Nb.optional(),[cn]:TI.optional()}),At=j({_meta:Vm.optional()}),ti=At.extend({task:$I.optional()}),Mb=t=>ti.safeParse(t).success,Ye=j({method:S(),params:At.loose().optional()}),qt=j({_meta:Vm.optional()}),Vt=j({method:S(),params:qt.loose().optional()}),Xe=pt({_meta:Vm.optional()}),pc=Te([S(),ge().int()]),jb=j({jsonrpc:H(dc),id:pc,...Ye.shape}).strict(),Wm=t=>jb.safeParse(t).success,zb=j({jsonrpc:H(dc),...Vt.shape}).strict(),Lb=t=>zb.safeParse(t).success,Gm=j({jsonrpc:H(dc),id:pc,result:Xe}).strict(),ri=t=>Gm.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"})(q||(q={}));Km=j({jsonrpc:H(dc),id:pc.optional(),error:j({code:ge().int(),message:S(),data:Ae().optional()})}).strict(),Fb=t=>Km.safeParse(t).success,Ub=Te([jb,zb,Gm,Km]),Oq=Te([Gm,Km]),mc=Xe.strict(),PI=qt.extend({requestId:pc.optional(),reason:S().optional()}),fc=Vt.extend({method:H("notifications/cancelled"),params:PI}),RI=j({src:S(),mimeType:S().optional(),sizes:ce(S()).optional(),theme:St(["light","dark"]).optional()}),ni=j({icons:ce(RI).optional()}),Hs=j({name:S(),title:S().optional()}),Hb=Hs.extend({...Hs.shape,...ni.shape,version:S(),websiteUrl:S().optional(),description:S().optional()}),CI=uc(j({applyDefaults:Ge().optional()}),Ee(S(),Ae())),OI=Zm(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,uc(j({form:CI.optional(),url:We.optional()}),Ee(S(),Ae()).optional())),II=pt({list:We.optional(),cancel:We.optional(),requests:pt({sampling:pt({createMessage:We.optional()}).optional(),elicitation:pt({create:We.optional()}).optional()}).optional()}),AI=pt({list:We.optional(),cancel:We.optional(),requests:pt({tools:pt({call:We.optional()}).optional()}).optional()}),NI=j({experimental:Ee(S(),We).optional(),sampling:j({context:We.optional(),tools:We.optional()}).optional(),elicitation:OI.optional(),roots:j({listChanged:Ge().optional()}).optional(),tasks:II.optional(),extensions:Ee(S(),We).optional()}),DI=At.extend({protocolVersion:S(),capabilities:NI,clientInfo:Hb}),Jm=Ye.extend({method:H("initialize"),params:DI}),MI=j({experimental:Ee(S(),We).optional(),logging:We.optional(),completions:We.optional(),prompts:j({listChanged:Ge().optional()}).optional(),resources:j({subscribe:Ge().optional(),listChanged:Ge().optional()}).optional(),tools:j({listChanged:Ge().optional()}).optional(),tasks:AI.optional(),extensions:Ee(S(),We).optional()}),jI=Xe.extend({protocolVersion:S(),capabilities:MI,serverInfo:Hb,instructions:S().optional()}),Ym=Vt.extend({method:H("notifications/initialized"),params:qt.optional()}),hc=Ye.extend({method:H("ping"),params:At.optional()}),zI=j({progress:ge(),total:Ne(ge()),message:Ne(S())}),LI=j({...qt.shape,...zI.shape,progressToken:Nb}),gc=Vt.extend({method:H("notifications/progress"),params:LI}),FI=At.extend({cursor:Db.optional()}),si=Ye.extend({params:FI.optional()}),oi=Xe.extend({nextCursor:Db.optional()}),UI=St(["working","input_required","completed","failed","cancelled"]),ii=j({taskId:S(),status:UI,ttl:Te([ge(),vb()]),createdAt:S(),lastUpdatedAt:S(),pollInterval:Ne(ge()),statusMessage:Ne(S())}),Zs=Xe.extend({task:ii}),HI=qt.merge(ii),ai=Vt.extend({method:H("notifications/tasks/status"),params:HI}),yc=Ye.extend({method:H("tasks/get"),params:At.extend({taskId:S()})}),_c=Xe.merge(ii),xc=Ye.extend({method:H("tasks/result"),params:At.extend({taskId:S()})}),Iq=Xe.loose(),vc=si.extend({method:H("tasks/list")}),bc=oi.extend({tasks:ce(ii)}),Sc=Ye.extend({method:H("tasks/cancel"),params:At.extend({taskId:S()})}),Zb=Xe.merge(ii),Bb=j({uri:S(),mimeType:Ne(S()),_meta:Ee(S(),Ae()).optional()}),qb=Bb.extend({text:S()}),Xm=S().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Vb=Bb.extend({blob:Xm}),ci=St(["user","assistant"]),Bs=j({audience:ce(ci).optional(),priority:ge().min(0).max(1).optional(),lastModified:Qo.datetime({offset:!0}).optional()}),Wb=j({...Hs.shape,...ni.shape,uri:S(),description:Ne(S()),mimeType:Ne(S()),size:Ne(ge()),annotations:Bs.optional(),_meta:Ne(pt({}))}),ZI=j({...Hs.shape,...ni.shape,uriTemplate:S(),description:Ne(S()),mimeType:Ne(S()),annotations:Bs.optional(),_meta:Ne(pt({}))}),qs=si.extend({method:H("resources/list")}),BI=oi.extend({resources:ce(Wb)}),Vs=si.extend({method:H("resources/templates/list")}),qI=oi.extend({resourceTemplates:ce(ZI)}),Qm=At.extend({uri:S()}),VI=Qm,kc=Ye.extend({method:H("resources/read"),params:VI}),WI=Xe.extend({contents:ce(Te([qb,Vb]))}),GI=Vt.extend({method:H("notifications/resources/list_changed"),params:qt.optional()}),KI=Qm,JI=Ye.extend({method:H("resources/subscribe"),params:KI}),YI=Qm,XI=Ye.extend({method:H("resources/unsubscribe"),params:YI}),QI=qt.extend({uri:S()}),eA=Vt.extend({method:H("notifications/resources/updated"),params:QI}),tA=j({name:S(),description:Ne(S()),required:Ne(Ge())}),rA=j({...Hs.shape,...ni.shape,description:Ne(S()),arguments:Ne(ce(tA)),_meta:Ne(pt({}))}),Ws=si.extend({method:H("prompts/list")}),nA=oi.extend({prompts:ce(rA)}),sA=At.extend({name:S(),arguments:Ee(S(),S()).optional()}),wc=Ye.extend({method:H("prompts/get"),params:sA}),ef=j({type:H("text"),text:S(),annotations:Bs.optional(),_meta:Ee(S(),Ae()).optional()}),tf=j({type:H("image"),data:Xm,mimeType:S(),annotations:Bs.optional(),_meta:Ee(S(),Ae()).optional()}),rf=j({type:H("audio"),data:Xm,mimeType:S(),annotations:Bs.optional(),_meta:Ee(S(),Ae()).optional()}),oA=j({type:H("tool_use"),name:S(),id:S(),input:Ee(S(),Ae()),_meta:Ee(S(),Ae()).optional()}),iA=j({type:H("resource"),resource:Te([qb,Vb]),annotations:Bs.optional(),_meta:Ee(S(),Ae()).optional()}),aA=Wb.extend({type:H("resource_link")}),nf=Te([ef,tf,rf,aA,iA]),cA=j({role:ci,content:nf}),uA=Xe.extend({description:S().optional(),messages:ce(cA)}),lA=Vt.extend({method:H("notifications/prompts/list_changed"),params:qt.optional()}),dA=j({title:S().optional(),readOnlyHint:Ge().optional(),destructiveHint:Ge().optional(),idempotentHint:Ge().optional(),openWorldHint:Ge().optional()}),pA=j({taskSupport:St(["required","optional","forbidden"]).optional()}),Gb=j({...Hs.shape,...ni.shape,description:S().optional(),inputSchema:j({type:H("object"),properties:Ee(S(),We).optional(),required:ce(S()).optional()}).catchall(Ae()),outputSchema:j({type:H("object"),properties:Ee(S(),We).optional(),required:ce(S()).optional()}).catchall(Ae()).optional(),annotations:dA.optional(),execution:pA.optional(),_meta:Ee(S(),Ae()).optional()}),Ec=si.extend({method:H("tools/list")}),mA=oi.extend({tools:ce(Gb)}),$c=Xe.extend({content:ce(nf).default([]),structuredContent:Ee(S(),Ae()).optional(),isError:Ge().optional()}),Aq=$c.or(Xe.extend({toolResult:Ae()})),fA=ti.extend({name:S(),arguments:Ee(S(),Ae()).optional()}),Gs=Ye.extend({method:H("tools/call"),params:fA}),hA=Vt.extend({method:H("notifications/tools/list_changed"),params:qt.optional()}),Nq=j({autoRefresh:Ge().default(!0),debounceMs:ge().int().nonnegative().default(300)}),ui=St(["debug","info","notice","warning","error","critical","alert","emergency"]),gA=At.extend({level:ui}),sf=Ye.extend({method:H("logging/setLevel"),params:gA}),yA=qt.extend({level:ui,logger:S().optional(),data:Ae()}),_A=Vt.extend({method:H("notifications/message"),params:yA}),xA=j({name:S().optional()}),vA=j({hints:ce(xA).optional(),costPriority:ge().min(0).max(1).optional(),speedPriority:ge().min(0).max(1).optional(),intelligencePriority:ge().min(0).max(1).optional()}),bA=j({mode:St(["auto","required","none"]).optional()}),SA=j({type:H("tool_result"),toolUseId:S().describe("The unique identifier for the corresponding tool call."),content:ce(nf).default([]),structuredContent:j({}).loose().optional(),isError:Ge().optional(),_meta:Ee(S(),Ae()).optional()}),kA=Hm("type",[ef,tf,rf]),lc=Hm("type",[ef,tf,rf,oA,SA]),wA=j({role:ci,content:Te([lc,ce(lc)]),_meta:Ee(S(),Ae()).optional()}),EA=ti.extend({messages:ce(wA),modelPreferences:vA.optional(),systemPrompt:S().optional(),includeContext:St(["none","thisServer","allServers"]).optional(),temperature:ge().optional(),maxTokens:ge().int(),stopSequences:ce(S()).optional(),metadata:We.optional(),tools:ce(Gb).optional(),toolChoice:bA.optional()}),$A=Ye.extend({method:H("sampling/createMessage"),params:EA}),li=Xe.extend({model:S(),stopReason:Ne(St(["endTurn","stopSequence","maxTokens"]).or(S())),role:ci,content:kA}),of=Xe.extend({model:S(),stopReason:Ne(St(["endTurn","stopSequence","maxTokens","toolUse"]).or(S())),role:ci,content:Te([lc,ce(lc)])}),TA=j({type:H("boolean"),title:S().optional(),description:S().optional(),default:Ge().optional()}),PA=j({type:H("string"),title:S().optional(),description:S().optional(),minLength:ge().optional(),maxLength:ge().optional(),format:St(["email","uri","date","date-time"]).optional(),default:S().optional()}),RA=j({type:St(["number","integer"]),title:S().optional(),description:S().optional(),minimum:ge().optional(),maximum:ge().optional(),default:ge().optional()}),CA=j({type:H("string"),title:S().optional(),description:S().optional(),enum:ce(S()),default:S().optional()}),OA=j({type:H("string"),title:S().optional(),description:S().optional(),oneOf:ce(j({const:S(),title:S()})),default:S().optional()}),IA=j({type:H("string"),title:S().optional(),description:S().optional(),enum:ce(S()),enumNames:ce(S()).optional(),default:S().optional()}),AA=Te([CA,OA]),NA=j({type:H("array"),title:S().optional(),description:S().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:j({type:H("string"),enum:ce(S())}),default:ce(S()).optional()}),DA=j({type:H("array"),title:S().optional(),description:S().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:j({anyOf:ce(j({const:S(),title:S()}))}),default:ce(S()).optional()}),MA=Te([NA,DA]),jA=Te([IA,AA,MA]),zA=Te([jA,TA,PA,RA]),LA=ti.extend({mode:H("form").optional(),message:S(),requestedSchema:j({type:H("object"),properties:Ee(S(),zA),required:ce(S()).optional()})}),FA=ti.extend({mode:H("url"),message:S(),elicitationId:S(),url:S().url()}),UA=Te([LA,FA]),HA=Ye.extend({method:H("elicitation/create"),params:UA}),ZA=qt.extend({elicitationId:S()}),BA=Vt.extend({method:H("notifications/elicitation/complete"),params:ZA}),Ks=Xe.extend({action:St(["accept","decline","cancel"]),content:Zm(t=>t===null?void 0:t,Ee(S(),Te([S(),ge(),Ge(),ce(S())])).optional())}),qA=j({type:H("ref/resource"),uri:S()}),VA=j({type:H("ref/prompt"),name:S()}),WA=At.extend({ref:Te([VA,qA]),argument:j({name:S(),value:S()}),context:j({arguments:Ee(S(),S()).optional()}).optional()}),Tc=Ye.extend({method:H("completion/complete"),params:WA});GA=Xe.extend({completion:pt({values:ce(S()).max(100),total:Ne(ge().int()),hasMore:Ne(Ge())})}),KA=j({uri:S().startsWith("file://"),name:S().optional(),_meta:Ee(S(),Ae()).optional()}),JA=Ye.extend({method:H("roots/list"),params:At.optional()}),af=Xe.extend({roots:ce(KA)}),YA=Vt.extend({method:H("notifications/roots/list_changed"),params:qt.optional()}),Dq=Te([hc,Jm,Tc,sf,wc,Ws,qs,Vs,kc,JI,XI,Gs,Ec,yc,xc,vc,Sc]),Mq=Te([fc,gc,Ym,YA,ai]),jq=Te([mc,li,of,Ks,af,_c,bc,Zs]),zq=Te([hc,$A,HA,JA,yc,xc,vc,Sc]),Lq=Te([fc,gc,_A,eA,GI,hA,lA,ai,BA]),Fq=Te([mc,jI,GA,uA,nA,BI,qI,WI,$c,mA,_c,bc,Zs]),F=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===q.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new Bm(s.elicitations,r)}return new t(e,r,n)}},Bm=class extends F{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(q.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function un(t){return t==="completed"||t==="failed"||t==="cancelled"}var Yb=v(()=>{});var Qb,Xb,eS,Pc=v(()=>{Qb=Symbol("Let zodToJsonSchema decide on which parser to use"),Xb={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"},eS=t=>typeof t=="string"?{...Xb,name:t}:{...Xb,...t}});var tS,cf=v(()=>{Pc();tS=t=>{let e=eS(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,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function uf(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ue(t,e,r,n,s){t[e]=r,uf(t,e,n,s)}var ln=v(()=>{});var Rc,Cc=v(()=>{Rc=(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 De(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Rc(e,t.currentPath):e.join("/")}}var Wt=v(()=>{Cc()});function rS(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==R.ZodAny&&(r.items=J(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ue(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ue(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ue(r,"minItems",t.exactLength.value,t.exactLength.message,e),ue(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var lf=v(()=>{Lo();ln();Ze()});function nS(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?ue(r,"minimum",n.value,n.message,e):ue(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ue(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ue(r,"maximum",n.value,n.message,e):ue(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ue(r,"maximum",n.value,n.message,e));break;case"multipleOf":ue(r,"multipleOf",n.value,n.message,e);break}return r}var df=v(()=>{ln()});function sS(){return{type:"boolean"}}var pf=v(()=>{});function Oc(t,e){return J(t.type._def,e)}var Ic=v(()=>{Ze()});var oS,mf=v(()=>{Ze();oS=(t,e)=>J(t.innerType._def,e)});function ff(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>ff(t,e,s))};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 XA(t,e)}}var XA,hf=v(()=>{ln();XA=(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":ue(r,"minimum",n.value,n.message,e);break;case"max":ue(r,"maximum",n.value,n.message,e);break}return r}});function iS(t,e){return{...J(t.innerType._def,e),default:t.defaultValue()}}var gf=v(()=>{Ze()});function aS(t,e){return e.effectStrategy==="input"?J(t.schema._def,e):De(e)}var yf=v(()=>{Ze();Wt()});function cS(t){return{type:"string",enum:Array.from(t.values)}}var _f=v(()=>{});function uS(t,e){let r=[J(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),J(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(o=>{if(QA(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}var QA,xf=v(()=>{Ze();QA=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function lS(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 vf=v(()=>{});function Ac(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ue(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ue(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":ar(r,"email",n.message,e);break;case"format:idn-email":ar(r,"idn-email",n.message,e);break;case"pattern:zod":mt(r,ir.email,n.message,e);break}break;case"url":ar(r,"uri",n.message,e);break;case"uuid":ar(r,"uuid",n.message,e);break;case"regex":mt(r,n.regex,n.message,e);break;case"cuid":mt(r,ir.cuid,n.message,e);break;case"cuid2":mt(r,ir.cuid2,n.message,e);break;case"startsWith":mt(r,RegExp(`^${Sf(n.value,e)}`),n.message,e);break;case"endsWith":mt(r,RegExp(`${Sf(n.value,e)}$`),n.message,e);break;case"datetime":ar(r,"date-time",n.message,e);break;case"date":ar(r,"date",n.message,e);break;case"time":ar(r,"time",n.message,e);break;case"duration":ar(r,"duration",n.message,e);break;case"length":ue(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ue(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{mt(r,RegExp(Sf(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&ar(r,"ipv4",n.message,e),n.version!=="v4"&&ar(r,"ipv6",n.message,e);break}case"base64url":mt(r,ir.base64url,n.message,e);break;case"jwt":mt(r,ir.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&mt(r,ir.ipv4Cidr,n.message,e),n.version!=="v4"&&mt(r,ir.ipv6Cidr,n.message,e);break}case"emoji":mt(r,ir.emoji(),n.message,e);break;case"ulid":{mt(r,ir.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ar(r,"binary",n.message,e);break}case"contentEncoding:base64":{ue(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{mt(r,ir.base64,n.message,e);break}}break}case"nanoid":mt(r,ir.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Sf(t,e){return e.patternStrategy==="escape"?t1(t):t}function t1(t){let e="";for(let r=0;r<t.length;r++)e1.has(t[r])||(e+="\\"),e+=t[r];return e}function ar(t,e,r,n){t.format||t.anyOf?.some(s=>s.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}}})):ue(t,"format",e,r,n)}function mt(t,e,r,n){t.pattern||t.allOf?.some(s=>s.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:dS(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ue(t,"pattern",dS(e,n),r,n)}function dS(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,s="",o=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],a=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
|
61
61
|
]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
|
|
62
62
|
]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
|
|
63
63
|
`:`[${n[c]}\r
|
|
64
|
-
]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}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 s}var _f,sr,BA,Nc=v(()=>{un();sr={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:()=>(_f===void 0&&(_f=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),_f),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-_]*$/};BA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Dc(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===R.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??De(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===R.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=Ac(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===R.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===R.ZodBranded&&t.keyType._def.type._def.typeName===R.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=Oc(t.keyType._def,e);return{...r,propertyNames:s}}}return r}var Mc=v(()=>{zo();He();Nc();Ic();Vt()});function uS(t,e){if(e.mapStrategy==="record")return Dc(t,e);let r=J(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||De(e),n=J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||De(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var vf=v(()=>{He();Mc();Vt()});function lS(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}var bf=v(()=>{});function dS(t){return t.target==="openAi"?void 0:{not:De({...t,currentPath:[...t.currentPath,"not"]})}}var Sf=v(()=>{Vt()});function pS(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var kf=v(()=>{});function fS(t,e){if(e.target==="openApi3")return mS(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in li&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=li[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return mS(t,e)}var li,mS,jc=v(()=>{He();li={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};mS=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>J(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function hS(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:li[t.innerType._def.typeName],nullable:!0}:{type:[li[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=J(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=J(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var wf=v(()=>{He();jc()});function gS(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",of(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ue(r,"minimum",n.value,n.message,e):ue(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ue(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ue(r,"maximum",n.value,n.message,e):ue(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ue(r,"maximum",n.value,n.message,e));break;case"multipleOf":ue(r,"multipleOf",n.value,n.message,e);break}return r}var Ef=v(()=>{un()});function yS(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let u=WA(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let d=J(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});d!==void 0&&(n.properties[a]=d,u||s.push(a))}s.length&&(n.required=s);let i=VA(t,e);return i!==void 0&&(n.additionalProperties=i),n}function VA(t,e){if(t.catchall._def.typeName!=="ZodNever")return J(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 WA(t){try{return t.isOptional()}catch{return!0}}var $f=v(()=>{He()});var _S,Tf=v(()=>{He();Vt();_S=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return J(t.innerType._def,e);let r=J(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:De(e)},r]}:De(e)}});var xS,Pf=v(()=>{He();xS=(t,e)=>{if(e.pipeStrategy==="input")return J(t.in._def,e);if(e.pipeStrategy==="output")return J(t.out._def,e);let r=J(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=J(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}}});function vS(t,e){return J(t.type._def,e)}var Rf=v(()=>{He()});function bS(t,e){let n={type:"array",uniqueItems:!0,items:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ue(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ue(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Cf=v(()=>{un();He()});function SS(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>J(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:J(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>J(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Of=v(()=>{He()});function kS(t){return{not:De(t)}}var If=v(()=>{Vt()});function wS(t){return De(t)}var Af=v(()=>{Vt()});var ES,Nf=v(()=>{He();ES=(t,e)=>J(t.innerType._def,e)});var $S,Df=v(()=>{zo();Vt();af();cf();uf();Ic();lf();pf();mf();ff();hf();gf();yf();vf();bf();Sf();kf();wf();Ef();$f();Tf();Pf();Rf();Mc();Cf();Nc();Of();If();jc();Af();Nf();$S=(t,e,r)=>{switch(e){case R.ZodString:return Ac(t,r);case R.ZodNumber:return gS(t,r);case R.ZodObject:return yS(t,r);case R.ZodBigInt:return eS(t,r);case R.ZodBoolean:return tS();case R.ZodDate:return df(t,r);case R.ZodUndefined:return kS(r);case R.ZodNull:return pS(r);case R.ZodArray:return Qb(t,r);case R.ZodUnion:case R.ZodDiscriminatedUnion:return fS(t,r);case R.ZodIntersection:return iS(t,r);case R.ZodTuple:return SS(t,r);case R.ZodRecord:return Dc(t,r);case R.ZodLiteral:return aS(t,r);case R.ZodEnum:return oS(t);case R.ZodNativeEnum:return lS(t);case R.ZodNullable:return hS(t,r);case R.ZodOptional:return _S(t,r);case R.ZodMap:return uS(t,r);case R.ZodSet:return bS(t,r);case R.ZodLazy:return()=>t.getter()._def;case R.ZodPromise:return vS(t,r);case R.ZodNaN:case R.ZodNever:return dS(r);case R.ZodEffects:return sS(t,r);case R.ZodAny:return De(r);case R.ZodUnknown:return wS(r);case R.ZodDefault:return nS(t,r);case R.ZodBranded:return Oc(t,r);case R.ZodReadonly:return ES(t,r);case R.ZodCatch:return rS(t,r);case R.ZodPipeline:return xS(t,r);case R.ZodFunction:case R.ZodVoid:case R.ZodSymbol:return;default:return(n=>{})(e)}}});function J(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Jb)return a}if(n&&!r){let a=GA(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=$S(t,t.typeName,e),i=typeof o=="function"?J(o(),e):o;if(i&&KA(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var GA,KA,He=v(()=>{Pc();Df();Cc();Vt();GA=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Rc(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`),De(e)):e.$refStrategy==="seen"?De(e):void 0}},KA=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var TS=v(()=>{});var Mf,jf=v(()=>{He();sf();Vt();Mf=(t,e)=>{let r=Xb(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,d])=>({...c,[u]:J(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??De(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=J(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??De(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.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=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};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 PS=v(()=>{Pc();sf();un();Cc();He();TS();Vt();af();cf();uf();Ic();lf();pf();mf();ff();hf();gf();yf();vf();bf();Sf();kf();wf();Ef();$f();Tf();Pf();Rf();Nf();Mc();Cf();Nc();Of();If();jc();Af();Df();jf();jf()});function JA(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function zf(t,e){return Zt(t)?wm(t,{target:JA(e?.target),io:e?.pipeStrategy??"input"}):Mf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Lf(t){let r=on(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ac(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ff(t,e){let r=sn(t,e);if(!r.success)throw r.error;return r.data}var Uf=v(()=>{Tm();Yo();PS()});function RS(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function CS(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];RS(i)&&RS(o)?r[s]={...i,...o}:r[s]=o}return r}var YA,zc,OS=v(()=>{Yo();Xn();Gb();Uf();YA=6e4,zc=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(fc,r=>{this._oncancel(r)}),this.setNotificationHandler(gc,r=>{this._onprogress(r)}),this.setRequestHandler(hc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(yc,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new F(q.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(xc,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,m=new F(l.error.code,l.error.message,l.error.data);d(m)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new F(q.InvalidParams,`Task not found: ${o}`);if(!cn(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(cn(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[an]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(vc,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new F(q.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Sc,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new F(q.InvalidParams,`Task not found: ${r.params.taskId}`);if(cn(s.status))throw new F(q.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new F(q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof F?s:new F(q.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_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),F.fromError(q.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=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),ti(o)||jb(o)?this._onresponse(o):Bm(o)?this._onrequest(o,i):Mb(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},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=F.fromError(q.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,s=this._transport,o=e.params?._meta?.[an]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:q.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):s?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Ab(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};o&&(l.relatedTask={taskId:o}),await this.notification(d,l)},sendRequest:async(d,l,m)=>{if(i.signal.aborted)throw new F(q.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:e.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});let p=f.relatedTask?.taskId??o;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,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 d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:l,timestamp:Date.now()},s?.sessionId):await s?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:q.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},s?.sessionId):await s?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ti(e))n(e);else{let i=new F(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===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 o=!1;if(ti(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"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),ti(e))s(e);else{let i=F.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof F?i:new F(q.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Us,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new F(q.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},cn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new F(q.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new F(q.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},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 F?i:new F(q.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=x=>{d(x)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(x){l(x);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[an]:c}});let p=x=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(x)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let _=x instanceof F?x:new F(q.RequestTimeout,String(x));d(_)};this._responseHandlers.set(m,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return d(x);try{let _=sn(r,x.result);_.success?u(_.data):d(_.error)}catch(_){d(_)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let h=n?.timeout??YA,g=()=>p(F.fromError(q.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let x=_=>{let b=this._responseHandlers.get(m);b?b(_):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,x),this._enqueueTaskMessage(y,{type:"request",message:f,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(m),d(_)})}else this._transport.send(f,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(x=>{this._cleanupTimeout(m),d(x)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},_c,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},bc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Fb,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||{},[an]: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||{},[an]: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||{},[an]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Lf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=Ff(e,s);return Promise.resolve(r(i,o))})}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=Lf(e);this._notificationHandlers.set(n,s=>{let o=Ff(e,s);return Promise.resolve(r(o))})}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 s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&Bm(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new F(q.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new F(q.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new F(q.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new F(q.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let a=await n.getTask(s,r);if(a){let c=ii.parse({method:"notifications/tasks/status",params:a});await this.notification(c),cn(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let a=await n.getTask(s,r);if(!a)throw new F(q.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(cn(a.status))throw new F(q.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let c=await n.getTask(s,r);if(c){let u=ii.parse({method:"notifications/tasks/status",params:c});await this.notification(u),cn(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}});var mi=D(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.regexpCode=me.getEsmExportName=me.getProperty=me.safeStringify=me.stringify=me.strConcat=me.addCodeArg=me.str=me._=me.nil=me._Code=me.Name=me.IDENTIFIER=me._CodeOrName=void 0;var di=class{};me._CodeOrName=di;me.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Qn=class extends di{constructor(e){if(super(),!me.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}}};me.Name=Qn;var Wt=class extends di{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 Qn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};me._Code=Wt;me.nil=new Wt("");function IS(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Zf(r,e[n]),r.push(t[++n]);return new Wt(r)}me._=IS;var Hf=new Wt("+");function AS(t,...e){let r=[pi(t[0])],n=0;for(;n<e.length;)r.push(Hf),Zf(r,e[n]),r.push(Hf,pi(t[++n]));return XA(r),new Wt(r)}me.str=AS;function Zf(t,e){e instanceof Wt?t.push(...e._items):e instanceof Qn?t.push(e):t.push(t1(e))}me.addCodeArg=Zf;function XA(t){let e=1;for(;e<t.length-1;){if(t[e]===Hf){let r=QA(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function QA(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Qn||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 Qn))return`"${t}${e.slice(1)}`}function e1(t,e){return e.emptyStr()?t:t.emptyStr()?e:AS`${t}${e}`}me.strConcat=e1;function t1(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:pi(Array.isArray(t)?t.join(","):t)}function r1(t){return new Wt(pi(t))}me.stringify=r1;function pi(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}me.safeStringify=pi;function n1(t){return typeof t=="string"&&me.IDENTIFIER.test(t)?new Wt(`.${t}`):IS`[${t}]`}me.getProperty=n1;function s1(t){if(typeof t=="string"&&me.IDENTIFIER.test(t))return new Wt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}me.getEsmExportName=s1;function o1(t){return new Wt(t.toString())}me.regexpCode=o1});var Vf=D(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.ValueScope=wt.ValueScopeName=wt.Scope=wt.varKinds=wt.UsedValueState=void 0;var kt=mi(),Bf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Lc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Lc||(wt.UsedValueState=Lc={}));wt.varKinds={const:new kt.Name("const"),let:new kt.Name("let"),var:new kt.Name("var")};var Fc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof kt.Name?e:this.name(e)}name(e){return new kt.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}}};wt.Scope=Fc;var Uc=class extends kt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,kt._)`.${new kt.Name(r)}[${n}]`}};wt.ValueScopeName=Uc;var i1=(0,kt._)`\n`,qf=class extends Fc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?i1:kt.nil}}get(){return this._scope}name(e){return new Uc(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 s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let d=a.get(i);if(d)return d}else a=this._values[o]=new Map;a.set(i,s);let c=this._scope[o]||(this._scope[o]=[]),u=c.length;return c[u]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}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,kt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=kt.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,Lc.Started);let d=r(u);if(d){let l=this.opts.es5?wt.varKinds.var:wt.varKinds.const;o=(0,kt._)`${o}${l} ${u} = ${d};${this.opts._n}`}else if(d=s?.(u))o=(0,kt._)`${o}${d}${this.opts._n}`;else throw new Bf(u);c.set(u,Lc.Completed)})}return o}};wt.ValueScope=qf});var te=D(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.or=re.and=re.not=re.CodeGen=re.operators=re.varKinds=re.ValueScopeName=re.ValueScope=re.Scope=re.Name=re.regexpCode=re.stringify=re.getProperty=re.nil=re.strConcat=re.str=re._=void 0;var le=mi(),ir=Vf(),ln=mi();Object.defineProperty(re,"_",{enumerable:!0,get:function(){return ln._}});Object.defineProperty(re,"str",{enumerable:!0,get:function(){return ln.str}});Object.defineProperty(re,"strConcat",{enumerable:!0,get:function(){return ln.strConcat}});Object.defineProperty(re,"nil",{enumerable:!0,get:function(){return ln.nil}});Object.defineProperty(re,"getProperty",{enumerable:!0,get:function(){return ln.getProperty}});Object.defineProperty(re,"stringify",{enumerable:!0,get:function(){return ln.stringify}});Object.defineProperty(re,"regexpCode",{enumerable:!0,get:function(){return ln.regexpCode}});Object.defineProperty(re,"Name",{enumerable:!0,get:function(){return ln.Name}});var qc=Vf();Object.defineProperty(re,"Scope",{enumerable:!0,get:function(){return qc.Scope}});Object.defineProperty(re,"ValueScope",{enumerable:!0,get:function(){return qc.ValueScope}});Object.defineProperty(re,"ValueScopeName",{enumerable:!0,get:function(){return qc.ValueScopeName}});Object.defineProperty(re,"varKinds",{enumerable:!0,get:function(){return qc.varKinds}});re.operators={GT:new le._Code(">"),GTE:new le._Code(">="),LT:new le._Code("<"),LTE:new le._Code("<="),EQ:new le._Code("==="),NEQ:new le._Code("!=="),NOT:new le._Code("!"),OR:new le._Code("||"),AND:new le._Code("&&"),ADD:new le._Code("+")};var Nr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Wf=class extends Nr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ir.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Ks(this.rhs,e,r)),this}get names(){return this.rhs instanceof le._CodeOrName?this.rhs.names:{}}},Hc=class extends Nr{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 le.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ks(this.rhs,e,r),this}get names(){let e=this.lhs instanceof le.Name?{}:{...this.lhs.names};return Bc(e,this.rhs)}},Gf=class extends Hc{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Kf=class extends Nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Jf=class extends Nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Yf=class extends Nr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Xf=class extends Nr{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=Ks(this.code,e,r),this}get names(){return this.code instanceof le._CodeOrName?this.code.names:{}}},fi=class extends Nr{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,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(a1(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>rs(e,r.names),{})}},Dr=class extends fi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Qf=class extends fi{},Gs=class extends Dr{};Gs.kind="else";var es=class t extends Dr{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 Gs(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(NS(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=Ks(this.condition,e,r),this}get names(){let e=super.names;return Bc(e,this.condition),this.else&&rs(e,this.else.names),e}};es.kind="if";var ts=class extends Dr{};ts.kind="for";var eh=class extends ts{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=Ks(this.iteration,e,r),this}get names(){return rs(super.names,this.iteration.names)}},th=class extends ts{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?ir.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=Bc(super.names,this.from);return Bc(e,this.to)}},Zc=class extends ts{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}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=Ks(this.iterable,e,r),this}get names(){return rs(super.names,this.iterable.names)}},hi=class extends Dr{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)}};hi.kind="func";var gi=class extends fi{render(e){return"return "+super.render(e)}};gi.kind="return";var rh=class extends Dr{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,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&rs(e,this.catch.names),this.finally&&rs(e,this.finally.names),e}},yi=class extends Dr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};yi.kind="catch";var _i=class extends Dr{render(e){return"finally"+super.render(e)}};_i.kind="finally";var nh=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
65
|
-
`:""},this._extScope=e,this._scope=new ir.Scope({parent:e}),this._nodes=[new Qf]}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,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new Wf(e,o,n)),o}const(e,r,n){return this._def(ir.varKinds.const,e,r,n)}let(e,r,n){return this._def(ir.varKinds.let,e,r,n)}var(e,r,n){return this._def(ir.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Hc(e,r,n))}add(e,r){return this._leafNode(new Gf(e,re.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==le.nil&&this._leafNode(new Xf(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,le.addCodeArg)(r,s));return r.push("}"),new le._Code(r)}if(e,r,n){if(this._blockNode(new es(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 es(e))}else(){return this._elseNode(new Gs)}endIf(){return this._endBlockNode(es,Gs)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new eh(e),r)}forRange(e,r,n,s,o=this.opts.es5?ir.varKinds.var:ir.varKinds.let){let i=this._scope.toName(e);return this._for(new th(o,i,r,n),()=>s(i))}forOf(e,r,n,s=ir.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof le.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,le._)`${i}.length`,a=>{this.var(o,(0,le._)`${i}[${a}]`),n(o)})}return this._for(new Zc("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?ir.varKinds.var:ir.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,le._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new Zc("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(ts)}label(e){return this._leafNode(new Kf(e))}break(e){return this._leafNode(new Jf(e))}return(e){let r=new gi;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(gi)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new rh;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new yi(o),r(o)}return n&&(this._currNode=s.finally=new _i,this.code(n)),this._endBlockNode(yi,_i)}throw(e){return this._leafNode(new Yf(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=le.nil,n,s){return this._blockNode(new hi(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(hi)}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 es))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}};re.CodeGen=nh;function rs(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Bc(t,e){return e instanceof le._CodeOrName?rs(t,e.names):t}function Ks(t,e,r){if(t instanceof le.Name)return n(t);if(!s(t))return t;return new le._Code(t._items.reduce((o,i)=>(i instanceof le.Name&&(i=n(i)),i instanceof le._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof le._Code&&o._items.some(i=>i instanceof le.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function a1(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function NS(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,le._)`!${sh(t)}`}re.not=NS;var c1=DS(re.operators.AND);function u1(...t){return t.reduce(c1)}re.and=u1;var l1=DS(re.operators.OR);function d1(...t){return t.reduce(l1)}re.or=d1;function DS(t){return(e,r)=>e===le.nil?r:r===le.nil?e:(0,le._)`${sh(e)} ${t} ${sh(r)}`}function sh(t){return t instanceof le.Name?t:(0,le._)`(${t})`}});var de=D(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.checkStrictMode=ne.getErrorPath=ne.Type=ne.useFunc=ne.setEvaluated=ne.evaluatedPropsToName=ne.mergeEvaluated=ne.eachItem=ne.unescapeJsonPointer=ne.escapeJsonPointer=ne.escapeFragment=ne.unescapeFragment=ne.schemaRefOrVal=ne.schemaHasRulesButRef=ne.schemaHasRules=ne.checkUnknownRules=ne.alwaysValidSchema=ne.toHash=void 0;var be=te(),p1=mi();function m1(t){let e={};for(let r of t)e[r]=!0;return e}ne.toHash=m1;function f1(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(zS(t,e),!LS(e,t.self.RULES.all))}ne.alwaysValidSchema=f1;function zS(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||HS(t,`unknown keyword: "${o}"`)}ne.checkUnknownRules=zS;function LS(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ne.schemaHasRules=LS;function h1(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ne.schemaHasRulesButRef=h1;function g1({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,be._)`${r}`}return(0,be._)`${t}${e}${(0,be.getProperty)(n)}`}ne.schemaRefOrVal=g1;function y1(t){return FS(decodeURIComponent(t))}ne.unescapeFragment=y1;function _1(t){return encodeURIComponent(ih(t))}ne.escapeFragment=_1;function ih(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=ih;function FS(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=FS;function x1(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ne.eachItem=x1;function MS({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof be.Name?(o instanceof be.Name?t(s,o,i):e(s,o,i),i):o instanceof be.Name?(e(s,i,o),o):r(o,i);return a===be.Name&&!(c instanceof be.Name)?n(s,c):c}}ne.mergeEvaluated={props:MS({mergeNames:(t,e,r)=>t.if((0,be._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,be._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,be._)`${r} || {}`).code((0,be._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,be._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,be._)`${r} || {}`),ah(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:US}),items:MS({mergeNames:(t,e,r)=>t.if((0,be._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,be._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,be._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,be._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function US(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,be._)`{}`);return e!==void 0&&ah(t,r,e),r}ne.evaluatedPropsToName=US;function ah(t,e,r){Object.keys(r).forEach(n=>t.assign((0,be._)`${e}${(0,be.getProperty)(n)}`,!0))}ne.setEvaluated=ah;var jS={};function v1(t,e){return t.scopeValue("func",{ref:e,code:jS[e.code]||(jS[e.code]=new p1._Code(e.code))})}ne.useFunc=v1;var oh;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(oh||(ne.Type=oh={}));function b1(t,e,r){if(t instanceof be.Name){let n=e===oh.Num;return r?n?(0,be._)`"[" + ${t} + "]"`:(0,be._)`"['" + ${t} + "']"`:n?(0,be._)`"/" + ${t}`:(0,be._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,be.getProperty)(t).toString():"/"+ih(t)}ne.getErrorPath=b1;function HS(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ne.checkStrictMode=HS});var Mr=D(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var ot=te(),S1={data:new ot.Name("data"),valCxt:new ot.Name("valCxt"),instancePath:new ot.Name("instancePath"),parentData:new ot.Name("parentData"),parentDataProperty:new ot.Name("parentDataProperty"),rootData:new ot.Name("rootData"),dynamicAnchors:new ot.Name("dynamicAnchors"),vErrors:new ot.Name("vErrors"),errors:new ot.Name("errors"),this:new ot.Name("this"),self:new ot.Name("self"),scope:new ot.Name("scope"),json:new ot.Name("json"),jsonPos:new ot.Name("jsonPos"),jsonLen:new ot.Name("jsonLen"),jsonPart:new ot.Name("jsonPart")};ch.default=S1});var xi=D(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.extendErrors=it.resetErrorsCount=it.reportExtraError=it.reportError=it.keyword$DataError=it.keywordError=void 0;var pe=te(),Vc=de(),ft=Mr();it.keywordError={message:({keyword:t})=>(0,pe.str)`must pass "${t}" keyword validation`};it.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,pe.str)`"${t}" keyword must be ${e} ($data)`:(0,pe.str)`"${t}" keyword is invalid ($data)`};function k1(t,e=it.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=qS(t,e,r);n??(i||a)?ZS(o,c):BS(s,(0,pe._)`[${c}]`)}it.reportError=k1;function w1(t,e=it.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=qS(t,e,r);ZS(s,a),o||i||BS(n,ft.default.vErrors)}it.reportExtraError=w1;function E1(t,e){t.assign(ft.default.errors,e),t.if((0,pe._)`${ft.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,pe._)`${ft.default.vErrors}.length`,e),()=>t.assign(ft.default.vErrors,null)))}it.resetErrorsCount=E1;function $1({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,ft.default.errors,a=>{t.const(i,(0,pe._)`${ft.default.vErrors}[${a}]`),t.if((0,pe._)`${i}.instancePath === undefined`,()=>t.assign((0,pe._)`${i}.instancePath`,(0,pe.strConcat)(ft.default.instancePath,o.errorPath))),t.assign((0,pe._)`${i}.schemaPath`,(0,pe.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,pe._)`${i}.schema`,r),t.assign((0,pe._)`${i}.data`,n))})}it.extendErrors=$1;function ZS(t,e){let r=t.const("err",e);t.if((0,pe._)`${ft.default.vErrors} === null`,()=>t.assign(ft.default.vErrors,(0,pe._)`[${r}]`),(0,pe._)`${ft.default.vErrors}.push(${r})`),t.code((0,pe._)`${ft.default.errors}++`)}function BS(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,pe._)`new ${t.ValidationError}(${e})`):(r.assign((0,pe._)`${n}.errors`,e),r.return(!1))}var ns={keyword:new pe.Name("keyword"),schemaPath:new pe.Name("schemaPath"),params:new pe.Name("params"),propertyName:new pe.Name("propertyName"),message:new pe.Name("message"),schema:new pe.Name("schema"),parentSchema:new pe.Name("parentSchema")};function qS(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,pe._)`{}`:T1(t,e,r)}function T1(t,e,r={}){let{gen:n,it:s}=t,o=[P1(s,r),R1(t,r)];return C1(t,e,o),n.object(...o)}function P1({errorPath:t},{instancePath:e}){let r=e?(0,pe.str)`${t}${(0,Vc.getErrorPath)(e,Vc.Type.Str)}`:t;return[ft.default.instancePath,(0,pe.strConcat)(ft.default.instancePath,r)]}function R1({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,pe.str)`${e}/${t}`;return r&&(s=(0,pe.str)`${s}${(0,Vc.getErrorPath)(r,Vc.Type.Str)}`),[ns.schemaPath,s]}function C1(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([ns.keyword,s],[ns.params,typeof e=="function"?e(t):e||(0,pe._)`{}`]),c.messages&&n.push([ns.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([ns.schema,i],[ns.parentSchema,(0,pe._)`${d}${l}`],[ft.default.data,o]),u&&n.push([ns.propertyName,u])}});var WS=D(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.boolOrEmptySchema=Js.topBoolOrEmptySchema=void 0;var O1=xi(),I1=te(),A1=Mr(),N1={message:"boolean schema is false"};function D1(t){let{gen:e,schema:r,validateName:n}=t;r===!1?VS(t,!1):typeof r=="object"&&r.$async===!0?e.return(A1.default.data):(e.assign((0,I1._)`${n}.errors`,null),e.return(!0))}Js.topBoolOrEmptySchema=D1;function M1(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),VS(t)):r.var(e,!0)}Js.boolOrEmptySchema=M1;function VS(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,O1.reportError)(s,N1,void 0,e)}});var uh=D(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.getRules=Ys.isJSONType=void 0;var j1=["string","number","integer","boolean","null","object","array"],z1=new Set(j1);function L1(t){return typeof t=="string"&&z1.has(t)}Ys.isJSONType=L1;function F1(){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:{}}}Ys.getRules=F1});var lh=D(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.shouldUseRule=dn.shouldUseGroup=dn.schemaHasRulesForType=void 0;function U1({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&GS(t,n)}dn.schemaHasRulesForType=U1;function GS(t,e){return e.rules.some(r=>KS(t,r))}dn.shouldUseGroup=GS;function KS(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))}dn.shouldUseRule=KS});var vi=D(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.reportTypeError=at.checkDataTypes=at.checkDataType=at.coerceAndCheckDataType=at.getJSONTypes=at.getSchemaTypes=at.DataType=void 0;var H1=uh(),Z1=lh(),B1=xi(),Q=te(),JS=de(),Xs;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Xs||(at.DataType=Xs={}));function q1(t){let e=YS(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}at.getSchemaTypes=q1;function YS(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(H1.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}at.getJSONTypes=YS;function V1(t,e){let{gen:r,data:n,opts:s}=t,o=W1(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,Z1.schemaHasRulesForType)(t,e[0]));if(i){let a=ph(e,n,s.strictNumbers,Xs.Wrong);r.if(a,()=>{o.length?G1(t,e,o):mh(t)})}return i}at.coerceAndCheckDataType=V1;var XS=new Set(["string","number","integer","boolean","null"]);function W1(t,e){return e?t.filter(r=>XS.has(r)||e==="array"&&r==="array"):[]}function G1(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,Q._)`typeof ${s}`),a=n.let("coerced",(0,Q._)`undefined`);o.coerceTypes==="array"&&n.if((0,Q._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,Q._)`${s}[0]`).assign(i,(0,Q._)`typeof ${s}`).if(ph(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,Q._)`${a} !== undefined`);for(let u of r)(XS.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),mh(t),n.endIf(),n.if((0,Q._)`${a} !== undefined`,()=>{n.assign(s,a),K1(t,a)});function c(u){switch(u){case"string":n.elseIf((0,Q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Q._)`"" + ${s}`).elseIf((0,Q._)`${s} === null`).assign(a,(0,Q._)`""`);return;case"number":n.elseIf((0,Q._)`${i} == "boolean" || ${s} === null
|
|
64
|
+
]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}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 s}var bf,ir,e1,Nc=v(()=>{ln();ir={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:()=>(bf===void 0&&(bf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),bf),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-_]*$/};e1=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Dc(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===R.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??De(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===R.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=Ac(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===R.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===R.ZodBranded&&t.keyType._def.type._def.typeName===R.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=Oc(t.keyType._def,e);return{...r,propertyNames:s}}}return r}var Mc=v(()=>{Lo();Ze();Nc();Ic();Wt()});function pS(t,e){if(e.mapStrategy==="record")return Dc(t,e);let r=J(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||De(e),n=J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||De(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var kf=v(()=>{Ze();Mc();Wt()});function mS(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}var wf=v(()=>{});function fS(t){return t.target==="openAi"?void 0:{not:De({...t,currentPath:[...t.currentPath,"not"]})}}var Ef=v(()=>{Wt()});function hS(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var $f=v(()=>{});function yS(t,e){if(e.target==="openApi3")return gS(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in di&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=di[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return gS(t,e)}var di,gS,jc=v(()=>{Ze();di={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};gS=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>J(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function _S(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:di[t.innerType._def.typeName],nullable:!0}:{type:[di[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=J(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=J(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Tf=v(()=>{Ze();jc()});function xS(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",uf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ue(r,"minimum",n.value,n.message,e):ue(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ue(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ue(r,"maximum",n.value,n.message,e):ue(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ue(r,"maximum",n.value,n.message,e));break;case"multipleOf":ue(r,"multipleOf",n.value,n.message,e);break}return r}var Pf=v(()=>{ln()});function vS(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let u=n1(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let d=J(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});d!==void 0&&(n.properties[a]=d,u||s.push(a))}s.length&&(n.required=s);let i=r1(t,e);return i!==void 0&&(n.additionalProperties=i),n}function r1(t,e){if(t.catchall._def.typeName!=="ZodNever")return J(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 n1(t){try{return t.isOptional()}catch{return!0}}var Rf=v(()=>{Ze()});var bS,Cf=v(()=>{Ze();Wt();bS=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return J(t.innerType._def,e);let r=J(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:De(e)},r]}:De(e)}});var SS,Of=v(()=>{Ze();SS=(t,e)=>{if(e.pipeStrategy==="input")return J(t.in._def,e);if(e.pipeStrategy==="output")return J(t.out._def,e);let r=J(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=J(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}}});function kS(t,e){return J(t.type._def,e)}var If=v(()=>{Ze()});function wS(t,e){let n={type:"array",uniqueItems:!0,items:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ue(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ue(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Af=v(()=>{ln();Ze()});function ES(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>J(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:J(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>J(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Nf=v(()=>{Ze()});function $S(t){return{not:De(t)}}var Df=v(()=>{Wt()});function TS(t){return De(t)}var Mf=v(()=>{Wt()});var PS,jf=v(()=>{Ze();PS=(t,e)=>J(t.innerType._def,e)});var RS,zf=v(()=>{Lo();Wt();lf();df();pf();Ic();mf();hf();gf();yf();_f();xf();vf();kf();wf();Ef();$f();Tf();Pf();Rf();Cf();Of();If();Mc();Af();Nc();Nf();Df();jc();Mf();jf();RS=(t,e,r)=>{switch(e){case R.ZodString:return Ac(t,r);case R.ZodNumber:return xS(t,r);case R.ZodObject:return vS(t,r);case R.ZodBigInt:return nS(t,r);case R.ZodBoolean:return sS();case R.ZodDate:return ff(t,r);case R.ZodUndefined:return $S(r);case R.ZodNull:return hS(r);case R.ZodArray:return rS(t,r);case R.ZodUnion:case R.ZodDiscriminatedUnion:return yS(t,r);case R.ZodIntersection:return uS(t,r);case R.ZodTuple:return ES(t,r);case R.ZodRecord:return Dc(t,r);case R.ZodLiteral:return lS(t,r);case R.ZodEnum:return cS(t);case R.ZodNativeEnum:return mS(t);case R.ZodNullable:return _S(t,r);case R.ZodOptional:return bS(t,r);case R.ZodMap:return pS(t,r);case R.ZodSet:return wS(t,r);case R.ZodLazy:return()=>t.getter()._def;case R.ZodPromise:return kS(t,r);case R.ZodNaN:case R.ZodNever:return fS(r);case R.ZodEffects:return aS(t,r);case R.ZodAny:return De(r);case R.ZodUnknown:return TS(r);case R.ZodDefault:return iS(t,r);case R.ZodBranded:return Oc(t,r);case R.ZodReadonly:return PS(t,r);case R.ZodCatch:return oS(t,r);case R.ZodPipeline:return SS(t,r);case R.ZodFunction:case R.ZodVoid:case R.ZodSymbol:return;default:return(n=>{})(e)}}});function J(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Qb)return a}if(n&&!r){let a=s1(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=RS(t,t.typeName,e),i=typeof o=="function"?J(o(),e):o;if(i&&o1(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var s1,o1,Ze=v(()=>{Pc();zf();Cc();Wt();s1=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Rc(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`),De(e)):e.$refStrategy==="seen"?De(e):void 0}},o1=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var CS=v(()=>{});var Lf,Ff=v(()=>{Ze();cf();Wt();Lf=(t,e)=>{let r=tS(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,d])=>({...c,[u]:J(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??De(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=J(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??De(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.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=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};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 OS=v(()=>{Pc();cf();ln();Cc();Ze();CS();Wt();lf();df();pf();Ic();mf();hf();gf();yf();_f();xf();vf();kf();wf();Ef();$f();Tf();Pf();Rf();Cf();Of();If();jf();Mc();Af();Nc();Nf();Df();jc();Mf();zf();Ff();Ff()});function i1(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Uf(t,e){return Bt(t)?Tm(t,{target:i1(e?.target),io:e?.pipeStrategy??"input"}):Lf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Hf(t){let r=an(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ac(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Zf(t,e){let r=on(t,e);if(!r.success)throw r.error;return r.data}var Bf=v(()=>{Cm();Xo();OS()});function IS(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function AS(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];IS(i)&&IS(o)?r[s]={...i,...o}:r[s]=o}return r}var a1,zc,NS=v(()=>{Xo();Qn();Yb();Bf();a1=6e4,zc=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(fc,r=>{this._oncancel(r)}),this.setNotificationHandler(gc,r=>{this._onprogress(r)}),this.setRequestHandler(hc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(yc,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new F(q.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(xc,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,m=new F(l.error.code,l.error.message,l.error.data);d(m)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new F(q.InvalidParams,`Task not found: ${o}`);if(!un(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(un(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[cn]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(vc,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new F(q.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Sc,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new F(q.InvalidParams,`Task not found: ${r.params.taskId}`);if(un(s.status))throw new F(q.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new F(q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof F?s:new F(q.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_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),F.fromError(q.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=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),ri(o)||Fb(o)?this._onresponse(o):Wm(o)?this._onrequest(o,i):Lb(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},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=F.fromError(q.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,s=this._transport,o=e.params?._meta?.[cn]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:q.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):s?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Mb(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};o&&(l.relatedTask={taskId:o}),await this.notification(d,l)},sendRequest:async(d,l,m)=>{if(i.signal.aborted)throw new F(q.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:e.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});let p=f.relatedTask?.taskId??o;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,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 d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:l,timestamp:Date.now()},s?.sessionId):await s?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:q.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},s?.sessionId):await s?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ri(e))n(e);else{let i=new F(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===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 o=!1;if(ri(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"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),ri(e))s(e);else{let i=F.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof F?i:new F(q.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Zs,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new F(q.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},un(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new F(q.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new F(q.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},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 F?i:new F(q.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=x=>{d(x)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(x){l(x);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[cn]:c}});let p=x=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(x)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let y=x instanceof F?x:new F(q.RequestTimeout,String(x));d(y)};this._responseHandlers.set(m,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return d(x);try{let y=on(r,x.result);y.success?u(y.data):d(y.error)}catch(y){d(y)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let h=n?.timeout??a1,g=()=>p(F.fromError(q.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let x=y=>{let b=this._responseHandlers.get(m);b?b(y):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,x),this._enqueueTaskMessage(_,{type:"request",message:f,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(m),d(y)})}else this._transport.send(f,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(x=>{this._cleanupTimeout(m),d(x)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},_c,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},bc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Zb,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||{},[cn]: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||{},[cn]: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||{},[cn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Hf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=Zf(e,s);return Promise.resolve(r(i,o))})}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=Hf(e);this._notificationHandlers.set(n,s=>{let o=Zf(e,s);return Promise.resolve(r(o))})}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 s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&Wm(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new F(q.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new F(q.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new F(q.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new F(q.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let a=await n.getTask(s,r);if(a){let c=ai.parse({method:"notifications/tasks/status",params:a});await this.notification(c),un(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let a=await n.getTask(s,r);if(!a)throw new F(q.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(un(a.status))throw new F(q.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let c=await n.getTask(s,r);if(c){let u=ai.parse({method:"notifications/tasks/status",params:c});await this.notification(u),un(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}});var fi=D(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.regexpCode=fe.getEsmExportName=fe.getProperty=fe.safeStringify=fe.stringify=fe.strConcat=fe.addCodeArg=fe.str=fe._=fe.nil=fe._Code=fe.Name=fe.IDENTIFIER=fe._CodeOrName=void 0;var pi=class{};fe._CodeOrName=pi;fe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var es=class extends pi{constructor(e){if(super(),!fe.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}}};fe.Name=es;var Gt=class extends pi{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 es&&(r[n.str]=(r[n.str]||0)+1),r),{})}};fe._Code=Gt;fe.nil=new Gt("");function DS(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Vf(r,e[n]),r.push(t[++n]);return new Gt(r)}fe._=DS;var qf=new Gt("+");function MS(t,...e){let r=[mi(t[0])],n=0;for(;n<e.length;)r.push(qf),Vf(r,e[n]),r.push(qf,mi(t[++n]));return c1(r),new Gt(r)}fe.str=MS;function Vf(t,e){e instanceof Gt?t.push(...e._items):e instanceof es?t.push(e):t.push(d1(e))}fe.addCodeArg=Vf;function c1(t){let e=1;for(;e<t.length-1;){if(t[e]===qf){let r=u1(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function u1(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof es||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 es))return`"${t}${e.slice(1)}`}function l1(t,e){return e.emptyStr()?t:t.emptyStr()?e:MS`${t}${e}`}fe.strConcat=l1;function d1(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:mi(Array.isArray(t)?t.join(","):t)}function p1(t){return new Gt(mi(t))}fe.stringify=p1;function mi(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}fe.safeStringify=mi;function m1(t){return typeof t=="string"&&fe.IDENTIFIER.test(t)?new Gt(`.${t}`):DS`[${t}]`}fe.getProperty=m1;function f1(t){if(typeof t=="string"&&fe.IDENTIFIER.test(t))return new Gt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}fe.getEsmExportName=f1;function h1(t){return new Gt(t.toString())}fe.regexpCode=h1});var Kf=D(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.ValueScope=wt.ValueScopeName=wt.Scope=wt.varKinds=wt.UsedValueState=void 0;var kt=fi(),Wf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Lc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Lc||(wt.UsedValueState=Lc={}));wt.varKinds={const:new kt.Name("const"),let:new kt.Name("let"),var:new kt.Name("var")};var Fc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof kt.Name?e:this.name(e)}name(e){return new kt.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}}};wt.Scope=Fc;var Uc=class extends kt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,kt._)`.${new kt.Name(r)}[${n}]`}};wt.ValueScopeName=Uc;var g1=(0,kt._)`\n`,Gf=class extends Fc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?g1:kt.nil}}get(){return this._scope}name(e){return new Uc(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 s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let d=a.get(i);if(d)return d}else a=this._values[o]=new Map;a.set(i,s);let c=this._scope[o]||(this._scope[o]=[]),u=c.length;return c[u]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}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,kt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=kt.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,Lc.Started);let d=r(u);if(d){let l=this.opts.es5?wt.varKinds.var:wt.varKinds.const;o=(0,kt._)`${o}${l} ${u} = ${d};${this.opts._n}`}else if(d=s?.(u))o=(0,kt._)`${o}${d}${this.opts._n}`;else throw new Wf(u);c.set(u,Lc.Completed)})}return o}};wt.ValueScope=Gf});var te=D(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.or=re.and=re.not=re.CodeGen=re.operators=re.varKinds=re.ValueScopeName=re.ValueScope=re.Scope=re.Name=re.regexpCode=re.stringify=re.getProperty=re.nil=re.strConcat=re.str=re._=void 0;var le=fi(),cr=Kf(),dn=fi();Object.defineProperty(re,"_",{enumerable:!0,get:function(){return dn._}});Object.defineProperty(re,"str",{enumerable:!0,get:function(){return dn.str}});Object.defineProperty(re,"strConcat",{enumerable:!0,get:function(){return dn.strConcat}});Object.defineProperty(re,"nil",{enumerable:!0,get:function(){return dn.nil}});Object.defineProperty(re,"getProperty",{enumerable:!0,get:function(){return dn.getProperty}});Object.defineProperty(re,"stringify",{enumerable:!0,get:function(){return dn.stringify}});Object.defineProperty(re,"regexpCode",{enumerable:!0,get:function(){return dn.regexpCode}});Object.defineProperty(re,"Name",{enumerable:!0,get:function(){return dn.Name}});var qc=Kf();Object.defineProperty(re,"Scope",{enumerable:!0,get:function(){return qc.Scope}});Object.defineProperty(re,"ValueScope",{enumerable:!0,get:function(){return qc.ValueScope}});Object.defineProperty(re,"ValueScopeName",{enumerable:!0,get:function(){return qc.ValueScopeName}});Object.defineProperty(re,"varKinds",{enumerable:!0,get:function(){return qc.varKinds}});re.operators={GT:new le._Code(">"),GTE:new le._Code(">="),LT:new le._Code("<"),LTE:new le._Code("<="),EQ:new le._Code("==="),NEQ:new le._Code("!=="),NOT:new le._Code("!"),OR:new le._Code("||"),AND:new le._Code("&&"),ADD:new le._Code("+")};var Dr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Jf=class extends Dr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?cr.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Ys(this.rhs,e,r)),this}get names(){return this.rhs instanceof le._CodeOrName?this.rhs.names:{}}},Hc=class extends Dr{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 le.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ys(this.rhs,e,r),this}get names(){let e=this.lhs instanceof le.Name?{}:{...this.lhs.names};return Bc(e,this.rhs)}},Yf=class extends Hc{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Xf=class extends Dr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Qf=class extends Dr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},eh=class extends Dr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},th=class extends Dr{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=Ys(this.code,e,r),this}get names(){return this.code instanceof le._CodeOrName?this.code.names:{}}},hi=class extends Dr{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,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(y1(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>ns(e,r.names),{})}},Mr=class extends hi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},rh=class extends hi{},Js=class extends Mr{};Js.kind="else";var ts=class t extends Mr{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 Js(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(jS(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=Ys(this.condition,e,r),this}get names(){let e=super.names;return Bc(e,this.condition),this.else&&ns(e,this.else.names),e}};ts.kind="if";var rs=class extends Mr{};rs.kind="for";var nh=class extends rs{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=Ys(this.iteration,e,r),this}get names(){return ns(super.names,this.iteration.names)}},sh=class extends rs{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?cr.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=Bc(super.names,this.from);return Bc(e,this.to)}},Zc=class extends rs{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}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=Ys(this.iterable,e,r),this}get names(){return ns(super.names,this.iterable.names)}},gi=class extends Mr{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)}};gi.kind="func";var yi=class extends hi{render(e){return"return "+super.render(e)}};yi.kind="return";var oh=class extends Mr{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,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&ns(e,this.catch.names),this.finally&&ns(e,this.finally.names),e}},_i=class extends Mr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};_i.kind="catch";var xi=class extends Mr{render(e){return"finally"+super.render(e)}};xi.kind="finally";var ih=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
65
|
+
`:""},this._extScope=e,this._scope=new cr.Scope({parent:e}),this._nodes=[new rh]}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,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new Jf(e,o,n)),o}const(e,r,n){return this._def(cr.varKinds.const,e,r,n)}let(e,r,n){return this._def(cr.varKinds.let,e,r,n)}var(e,r,n){return this._def(cr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Hc(e,r,n))}add(e,r){return this._leafNode(new Yf(e,re.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==le.nil&&this._leafNode(new th(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,le.addCodeArg)(r,s));return r.push("}"),new le._Code(r)}if(e,r,n){if(this._blockNode(new ts(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 ts(e))}else(){return this._elseNode(new Js)}endIf(){return this._endBlockNode(ts,Js)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new nh(e),r)}forRange(e,r,n,s,o=this.opts.es5?cr.varKinds.var:cr.varKinds.let){let i=this._scope.toName(e);return this._for(new sh(o,i,r,n),()=>s(i))}forOf(e,r,n,s=cr.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof le.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,le._)`${i}.length`,a=>{this.var(o,(0,le._)`${i}[${a}]`),n(o)})}return this._for(new Zc("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?cr.varKinds.var:cr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,le._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new Zc("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(rs)}label(e){return this._leafNode(new Xf(e))}break(e){return this._leafNode(new Qf(e))}return(e){let r=new yi;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(yi)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new oh;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new _i(o),r(o)}return n&&(this._currNode=s.finally=new xi,this.code(n)),this._endBlockNode(_i,xi)}throw(e){return this._leafNode(new eh(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=le.nil,n,s){return this._blockNode(new gi(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(gi)}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 ts))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}};re.CodeGen=ih;function ns(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Bc(t,e){return e instanceof le._CodeOrName?ns(t,e.names):t}function Ys(t,e,r){if(t instanceof le.Name)return n(t);if(!s(t))return t;return new le._Code(t._items.reduce((o,i)=>(i instanceof le.Name&&(i=n(i)),i instanceof le._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof le._Code&&o._items.some(i=>i instanceof le.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function y1(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function jS(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,le._)`!${ah(t)}`}re.not=jS;var _1=zS(re.operators.AND);function x1(...t){return t.reduce(_1)}re.and=x1;var v1=zS(re.operators.OR);function b1(...t){return t.reduce(v1)}re.or=b1;function zS(t){return(e,r)=>e===le.nil?r:r===le.nil?e:(0,le._)`${ah(e)} ${t} ${ah(r)}`}function ah(t){return t instanceof le.Name?t:(0,le._)`(${t})`}});var pe=D(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.checkStrictMode=ne.getErrorPath=ne.Type=ne.useFunc=ne.setEvaluated=ne.evaluatedPropsToName=ne.mergeEvaluated=ne.eachItem=ne.unescapeJsonPointer=ne.escapeJsonPointer=ne.escapeFragment=ne.unescapeFragment=ne.schemaRefOrVal=ne.schemaHasRulesButRef=ne.schemaHasRules=ne.checkUnknownRules=ne.alwaysValidSchema=ne.toHash=void 0;var be=te(),S1=fi();function k1(t){let e={};for(let r of t)e[r]=!0;return e}ne.toHash=k1;function w1(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(US(t,e),!HS(e,t.self.RULES.all))}ne.alwaysValidSchema=w1;function US(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||qS(t,`unknown keyword: "${o}"`)}ne.checkUnknownRules=US;function HS(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ne.schemaHasRules=HS;function E1(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ne.schemaHasRulesButRef=E1;function $1({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,be._)`${r}`}return(0,be._)`${t}${e}${(0,be.getProperty)(n)}`}ne.schemaRefOrVal=$1;function T1(t){return ZS(decodeURIComponent(t))}ne.unescapeFragment=T1;function P1(t){return encodeURIComponent(uh(t))}ne.escapeFragment=P1;function uh(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=uh;function ZS(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=ZS;function R1(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ne.eachItem=R1;function LS({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof be.Name?(o instanceof be.Name?t(s,o,i):e(s,o,i),i):o instanceof be.Name?(e(s,i,o),o):r(o,i);return a===be.Name&&!(c instanceof be.Name)?n(s,c):c}}ne.mergeEvaluated={props:LS({mergeNames:(t,e,r)=>t.if((0,be._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,be._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,be._)`${r} || {}`).code((0,be._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,be._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,be._)`${r} || {}`),lh(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:BS}),items:LS({mergeNames:(t,e,r)=>t.if((0,be._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,be._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,be._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,be._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function BS(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,be._)`{}`);return e!==void 0&&lh(t,r,e),r}ne.evaluatedPropsToName=BS;function lh(t,e,r){Object.keys(r).forEach(n=>t.assign((0,be._)`${e}${(0,be.getProperty)(n)}`,!0))}ne.setEvaluated=lh;var FS={};function C1(t,e){return t.scopeValue("func",{ref:e,code:FS[e.code]||(FS[e.code]=new S1._Code(e.code))})}ne.useFunc=C1;var ch;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ch||(ne.Type=ch={}));function O1(t,e,r){if(t instanceof be.Name){let n=e===ch.Num;return r?n?(0,be._)`"[" + ${t} + "]"`:(0,be._)`"['" + ${t} + "']"`:n?(0,be._)`"/" + ${t}`:(0,be._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,be.getProperty)(t).toString():"/"+uh(t)}ne.getErrorPath=O1;function qS(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ne.checkStrictMode=qS});var jr=D(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});var ot=te(),I1={data:new ot.Name("data"),valCxt:new ot.Name("valCxt"),instancePath:new ot.Name("instancePath"),parentData:new ot.Name("parentData"),parentDataProperty:new ot.Name("parentDataProperty"),rootData:new ot.Name("rootData"),dynamicAnchors:new ot.Name("dynamicAnchors"),vErrors:new ot.Name("vErrors"),errors:new ot.Name("errors"),this:new ot.Name("this"),self:new ot.Name("self"),scope:new ot.Name("scope"),json:new ot.Name("json"),jsonPos:new ot.Name("jsonPos"),jsonLen:new ot.Name("jsonLen"),jsonPart:new ot.Name("jsonPart")};dh.default=I1});var vi=D(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.extendErrors=it.resetErrorsCount=it.reportExtraError=it.reportError=it.keyword$DataError=it.keywordError=void 0;var me=te(),Vc=pe(),ft=jr();it.keywordError={message:({keyword:t})=>(0,me.str)`must pass "${t}" keyword validation`};it.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,me.str)`"${t}" keyword must be ${e} ($data)`:(0,me.str)`"${t}" keyword is invalid ($data)`};function A1(t,e=it.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=GS(t,e,r);n??(i||a)?VS(o,c):WS(s,(0,me._)`[${c}]`)}it.reportError=A1;function N1(t,e=it.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=GS(t,e,r);VS(s,a),o||i||WS(n,ft.default.vErrors)}it.reportExtraError=N1;function D1(t,e){t.assign(ft.default.errors,e),t.if((0,me._)`${ft.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,me._)`${ft.default.vErrors}.length`,e),()=>t.assign(ft.default.vErrors,null)))}it.resetErrorsCount=D1;function M1({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,ft.default.errors,a=>{t.const(i,(0,me._)`${ft.default.vErrors}[${a}]`),t.if((0,me._)`${i}.instancePath === undefined`,()=>t.assign((0,me._)`${i}.instancePath`,(0,me.strConcat)(ft.default.instancePath,o.errorPath))),t.assign((0,me._)`${i}.schemaPath`,(0,me.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,me._)`${i}.schema`,r),t.assign((0,me._)`${i}.data`,n))})}it.extendErrors=M1;function VS(t,e){let r=t.const("err",e);t.if((0,me._)`${ft.default.vErrors} === null`,()=>t.assign(ft.default.vErrors,(0,me._)`[${r}]`),(0,me._)`${ft.default.vErrors}.push(${r})`),t.code((0,me._)`${ft.default.errors}++`)}function WS(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,me._)`new ${t.ValidationError}(${e})`):(r.assign((0,me._)`${n}.errors`,e),r.return(!1))}var ss={keyword:new me.Name("keyword"),schemaPath:new me.Name("schemaPath"),params:new me.Name("params"),propertyName:new me.Name("propertyName"),message:new me.Name("message"),schema:new me.Name("schema"),parentSchema:new me.Name("parentSchema")};function GS(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,me._)`{}`:j1(t,e,r)}function j1(t,e,r={}){let{gen:n,it:s}=t,o=[z1(s,r),L1(t,r)];return F1(t,e,o),n.object(...o)}function z1({errorPath:t},{instancePath:e}){let r=e?(0,me.str)`${t}${(0,Vc.getErrorPath)(e,Vc.Type.Str)}`:t;return[ft.default.instancePath,(0,me.strConcat)(ft.default.instancePath,r)]}function L1({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,me.str)`${e}/${t}`;return r&&(s=(0,me.str)`${s}${(0,Vc.getErrorPath)(r,Vc.Type.Str)}`),[ss.schemaPath,s]}function F1(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([ss.keyword,s],[ss.params,typeof e=="function"?e(t):e||(0,me._)`{}`]),c.messages&&n.push([ss.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([ss.schema,i],[ss.parentSchema,(0,me._)`${d}${l}`],[ft.default.data,o]),u&&n.push([ss.propertyName,u])}});var JS=D(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.boolOrEmptySchema=Xs.topBoolOrEmptySchema=void 0;var U1=vi(),H1=te(),Z1=jr(),B1={message:"boolean schema is false"};function q1(t){let{gen:e,schema:r,validateName:n}=t;r===!1?KS(t,!1):typeof r=="object"&&r.$async===!0?e.return(Z1.default.data):(e.assign((0,H1._)`${n}.errors`,null),e.return(!0))}Xs.topBoolOrEmptySchema=q1;function V1(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),KS(t)):r.var(e,!0)}Xs.boolOrEmptySchema=V1;function KS(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,U1.reportError)(s,B1,void 0,e)}});var ph=D(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.getRules=Qs.isJSONType=void 0;var W1=["string","number","integer","boolean","null","object","array"],G1=new Set(W1);function K1(t){return typeof t=="string"&&G1.has(t)}Qs.isJSONType=K1;function J1(){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:{}}}Qs.getRules=J1});var mh=D(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.shouldUseRule=pn.shouldUseGroup=pn.schemaHasRulesForType=void 0;function Y1({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&YS(t,n)}pn.schemaHasRulesForType=Y1;function YS(t,e){return e.rules.some(r=>XS(t,r))}pn.shouldUseGroup=YS;function XS(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))}pn.shouldUseRule=XS});var bi=D(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.reportTypeError=at.checkDataTypes=at.checkDataType=at.coerceAndCheckDataType=at.getJSONTypes=at.getSchemaTypes=at.DataType=void 0;var X1=ph(),Q1=mh(),eN=vi(),Q=te(),QS=pe(),eo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(eo||(at.DataType=eo={}));function tN(t){let e=ek(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}at.getSchemaTypes=tN;function ek(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(X1.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}at.getJSONTypes=ek;function rN(t,e){let{gen:r,data:n,opts:s}=t,o=nN(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,Q1.schemaHasRulesForType)(t,e[0]));if(i){let a=hh(e,n,s.strictNumbers,eo.Wrong);r.if(a,()=>{o.length?sN(t,e,o):gh(t)})}return i}at.coerceAndCheckDataType=rN;var tk=new Set(["string","number","integer","boolean","null"]);function nN(t,e){return e?t.filter(r=>tk.has(r)||e==="array"&&r==="array"):[]}function sN(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,Q._)`typeof ${s}`),a=n.let("coerced",(0,Q._)`undefined`);o.coerceTypes==="array"&&n.if((0,Q._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,Q._)`${s}[0]`).assign(i,(0,Q._)`typeof ${s}`).if(hh(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,Q._)`${a} !== undefined`);for(let u of r)(tk.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),gh(t),n.endIf(),n.if((0,Q._)`${a} !== undefined`,()=>{n.assign(s,a),oN(t,a)});function c(u){switch(u){case"string":n.elseIf((0,Q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Q._)`"" + ${s}`).elseIf((0,Q._)`${s} === null`).assign(a,(0,Q._)`""`);return;case"number":n.elseIf((0,Q._)`${i} == "boolean" || ${s} === null
|
|
66
66
|
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,Q._)`+${s}`);return;case"integer":n.elseIf((0,Q._)`${i} === "boolean" || ${s} === null
|
|
67
67
|
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,Q._)`+${s}`);return;case"boolean":n.elseIf((0,Q._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,Q._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,Q._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,Q._)`${i} === "string" || ${i} === "number"
|
|
68
|
-
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,Q._)`[${s}]`)}}}function K1({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,Q._)`${e} !== undefined`,()=>t.assign((0,Q._)`${e}[${r}]`,n))}function dh(t,e,r,n=Xs.Correct){let s=n===Xs.Correct?Q.operators.EQ:Q.operators.NEQ,o;switch(t){case"null":return(0,Q._)`${e} ${s} null`;case"array":o=(0,Q._)`Array.isArray(${e})`;break;case"object":o=(0,Q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,Q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,Q._)`typeof ${e} ${s} ${t}`}return n===Xs.Correct?o:(0,Q.not)(o);function i(a=Q.nil){return(0,Q.and)((0,Q._)`typeof ${e} == "number"`,a,r?(0,Q._)`isFinite(${e})`:Q.nil)}}at.checkDataType=dh;function ph(t,e,r,n){if(t.length===1)return dh(t[0],e,r,n);let s,o=(0,JS.toHash)(t);if(o.array&&o.object){let i=(0,Q._)`typeof ${e} != "object"`;s=o.null?i:(0,Q._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=Q.nil;o.number&&delete o.integer;for(let i in o)s=(0,Q.and)(s,dh(i,e,r,n));return s}at.checkDataTypes=ph;var J1={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Q._)`{type: ${t}}`:(0,Q._)`{type: ${e}}`};function mh(t){let e=Y1(t);(0,B1.reportError)(e,J1)}at.reportTypeError=mh;function Y1(t){let{gen:e,data:r,schema:n}=t,s=(0,JS.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var ek=D(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.assignDefaults=void 0;var Qs=te(),X1=de();function Q1(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)QS(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>QS(t,o,s.default))}Wc.assignDefaults=Q1;function QS(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,Qs._)`${o}${(0,Qs.getProperty)(e)}`;if(s){(0,X1.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Qs._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Qs._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Qs._)`${a} = ${(0,Qs.stringify)(r)}`)}});var Gt=D(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.validateUnion=ve.validateArray=ve.usePattern=ve.callValidateCode=ve.schemaProperties=ve.allSchemaProperties=ve.noPropertyInData=ve.propertyInData=ve.isOwnProperty=ve.hasPropFunc=ve.reportMissingProp=ve.checkMissingProp=ve.checkReportMissingProp=void 0;var Pe=te(),fh=de(),pn=Mr(),eN=de();function tN(t,e){let{gen:r,data:n,it:s}=t;r.if(gh(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Pe._)`${e}`},!0),t.error()})}ve.checkReportMissingProp=tN;function rN({gen:t,data:e,it:{opts:r}},n,s){return(0,Pe.or)(...n.map(o=>(0,Pe.and)(gh(t,e,o,r.ownProperties),(0,Pe._)`${s} = ${o}`)))}ve.checkMissingProp=rN;function nN(t,e){t.setParams({missingProperty:e},!0),t.error()}ve.reportMissingProp=nN;function tk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Pe._)`Object.prototype.hasOwnProperty`})}ve.hasPropFunc=tk;function hh(t,e,r){return(0,Pe._)`${tk(t)}.call(${e}, ${r})`}ve.isOwnProperty=hh;function sN(t,e,r,n){let s=(0,Pe._)`${e}${(0,Pe.getProperty)(r)} !== undefined`;return n?(0,Pe._)`${s} && ${hh(t,e,r)}`:s}ve.propertyInData=sN;function gh(t,e,r,n){let s=(0,Pe._)`${e}${(0,Pe.getProperty)(r)} === undefined`;return n?(0,Pe.or)(s,(0,Pe.not)(hh(t,e,r))):s}ve.noPropertyInData=gh;function rk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ve.allSchemaProperties=rk;function oN(t,e){return rk(e).filter(r=>!(0,fh.alwaysValidSchema)(t,e[r]))}ve.schemaProperties=oN;function iN({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,u){let d=u?(0,Pe._)`${t}, ${e}, ${n}${s}`:e,l=[[pn.default.instancePath,(0,Pe.strConcat)(pn.default.instancePath,o)],[pn.default.parentData,i.parentData],[pn.default.parentDataProperty,i.parentDataProperty],[pn.default.rootData,pn.default.rootData]];i.opts.dynamicRef&&l.push([pn.default.dynamicAnchors,pn.default.dynamicAnchors]);let m=(0,Pe._)`${d}, ${r.object(...l)}`;return c!==Pe.nil?(0,Pe._)`${a}.call(${c}, ${m})`:(0,Pe._)`${a}(${m})`}ve.callValidateCode=iN;var aN=(0,Pe._)`new RegExp`;function cN({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,Pe._)`${s.code==="new RegExp"?aN:(0,eN.useFunc)(t,s)}(${r}, ${n})`})}ve.usePattern=cN;function uN(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let c=e.const("len",(0,Pe._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:fh.Type.Num},o),e.if((0,Pe.not)(o),a)})}}ve.validateArray=uN;function lN(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,fh.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Pe._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,Pe.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ve.validateUnion=lN});var ok=D(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.validateKeywordUsage=Sr.validSchemaType=Sr.funcKeywordCode=Sr.macroKeywordCode=void 0;var ht=te(),ss=Mr(),dN=Gt(),pN=xi();function mN(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=sk(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:ht.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Sr.macroKeywordCode=mN;function fN(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;gN(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,d=sk(n,s,u),l=n.let("valid");t.block$data(l,m),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function m(){if(e.errors===!1)h(),e.modifying&&nk(t),g(()=>t.error());else{let y=e.async?f():p();e.modifying&&nk(t),g(()=>hN(t,y))}}function f(){let y=n.let("ruleErrs",null);return n.try(()=>h((0,ht._)`await `),x=>n.assign(l,!1).if((0,ht._)`${x} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,ht._)`${x}.errors`),()=>n.throw(x))),y}function p(){let y=(0,ht._)`${d}.errors`;return n.assign(y,null),h(ht.nil),y}function h(y=e.async?(0,ht._)`await `:ht.nil){let x=c.opts.passContext?ss.default.this:ss.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,ht._)`${y}${(0,dN.callValidateCode)(t,d,x,_)}`,e.modifying)}function g(y){var x;n.if((0,ht.not)((x=e.valid)!==null&&x!==void 0?x:l),y)}}Sr.funcKeywordCode=fN;function nk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ht._)`${n.parentData}[${n.parentDataProperty}]`))}function hN(t,e){let{gen:r}=t;r.if((0,ht._)`Array.isArray(${e})`,()=>{r.assign(ss.default.vErrors,(0,ht._)`${ss.default.vErrors} === null ? ${e} : ${ss.default.vErrors}.concat(${e})`).assign(ss.default.errors,(0,ht._)`${ss.default.vErrors}.length`),(0,pN.extendErrors)(t)},()=>t.error())}function gN({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function sk(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,ht.stringify)(r)})}function yN(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")}Sr.validSchemaType=yN;function _N({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Sr.validateKeywordUsage=_N});var ak=D(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.extendSubschemaMode=mn.extendSubschemaData=mn.getSubschema=void 0;var kr=te(),ik=de();function xN(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,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,kr._)`${t.schemaPath}${(0,kr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,kr._)`${t.schemaPath}${(0,kr.getProperty)(e)}${(0,kr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,ik.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}mn.getSubschema=xN;function vN(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==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:d,opts:l}=e,m=a.let("data",(0,kr._)`${e.data}${(0,kr.getProperty)(r)}`,!0);c(m),t.errorPath=(0,kr.str)`${u}${(0,ik.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,kr._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof kr.Name?s:a.let("data",s,!0);c(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);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]}}mn.extendSubschemaData=vN;function bN(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}mn.extendSubschemaMode=bN});var yh=D((H3,ck)=>{"use strict";ck.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,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))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(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var lk=D((Z3,uk)=>{"use strict";var fn=uk.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};Gc(e,n,s,t,"",t)};fn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};fn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};fn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};fn.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 Gc(t,e,r,n,s,o,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in fn.arrayKeywords)for(var m=0;m<l.length;m++)Gc(t,e,r,l[m],s+"/"+d+"/"+m,o,s,d,n,m)}else if(d in fn.propsKeywords){if(l&&typeof l=="object")for(var f in l)Gc(t,e,r,l[f],s+"/"+d+"/"+SN(f),o,s,d,n,f)}else(d in fn.keywords||t.allKeys&&!(d in fn.skipKeywords))&&Gc(t,e,r,l,s+"/"+d,o,s,d,n)}r(n,s,o,i,a,c,u)}}function SN(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var bi=D(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.getSchemaRefs=Et.resolveUrl=Et.normalizeId=Et._getFullPath=Et.getFullPath=Et.inlineRef=void 0;var kN=de(),wN=yh(),EN=lk(),$N=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function TN(t,e=!0){return typeof t=="boolean"?!0:e===!0?!_h(t):e?dk(t)<=e:!1}Et.inlineRef=TN;var PN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function _h(t){for(let e in t){if(PN.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(_h)||typeof r=="object"&&_h(r))return!0}return!1}function dk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!$N.has(r)&&(typeof t[r]=="object"&&(0,kN.eachItem)(t[r],n=>e+=dk(n)),e===1/0))return 1/0}return e}function pk(t,e="",r){r!==!1&&(e=eo(e));let n=t.parse(e);return mk(t,n)}Et.getFullPath=pk;function mk(t,e){return t.serialize(e).split("#")[0]+"#"}Et._getFullPath=mk;var RN=/#\/?$/;function eo(t){return t?t.replace(RN,""):""}Et.normalizeId=eo;function CN(t,e,r){return r=eo(r),t.resolve(e,r)}Et.resolveUrl=CN;var ON=/^[a-z_][-a-z0-9._]*$/i;function IN(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=eo(t[r]||e),o={"":s},i=pk(n,s,!1),a={},c=new Set;return EN(t,{allKeys:!0},(l,m,f,p)=>{if(p===void 0)return;let h=i+m,g=o[p];typeof l[r]=="string"&&(g=y.call(this,l[r])),x.call(this,l.$anchor),x.call(this,l.$dynamicAnchor),o[m]=g;function y(_){let b=this.opts.uriResolver.resolve;if(_=eo(g?b(g,_):_),c.has(_))throw d(_);c.add(_);let w=this.refs[_];return typeof w=="string"&&(w=this.refs[w]),typeof w=="object"?u(l,w.schema,_):_!==eo(h)&&(_[0]==="#"?(u(l,a[_],_),a[_]=l):this.refs[_]=h),_}function x(_){if(typeof _=="string"){if(!ON.test(_))throw new Error(`invalid anchor "${_}"`);y.call(this,`#${_}`)}}}),a;function u(l,m,f){if(m!==void 0&&!wN(l,m))throw d(f)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Et.getSchemaRefs=IN});var wi=D(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.getData=hn.KeywordCxt=hn.validateFunctionCode=void 0;var _k=WS(),fk=vi(),vh=lh(),Kc=vi(),AN=ek(),ki=ok(),xh=ak(),Z=te(),Y=Mr(),NN=bi(),jr=de(),Si=xi();function DN(t){if(bk(t)&&(Sk(t),vk(t))){zN(t);return}xk(t,()=>(0,_k.topBoolOrEmptySchema)(t))}hn.validateFunctionCode=DN;function xk({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,Z._)`${Y.default.data}, ${Y.default.valCxt}`,n.$async,()=>{t.code((0,Z._)`"use strict"; ${hk(r,s)}`),jN(t,s),t.code(o)}):t.func(e,(0,Z._)`${Y.default.data}, ${MN(s)}`,n.$async,()=>t.code(hk(r,s)).code(o))}function MN(t){return(0,Z._)`{${Y.default.instancePath}="", ${Y.default.parentData}, ${Y.default.parentDataProperty}, ${Y.default.rootData}=${Y.default.data}${t.dynamicRef?(0,Z._)`, ${Y.default.dynamicAnchors}={}`:Z.nil}}={}`}function jN(t,e){t.if(Y.default.valCxt,()=>{t.var(Y.default.instancePath,(0,Z._)`${Y.default.valCxt}.${Y.default.instancePath}`),t.var(Y.default.parentData,(0,Z._)`${Y.default.valCxt}.${Y.default.parentData}`),t.var(Y.default.parentDataProperty,(0,Z._)`${Y.default.valCxt}.${Y.default.parentDataProperty}`),t.var(Y.default.rootData,(0,Z._)`${Y.default.valCxt}.${Y.default.rootData}`),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,Z._)`${Y.default.valCxt}.${Y.default.dynamicAnchors}`)},()=>{t.var(Y.default.instancePath,(0,Z._)`""`),t.var(Y.default.parentData,(0,Z._)`undefined`),t.var(Y.default.parentDataProperty,(0,Z._)`undefined`),t.var(Y.default.rootData,Y.default.data),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,Z._)`{}`)})}function zN(t){let{schema:e,opts:r,gen:n}=t;xk(t,()=>{r.$comment&&e.$comment&&wk(t),ZN(t),n.let(Y.default.vErrors,null),n.let(Y.default.errors,0),r.unevaluated&&LN(t),kk(t),VN(t)})}function LN(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Z._)`${r}.evaluated`),e.if((0,Z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Z._)`${t.evaluated}.props`,(0,Z._)`undefined`)),e.if((0,Z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Z._)`${t.evaluated}.items`,(0,Z._)`undefined`))}function hk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Z._)`/*# sourceURL=${r} */`:Z.nil}function FN(t,e){if(bk(t)&&(Sk(t),vk(t))){UN(t,e);return}(0,_k.boolOrEmptySchema)(t,e)}function vk({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 bk(t){return typeof t.schema!="boolean"}function UN(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&wk(t),BN(t),qN(t);let o=n.const("_errs",Y.default.errors);kk(t,o),n.var(e,(0,Z._)`${o} === ${Y.default.errors}`)}function Sk(t){(0,jr.checkUnknownRules)(t),HN(t)}function kk(t,e){if(t.opts.jtd)return gk(t,[],!1,e);let r=(0,fk.getSchemaTypes)(t.schema),n=(0,fk.coerceAndCheckDataType)(t,r);gk(t,r,!n,e)}function HN(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,jr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function ZN(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,jr.checkStrictMode)(t,"default is ignored in the schema root")}function BN(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,NN.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function qN(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function wk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,Z._)`${Y.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,Z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Z._)`${Y.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function VN(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,Z._)`${Y.default.errors} === 0`,()=>e.return(Y.default.data),()=>e.throw((0,Z._)`new ${s}(${Y.default.vErrors})`)):(e.assign((0,Z._)`${n}.errors`,Y.default.vErrors),o.unevaluated&&WN(t),e.return((0,Z._)`${Y.default.errors} === 0`))}function WN({gen:t,evaluated:e,props:r,items:n}){r instanceof Z.Name&&t.assign((0,Z._)`${e}.props`,r),n instanceof Z.Name&&t.assign((0,Z._)`${e}.items`,n)}function gk(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,jr.schemaHasRulesButRef)(o,d))){s.block(()=>$k(t,"$ref",d.all.$ref.definition));return}c.jtd||GN(t,e),s.block(()=>{for(let m of d.rules)l(m);l(d.post)});function l(m){(0,vh.shouldUseGroup)(o,m)&&(m.type?(s.if((0,Kc.checkDataType)(m.type,i,c.strictNumbers)),yk(t,m),e.length===1&&e[0]===m.type&&r&&(s.else(),(0,Kc.reportTypeError)(t)),s.endIf()):yk(t,m),a||s.if((0,Z._)`${Y.default.errors} === ${n||0}`))}}function yk(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,AN.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,vh.shouldUseRule)(n,o)&&$k(t,o.keyword,o.definition,e.type)})}function GN(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(KN(t,e),t.opts.allowUnionTypes||JN(t,e),YN(t,t.dataTypes))}function KN(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Ek(t.dataTypes,r)||bh(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),QN(t,e)}}function JN(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&bh(t,"use allowUnionTypes to allow union type keyword")}function YN(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,vh.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>XN(e,i))&&bh(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function XN(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Ek(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function QN(t,e){let r=[];for(let n of t.dataTypes)Ek(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function bh(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,jr.checkStrictMode)(t,e,t.opts.strictTypes)}var Jc=class{constructor(e,r,n){if((0,ki.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,jr.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",Tk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ki.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",Y.default.errors))}result(e,r,n){this.failResult((0,Z.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,Z.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,Z._)`${r} !== undefined && (${(0,Z.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?Si.reportExtraError:Si.reportError)(this,this.def.error,r)}$dataError(){(0,Si.reportError)(this,this.def.$dataError||Si.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Si.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=Z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Z.nil,r=Z.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,Z.or)((0,Z._)`${s} === undefined`,r)),e!==Z.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,Z.or)(i(),a());function i(){if(n.length){if(!(r instanceof Z.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Z._)`${(0,Kc.checkDataTypes)(c,r,o.opts.strictNumbers,Kc.DataType.Wrong)}`}return Z.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,Z._)`!${c}(${r})`}return Z.nil}}subschema(e,r){let n=(0,xh.getSubschema)(this.it,e);(0,xh.extendSubschemaData)(n,this.it,e),(0,xh.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return FN(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=jr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=jr.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,Z.Name)),!0}};hn.KeywordCxt=Jc;function $k(t,e,r,n){let s=new Jc(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,ki.funcKeywordCode)(s,r):"macro"in r?(0,ki.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,ki.funcKeywordCode)(s,r)}var eD=/^\/(?:[^~]|~0|~1)*$/,tD=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Tk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return Y.default.rootData;if(t[0]==="/"){if(!eD.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Y.default.rootData}else{let u=tD.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(s=u[2],s==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(o=r[e-d],!s)return o}let i=o,a=s.split("/");for(let u of a)u&&(o=(0,Z._)`${o}${(0,Z.getProperty)((0,jr.unescapeJsonPointer)(u))}`,i=(0,Z._)`${i} && ${o}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}hn.getData=Tk});var Yc=D(kh=>{"use strict";Object.defineProperty(kh,"__esModule",{value:!0});var Sh=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};kh.default=Sh});var Ei=D($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});var wh=bi(),Eh=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,wh.resolveUrl)(e,r,n),this.missingSchema=(0,wh.normalizeId)((0,wh.getFullPath)(e,this.missingRef))}};$h.default=Eh});var Qc=D(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.resolveSchema=Kt.getCompilingSchema=Kt.resolveRef=Kt.compileSchema=Kt.SchemaEnv=void 0;var ar=te(),rD=Yc(),os=Mr(),cr=bi(),Pk=de(),nD=wi(),to=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,cr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Kt.SchemaEnv=to;function Ph(t){let e=Rk.call(this,t);if(e)return e;let r=(0,cr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new ar.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:rD.default,code:(0,ar._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:os.default.data,parentData:os.default.parentData,parentDataProperty:os.default.parentDataProperty,dataNames:[os.default.data],dataPathArr:[ar.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ar.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ar.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ar._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,nD.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(os.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${os.default.self}`,`${os.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:h}=u;f.evaluated={props:p instanceof ar.Name?void 0:p,items:h instanceof ar.Name?void 0:h,dynamicProps:p instanceof ar.Name,dynamicItems:h instanceof ar.Name},f.source&&(f.source.evaluated=(0,ar.stringify)(f.evaluated))}return t.validate=f,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}Kt.compileSchema=Ph;function sD(t,e,r){var n;r=(0,cr.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=aD.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new to({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=oD.call(this,o)}Kt.resolveRef=sD;function oD(t){return(0,cr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ph.call(this,t)}function Rk(t){for(let e of this._compilations)if(iD(e,t))return e}Kt.getCompilingSchema=Rk;function iD(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function aD(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Xc.call(this,t,e)}function Xc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,cr._getFullPath)(this.opts.uriResolver,r),s=(0,cr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return Th.call(this,r,t);let o=(0,cr.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Xc.call(this,t,i);return typeof a?.schema!="object"?void 0:Th.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Ph.call(this,i),o===(0,cr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,cr.resolveUrl)(this.opts.uriResolver,s,u)),new to({schema:a,schemaId:c,root:t,baseId:s})}return Th.call(this,r,i)}}Kt.resolveSchema=Xc;var cD=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Th(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Pk.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!cD.has(a)&&u&&(e=(0,cr.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Pk.schemaHasRulesButRef)(r,this.RULES)){let a=(0,cr.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Xc.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new to({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var Ck=D((K3,uD)=>{uD.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 Ch=D((J3,Nk)=>{"use strict";var lD=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ik=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 Rh(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 dD=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ok(t){return t.length=0,!0}function pD(t,e,r){if(t.length){let n=Rh(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function mD(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=pD;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!a(s,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(o=!0),n.push(":");continue}else if(u==="%"){if(!a(s,n,r))break;a=Ok}else{s.push(u);continue}}return s.length&&(a===Ok?r.zone=s.join(""):i?n.push(s.join("")):n.push(Rh(s))),r.address=n.join(""),r}function Ak(t){if(fD(t,":")<2)return{host:t,isIPV6:!1};let e=mD(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 fD(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function hD(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===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(s===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 gD(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 yD(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Ik(r)){let n=Ak(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}Nk.exports={nonSimpleDomain:dD,recomposeAuthority:yD,normalizeComponentEncoding:gD,removeDotSegments:hD,isIPv4:Ik,isUUID:lD,normalizeIPv6:Ak,stringArrayToHexStripped:Rh}});var Lk=D((Y3,zk)=>{"use strict";var{isUUID:_D}=Ch(),xD=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,vD=["http","https","ws","wss","urn","urn:uuid"];function bD(t){return vD.indexOf(t)!==-1}function Oh(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 Dk(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Mk(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 SD(t){return t.secure=Oh(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function kD(t){if((t.port===(Oh(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 wD(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(xD);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=Ih(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function ED(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(),s=`${r}:${e.nid||n}`,o=Ih(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function $D(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!_D(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function TD(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var jk={scheme:"http",domainHost:!0,parse:Dk,serialize:Mk},PD={scheme:"https",domainHost:jk.domainHost,parse:Dk,serialize:Mk},eu={scheme:"ws",domainHost:!0,parse:SD,serialize:kD},RD={scheme:"wss",domainHost:eu.domainHost,parse:eu.parse,serialize:eu.serialize},CD={scheme:"urn",parse:wD,serialize:ED,skipNormalize:!0},OD={scheme:"urn:uuid",parse:$D,serialize:TD,skipNormalize:!0},tu={http:jk,https:PD,ws:eu,wss:RD,urn:CD,"urn:uuid":OD};Object.setPrototypeOf(tu,null);function Ih(t){return t&&(tu[t]||tu[t.toLowerCase()])||void 0}zk.exports={wsIsSecure:Oh,SCHEMES:tu,isValidSchemeName:bD,getSchemeHandler:Ih}});var Hk=D((X3,nu)=>{"use strict";var{normalizeIPv6:ID,removeDotSegments:$i,recomposeAuthority:AD,normalizeComponentEncoding:ru,isIPv4:ND,nonSimpleDomain:DD}=Ch(),{SCHEMES:MD,getSchemeHandler:Fk}=Lk();function jD(t,e){return typeof t=="string"?t=wr(zr(t,e),e):typeof t=="object"&&(t=zr(wr(t,e),e)),t}function zD(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=Uk(zr(t,n),zr(e,n),n,!0);return n.skipEscape=!0,wr(s,n)}function Uk(t,e,r,n){let s={};return n||(t=zr(wr(t,r),r),e=zr(wr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=$i(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=$i(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=$i(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=$i(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function LD(t,e,r){return typeof t=="string"?(t=unescape(t),t=wr(ru(zr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=wr(ru(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=wr(ru(zr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=wr(ru(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function wr(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),s=[],o=Fk(n.scheme||r.scheme);o&&o.serialize&&o.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&&s.push(r.scheme,":");let i=AD(r);if(i!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(i),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=$i(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var FD=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function zr(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},s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(FD);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(ND(n.host)===!1){let c=ID(n.host);n.host=c.host.toLowerCase(),s=c.isIPV6}else s=!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=Fk(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&DD(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 Ah={SCHEMES:MD,normalize:jD,resolve:zD,resolveComponent:Uk,equal:LD,serialize:wr,parse:zr};nu.exports=Ah;nu.exports.default=Ah;nu.exports.fastUri=Ah});var Bk=D(Nh=>{"use strict";Object.defineProperty(Nh,"__esModule",{value:!0});var Zk=Hk();Zk.code='require("ajv/dist/runtime/uri").default';Nh.default=Zk});var Xk=D(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.CodeGen=Qe.Name=Qe.nil=Qe.stringify=Qe.str=Qe._=Qe.KeywordCxt=void 0;var UD=wi();Object.defineProperty(Qe,"KeywordCxt",{enumerable:!0,get:function(){return UD.KeywordCxt}});var ro=te();Object.defineProperty(Qe,"_",{enumerable:!0,get:function(){return ro._}});Object.defineProperty(Qe,"str",{enumerable:!0,get:function(){return ro.str}});Object.defineProperty(Qe,"stringify",{enumerable:!0,get:function(){return ro.stringify}});Object.defineProperty(Qe,"nil",{enumerable:!0,get:function(){return ro.nil}});Object.defineProperty(Qe,"Name",{enumerable:!0,get:function(){return ro.Name}});Object.defineProperty(Qe,"CodeGen",{enumerable:!0,get:function(){return ro.CodeGen}});var HD=Yc(),Kk=Ei(),ZD=uh(),Ti=Qc(),BD=te(),Pi=bi(),su=vi(),Mh=de(),qk=Ck(),qD=Bk(),Jk=(t,e)=>new RegExp(t,e);Jk.code="new RegExp";var VD=["removeAdditional","useDefaults","coerceTypes"],WD=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),GD={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."},KD={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Vk=200;function JD(t){var e,r,n,s,o,i,a,c,u,d,l,m,f,p,h,g,y,x,_,b,w,I,C,T,z;let P=t.strict,O=(e=t.code)===null||e===void 0?void 0:e.optimize,V=O===!0||O===void 0?1:O||0,oe=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Jk,fe=(s=t.uriResolver)!==null&&s!==void 0?s:qD.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:P)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:P)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:P)!==null&&d!==void 0?d:"log",strictTuples:(m=(l=t.strictTuples)!==null&&l!==void 0?l:P)!==null&&m!==void 0?m:"log",strictRequired:(p=(f=t.strictRequired)!==null&&f!==void 0?f:P)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:V,regExp:oe}:{optimize:V,regExp:oe},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Vk,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:Vk,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(x=t.messages)!==null&&x!==void 0?x:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(b=t.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(w=t.addUsedSchema)!==null&&w!==void 0?w:!0,validateSchema:(I=t.validateSchema)!==null&&I!==void 0?I:!0,validateFormats:(C=t.validateFormats)!==null&&C!==void 0?C:!0,unicodeRegExp:(T=t.unicodeRegExp)!==null&&T!==void 0?T:!0,int32range:(z=t.int32range)!==null&&z!==void 0?z:!0,uriResolver:fe}}var Ri=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...JD(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new BD.ValueScope({scope:{},prefixes:WD,es5:r,lines:n}),this.logger=rM(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,ZD.getRules)(),Wk.call(this,GD,e,"NOT SUPPORTED"),Wk.call(this,KD,e,"DEPRECATED","warn"),this._metaOpts=eM.call(this),e.formats&&XD.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&QD.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),YD.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=qk;n==="id"&&(s={...qk},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[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 s=n(r);return"$async"in n||(this.errors=n.errors),s}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 s.call(this,e,r);async function s(d,l){await o.call(this,d.$schema);let m=this._addSchema(d,l);return m.validate||i.call(this,m)}async function o(d){d&&!this.getSchema(d)&&await s.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof Kk.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await o.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Pi.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!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 s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=Gk.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Ti.SchemaEnv({schema:{},schemaId:n});if(r=Ti.resolveSchema.call(this,s,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=Gk.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,Pi.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(sM.call(this,n,r),!r)return(0,Mh.eachItem)(n,o=>Dh.call(this,o)),this;iM.call(this,r);let s={...r,type:(0,su.getJSONTypes)(r.type),schemaType:(0,su.getJSONTypes)(r.schemaType)};return(0,Mh.eachItem)(n,s.type.length===0?o=>Dh.call(this,o,s):o=>s.type.forEach(i=>Dh.call(this,o,s,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 s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,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(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=i[a];u&&d&&(i[a]=Yk(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=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,Pi.normalizeId)(i||n);let u=Pi.getSchemaRefs.call(this,e,n);return c=new Ti.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&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):Ti.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{Ti.compileSchema.call(this,e)}finally{this.opts=r}}};Ri.ValidationError=HD.default;Ri.MissingRefError=Kk.default;Qe.default=Ri;function Wk(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function Gk(t){return t=(0,Pi.normalizeId)(t),this.schemas[t]||this.refs[t]}function YD(){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 XD(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function QD(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 eM(){let t={...this.opts};for(let e of VD)delete t[e];return t}var tM={log(){},warn(){},error(){}};function rM(t){if(t===!1)return tM;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 nM=/^[a-z_$][a-z0-9_$:-]*$/i;function sM(t,e){let{RULES:r}=this;if((0,Mh.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!nM.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 Dh(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,su.getJSONTypes)(e.type),schemaType:(0,su.getJSONTypes)(e.schemaType)}};e.before?oM.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function oM(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function iM(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Yk(e)),t.validateSchema=this.compile(e,!0))}var aM={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Yk(t){return{anyOf:[t,aM]}}});var Qk=D(jh=>{"use strict";Object.defineProperty(jh,"__esModule",{value:!0});var cM={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};jh.default=cM});var n0=D(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.callRef=is.getValidate=void 0;var uM=Ei(),e0=Gt(),$t=te(),no=Mr(),t0=Qc(),ou=de(),lM={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return l();let d=t0.resolveRef.call(c,u,s,r);if(d===void 0)throw new uM.default(n.opts.uriResolver,s,r);if(d instanceof t0.SchemaEnv)return m(d);return f(d);function l(){if(o===u)return iu(t,i,o,o.$async);let p=e.scopeValue("root",{ref:u});return iu(t,(0,$t._)`${p}.validate`,u,u.$async)}function m(p){let h=r0(t,p);iu(t,h,p,p.$async)}function f(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,$t.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:$t.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function r0(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,$t._)`${r.scopeValue("wrapper",{ref:e})}.validate`}is.getValidate=r0;function iu(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?no.default.this:$t.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=s.let("valid");s.try(()=>{s.code((0,$t._)`await ${(0,e0.callValidateCode)(t,e,u)}`),f(e),i||s.assign(p,!0)},h=>{s.if((0,$t._)`!(${h} instanceof ${o.ValidationError})`,()=>s.throw(h)),m(h),i||s.assign(p,!1)}),t.ok(p)}function l(){t.result((0,e0.callValidateCode)(t,e,u),()=>f(e),()=>m(e))}function m(p){let h=(0,$t._)`${p}.errors`;s.assign(no.default.vErrors,(0,$t._)`${no.default.vErrors} === null ? ${h} : ${no.default.vErrors}.concat(${h})`),s.assign(no.default.errors,(0,$t._)`${no.default.vErrors}.length`)}function f(p){var h;if(!o.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=ou.mergeEvaluated.props(s,g.props,o.props));else{let y=s.var("props",(0,$t._)`${p}.evaluated.props`);o.props=ou.mergeEvaluated.props(s,y,o.props,$t.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=ou.mergeEvaluated.items(s,g.items,o.items));else{let y=s.var("items",(0,$t._)`${p}.evaluated.items`);o.items=ou.mergeEvaluated.items(s,y,o.items,$t.Name)}}}is.callRef=iu;is.default=lM});var s0=D(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var dM=Qk(),pM=n0(),mM=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",dM.default,pM.default];zh.default=mM});var o0=D(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});var au=te(),gn=au.operators,cu={maximum:{okStr:"<=",ok:gn.LTE,fail:gn.GT},minimum:{okStr:">=",ok:gn.GTE,fail:gn.LT},exclusiveMaximum:{okStr:"<",ok:gn.LT,fail:gn.GTE},exclusiveMinimum:{okStr:">",ok:gn.GT,fail:gn.LTE}},fM={message:({keyword:t,schemaCode:e})=>(0,au.str)`must be ${cu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,au._)`{comparison: ${cu[t].okStr}, limit: ${e}}`},hM={keyword:Object.keys(cu),type:"number",schemaType:"number",$data:!0,error:fM,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,au._)`${r} ${cu[e].fail} ${n} || isNaN(${r})`)}};Lh.default=hM});var i0=D(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});var Ci=te(),gM={message:({schemaCode:t})=>(0,Ci.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ci._)`{multipleOf: ${t}}`},yM={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:gM,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Ci._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Ci._)`${i} !== parseInt(${i})`;t.fail$data((0,Ci._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Fh.default=yM});var c0=D(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});function a0(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}Uh.default=a0;a0.code='require("ajv/dist/runtime/ucs2length").default'});var u0=D(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});var as=te(),_M=de(),xM=c0(),vM={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,as.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,as._)`{limit: ${t}}`},bM={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:vM,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?as.operators.GT:as.operators.LT,i=s.opts.unicode===!1?(0,as._)`${r}.length`:(0,as._)`${(0,_M.useFunc)(t.gen,xM.default)}(${r})`;t.fail$data((0,as._)`${i} ${o} ${n}`)}};Hh.default=bM});var l0=D(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});var SM=Gt(),kM=de(),so=te(),wM={message:({schemaCode:t})=>(0,so.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,so._)`{pattern: ${t}}`},EM={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:wM,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,so._)`new RegExp`:(0,kM.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,so._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,so._)`!${d}`)}else{let c=(0,SM.usePattern)(t,s);t.fail$data((0,so._)`!${c}.test(${r})`)}}};Zh.default=EM});var d0=D(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});var Oi=te(),$M={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Oi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Oi._)`{limit: ${t}}`},TM={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:$M,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Oi.operators.GT:Oi.operators.LT;t.fail$data((0,Oi._)`Object.keys(${r}).length ${s} ${n}`)}};Bh.default=TM});var p0=D(qh=>{"use strict";Object.defineProperty(qh,"__esModule",{value:!0});var Ii=Gt(),Ai=te(),PM=de(),RM={message:({params:{missingProperty:t}})=>(0,Ai.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ai._)`{missingProperty: ${t}}`},CM={keyword:"required",type:"object",schemaType:"array",$data:!0,error:RM,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:p}=t.it;for(let h of r)if(f?.[h]===void 0&&!p.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,PM.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(Ai.nil,l);else for(let f of r)(0,Ii.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(c||o){let p=e.let("valid",!0);t.block$data(p,()=>m(f,p)),t.ok(p)}else e.if((0,Ii.checkMissingProp)(t,r,f)),(0,Ii.reportMissingProp)(t,f),e.else()}function l(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Ii.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function m(f,p){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(p,(0,Ii.propertyInData)(e,s,f,a.ownProperties)),e.if((0,Ai.not)(p),()=>{t.error(),e.break()})},Ai.nil)}}};qh.default=CM});var m0=D(Vh=>{"use strict";Object.defineProperty(Vh,"__esModule",{value:!0});var Ni=te(),OM={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ni.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ni._)`{limit: ${t}}`},IM={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:OM,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Ni.operators.GT:Ni.operators.LT;t.fail$data((0,Ni._)`${r}.length ${s} ${n}`)}};Vh.default=IM});var uu=D(Wh=>{"use strict";Object.defineProperty(Wh,"__esModule",{value:!0});var f0=yh();f0.code='require("ajv/dist/runtime/equal").default';Wh.default=f0});var h0=D(Kh=>{"use strict";Object.defineProperty(Kh,"__esModule",{value:!0});var Gh=vi(),et=te(),AM=de(),NM=uu(),DM={message:({params:{i:t,j:e}})=>(0,et.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,et._)`{i: ${t}, j: ${e}}`},MM={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:DM,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let c=e.let("valid"),u=o.items?(0,Gh.getSchemaTypes)(o.items):[];t.block$data(c,d,(0,et._)`${i} === false`),t.ok(c);function d(){let p=e.let("i",(0,et._)`${r}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,et._)`${p} > 1`,()=>(l()?m:f)(p,h))}function l(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function m(p,h){let g=e.name("item"),y=(0,Gh.checkDataTypes)(u,g,a.opts.strictNumbers,Gh.DataType.Wrong),x=e.const("indices",(0,et._)`{}`);e.for((0,et._)`;${p}--;`,()=>{e.let(g,(0,et._)`${r}[${p}]`),e.if(y,(0,et._)`continue`),u.length>1&&e.if((0,et._)`typeof ${g} == "string"`,(0,et._)`${g} += "_"`),e.if((0,et._)`typeof ${x}[${g}] == "number"`,()=>{e.assign(h,(0,et._)`${x}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,et._)`${x}[${g}] = ${p}`)})}function f(p,h){let g=(0,AM.useFunc)(e,NM.default),y=e.name("outer");e.label(y).for((0,et._)`;${p}--;`,()=>e.for((0,et._)`${h} = ${p}; ${h}--;`,()=>e.if((0,et._)`${g}(${r}[${p}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Kh.default=MM});var g0=D(Yh=>{"use strict";Object.defineProperty(Yh,"__esModule",{value:!0});var Jh=te(),jM=de(),zM=uu(),LM={message:"must be equal to constant",params:({schemaCode:t})=>(0,Jh._)`{allowedValue: ${t}}`},FM={keyword:"const",$data:!0,error:LM,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Jh._)`!${(0,jM.useFunc)(e,zM.default)}(${r}, ${s})`):t.fail((0,Jh._)`${o} !== ${r}`)}};Yh.default=FM});var y0=D(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});var Di=te(),UM=de(),HM=uu(),ZM={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Di._)`{allowedValues: ${t}}`},BM={keyword:"enum",schemaType:"array",$data:!0,error:ZM,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,UM.useFunc)(e,HM.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let f=e.const("vSchema",o);d=(0,Di.or)(...s.map((p,h)=>m(f,h)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",o,f=>e.if((0,Di._)`${u()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function m(f,p){let h=s[p];return typeof h=="object"&&h!==null?(0,Di._)`${u()}(${r}, ${f}[${p}])`:(0,Di._)`${r} === ${h}`}}};Xh.default=BM});var _0=D(Qh=>{"use strict";Object.defineProperty(Qh,"__esModule",{value:!0});var qM=o0(),VM=i0(),WM=u0(),GM=l0(),KM=d0(),JM=p0(),YM=m0(),XM=h0(),QM=g0(),ej=y0(),tj=[qM.default,VM.default,WM.default,GM.default,KM.default,JM.default,YM.default,XM.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},QM.default,ej.default];Qh.default=tj});var tg=D(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.validateAdditionalItems=void 0;var cs=te(),eg=de(),rj={message:({params:{len:t}})=>(0,cs.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,cs._)`{limit: ${t}}`},nj={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:rj,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,eg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}x0(t,n)}};function x0(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,cs._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,cs._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,eg.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,cs._)`${a} <= ${e.length}`);r.if((0,cs.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:eg.Type.Num},u),i.allErrors||r.if((0,cs.not)(u),()=>r.break())})}}Mi.validateAdditionalItems=x0;Mi.default=nj});var rg=D(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.validateTuple=void 0;var v0=te(),lu=de(),sj=Gt(),oj={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return b0(t,"additionalItems",e);r.items=!0,!(0,lu.alwaysValidSchema)(r,e)&&t.ok((0,sj.validateArray)(t))}};function b0(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;d(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=lu.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,v0._)`${o}.length`);r.forEach((l,m)=>{(0,lu.alwaysValidSchema)(a,l)||(n.if((0,v0._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function d(l){let{opts:m,errSchemaPath:f}=a,p=r.length,h=p===l.minItems&&(p===l.maxItems||l[e]===!1);if(m.strictTuples&&!h){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,lu.checkStrictMode)(a,g,m.strictTuples)}}}ji.validateTuple=b0;ji.default=oj});var S0=D(ng=>{"use strict";Object.defineProperty(ng,"__esModule",{value:!0});var ij=rg(),aj={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,ij.validateTuple)(t,"items")};ng.default=aj});var w0=D(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});var k0=te(),cj=de(),uj=Gt(),lj=tg(),dj={message:({params:{len:t}})=>(0,k0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,k0._)`{limit: ${t}}`},pj={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:dj,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,cj.alwaysValidSchema)(n,e)&&(s?(0,lj.validateAdditionalItems)(t,s):t.ok((0,uj.validateArray)(t)))}};sg.default=pj});var E0=D(og=>{"use strict";Object.defineProperty(og,"__esModule",{value:!0});var Jt=te(),du=de(),mj={message:({params:{min:t,max:e}})=>e===void 0?(0,Jt.str)`must contain at least ${t} valid item(s)`:(0,Jt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Jt._)`{minContains: ${t}}`:(0,Jt._)`{minContains: ${t}, maxContains: ${e}}`},fj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:mj,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:c,maxContains:u}=n;o.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,Jt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,du.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,du.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,du.alwaysValidSchema)(o,r)){let h=(0,Jt._)`${d} >= ${i}`;a!==void 0&&(h=(0,Jt._)`${h} && ${d} <= ${a}`),t.pass(h);return}o.items=!0;let l=e.name("valid");a===void 0&&i===1?f(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,Jt._)`${s}.length > 0`,m)):(e.let(l,!1),m()),t.result(l,()=>t.reset());function m(){let h=e.name("_valid"),g=e.let("count",0);f(h,()=>e.if(h,()=>p(g)))}function f(h,g){e.forRange("i",0,d,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:du.Type.Num,compositeRule:!0},h),g()})}function p(h){e.code((0,Jt._)`${h}++`),a===void 0?e.if((0,Jt._)`${h} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,Jt._)`${h} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,Jt._)`${h} >= ${i}`,()=>e.assign(l,!0)))}}};og.default=fj});var P0=D(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.validateSchemaDeps=Er.validatePropertyDeps=Er.error=void 0;var ig=te(),hj=de(),zi=Gt();Er.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,ig.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,ig._)`{property: ${t},
|
|
68
|
+
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,Q._)`[${s}]`)}}}function oN({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,Q._)`${e} !== undefined`,()=>t.assign((0,Q._)`${e}[${r}]`,n))}function fh(t,e,r,n=eo.Correct){let s=n===eo.Correct?Q.operators.EQ:Q.operators.NEQ,o;switch(t){case"null":return(0,Q._)`${e} ${s} null`;case"array":o=(0,Q._)`Array.isArray(${e})`;break;case"object":o=(0,Q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,Q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,Q._)`typeof ${e} ${s} ${t}`}return n===eo.Correct?o:(0,Q.not)(o);function i(a=Q.nil){return(0,Q.and)((0,Q._)`typeof ${e} == "number"`,a,r?(0,Q._)`isFinite(${e})`:Q.nil)}}at.checkDataType=fh;function hh(t,e,r,n){if(t.length===1)return fh(t[0],e,r,n);let s,o=(0,QS.toHash)(t);if(o.array&&o.object){let i=(0,Q._)`typeof ${e} != "object"`;s=o.null?i:(0,Q._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=Q.nil;o.number&&delete o.integer;for(let i in o)s=(0,Q.and)(s,fh(i,e,r,n));return s}at.checkDataTypes=hh;var iN={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Q._)`{type: ${t}}`:(0,Q._)`{type: ${e}}`};function gh(t){let e=aN(t);(0,eN.reportError)(e,iN)}at.reportTypeError=gh;function aN(t){let{gen:e,data:r,schema:n}=t,s=(0,QS.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var nk=D(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.assignDefaults=void 0;var to=te(),cN=pe();function uN(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)rk(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>rk(t,o,s.default))}Wc.assignDefaults=uN;function rk(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,to._)`${o}${(0,to.getProperty)(e)}`;if(s){(0,cN.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,to._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,to._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,to._)`${a} = ${(0,to.stringify)(r)}`)}});var Kt=D(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.validateUnion=ve.validateArray=ve.usePattern=ve.callValidateCode=ve.schemaProperties=ve.allSchemaProperties=ve.noPropertyInData=ve.propertyInData=ve.isOwnProperty=ve.hasPropFunc=ve.reportMissingProp=ve.checkMissingProp=ve.checkReportMissingProp=void 0;var Pe=te(),yh=pe(),mn=jr(),lN=pe();function dN(t,e){let{gen:r,data:n,it:s}=t;r.if(xh(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Pe._)`${e}`},!0),t.error()})}ve.checkReportMissingProp=dN;function pN({gen:t,data:e,it:{opts:r}},n,s){return(0,Pe.or)(...n.map(o=>(0,Pe.and)(xh(t,e,o,r.ownProperties),(0,Pe._)`${s} = ${o}`)))}ve.checkMissingProp=pN;function mN(t,e){t.setParams({missingProperty:e},!0),t.error()}ve.reportMissingProp=mN;function sk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Pe._)`Object.prototype.hasOwnProperty`})}ve.hasPropFunc=sk;function _h(t,e,r){return(0,Pe._)`${sk(t)}.call(${e}, ${r})`}ve.isOwnProperty=_h;function fN(t,e,r,n){let s=(0,Pe._)`${e}${(0,Pe.getProperty)(r)} !== undefined`;return n?(0,Pe._)`${s} && ${_h(t,e,r)}`:s}ve.propertyInData=fN;function xh(t,e,r,n){let s=(0,Pe._)`${e}${(0,Pe.getProperty)(r)} === undefined`;return n?(0,Pe.or)(s,(0,Pe.not)(_h(t,e,r))):s}ve.noPropertyInData=xh;function ok(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ve.allSchemaProperties=ok;function hN(t,e){return ok(e).filter(r=>!(0,yh.alwaysValidSchema)(t,e[r]))}ve.schemaProperties=hN;function gN({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,u){let d=u?(0,Pe._)`${t}, ${e}, ${n}${s}`:e,l=[[mn.default.instancePath,(0,Pe.strConcat)(mn.default.instancePath,o)],[mn.default.parentData,i.parentData],[mn.default.parentDataProperty,i.parentDataProperty],[mn.default.rootData,mn.default.rootData]];i.opts.dynamicRef&&l.push([mn.default.dynamicAnchors,mn.default.dynamicAnchors]);let m=(0,Pe._)`${d}, ${r.object(...l)}`;return c!==Pe.nil?(0,Pe._)`${a}.call(${c}, ${m})`:(0,Pe._)`${a}(${m})`}ve.callValidateCode=gN;var yN=(0,Pe._)`new RegExp`;function _N({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,Pe._)`${s.code==="new RegExp"?yN:(0,lN.useFunc)(t,s)}(${r}, ${n})`})}ve.usePattern=_N;function xN(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let c=e.const("len",(0,Pe._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:yh.Type.Num},o),e.if((0,Pe.not)(o),a)})}}ve.validateArray=xN;function vN(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,yh.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Pe._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,Pe.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ve.validateUnion=vN});var ck=D(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.validateKeywordUsage=kr.validSchemaType=kr.funcKeywordCode=kr.macroKeywordCode=void 0;var ht=te(),os=jr(),bN=Kt(),SN=vi();function kN(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=ak(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:ht.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}kr.macroKeywordCode=kN;function wN(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;$N(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,d=ak(n,s,u),l=n.let("valid");t.block$data(l,m),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function m(){if(e.errors===!1)h(),e.modifying&&ik(t),g(()=>t.error());else{let _=e.async?f():p();e.modifying&&ik(t),g(()=>EN(t,_))}}function f(){let _=n.let("ruleErrs",null);return n.try(()=>h((0,ht._)`await `),x=>n.assign(l,!1).if((0,ht._)`${x} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,ht._)`${x}.errors`),()=>n.throw(x))),_}function p(){let _=(0,ht._)`${d}.errors`;return n.assign(_,null),h(ht.nil),_}function h(_=e.async?(0,ht._)`await `:ht.nil){let x=c.opts.passContext?os.default.this:os.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,ht._)`${_}${(0,bN.callValidateCode)(t,d,x,y)}`,e.modifying)}function g(_){var x;n.if((0,ht.not)((x=e.valid)!==null&&x!==void 0?x:l),_)}}kr.funcKeywordCode=wN;function ik(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ht._)`${n.parentData}[${n.parentDataProperty}]`))}function EN(t,e){let{gen:r}=t;r.if((0,ht._)`Array.isArray(${e})`,()=>{r.assign(os.default.vErrors,(0,ht._)`${os.default.vErrors} === null ? ${e} : ${os.default.vErrors}.concat(${e})`).assign(os.default.errors,(0,ht._)`${os.default.vErrors}.length`),(0,SN.extendErrors)(t)},()=>t.error())}function $N({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function ak(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,ht.stringify)(r)})}function TN(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")}kr.validSchemaType=TN;function PN({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}kr.validateKeywordUsage=PN});var lk=D(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.extendSubschemaMode=fn.extendSubschemaData=fn.getSubschema=void 0;var wr=te(),uk=pe();function RN(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,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,wr._)`${t.schemaPath}${(0,wr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,wr._)`${t.schemaPath}${(0,wr.getProperty)(e)}${(0,wr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,uk.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}fn.getSubschema=RN;function CN(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==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:d,opts:l}=e,m=a.let("data",(0,wr._)`${e.data}${(0,wr.getProperty)(r)}`,!0);c(m),t.errorPath=(0,wr.str)`${u}${(0,uk.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,wr._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof wr.Name?s:a.let("data",s,!0);c(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);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]}}fn.extendSubschemaData=CN;function ON(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}fn.extendSubschemaMode=ON});var vh=D((rV,dk)=>{"use strict";dk.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,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))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(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var mk=D((nV,pk)=>{"use strict";var hn=pk.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};Gc(e,n,s,t,"",t)};hn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};hn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};hn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};hn.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 Gc(t,e,r,n,s,o,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in hn.arrayKeywords)for(var m=0;m<l.length;m++)Gc(t,e,r,l[m],s+"/"+d+"/"+m,o,s,d,n,m)}else if(d in hn.propsKeywords){if(l&&typeof l=="object")for(var f in l)Gc(t,e,r,l[f],s+"/"+d+"/"+IN(f),o,s,d,n,f)}else(d in hn.keywords||t.allKeys&&!(d in hn.skipKeywords))&&Gc(t,e,r,l,s+"/"+d,o,s,d,n)}r(n,s,o,i,a,c,u)}}function IN(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Si=D(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.getSchemaRefs=Et.resolveUrl=Et.normalizeId=Et._getFullPath=Et.getFullPath=Et.inlineRef=void 0;var AN=pe(),NN=vh(),DN=mk(),MN=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function jN(t,e=!0){return typeof t=="boolean"?!0:e===!0?!bh(t):e?fk(t)<=e:!1}Et.inlineRef=jN;var zN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function bh(t){for(let e in t){if(zN.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(bh)||typeof r=="object"&&bh(r))return!0}return!1}function fk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!MN.has(r)&&(typeof t[r]=="object"&&(0,AN.eachItem)(t[r],n=>e+=fk(n)),e===1/0))return 1/0}return e}function hk(t,e="",r){r!==!1&&(e=ro(e));let n=t.parse(e);return gk(t,n)}Et.getFullPath=hk;function gk(t,e){return t.serialize(e).split("#")[0]+"#"}Et._getFullPath=gk;var LN=/#\/?$/;function ro(t){return t?t.replace(LN,""):""}Et.normalizeId=ro;function FN(t,e,r){return r=ro(r),t.resolve(e,r)}Et.resolveUrl=FN;var UN=/^[a-z_][-a-z0-9._]*$/i;function HN(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=ro(t[r]||e),o={"":s},i=hk(n,s,!1),a={},c=new Set;return DN(t,{allKeys:!0},(l,m,f,p)=>{if(p===void 0)return;let h=i+m,g=o[p];typeof l[r]=="string"&&(g=_.call(this,l[r])),x.call(this,l.$anchor),x.call(this,l.$dynamicAnchor),o[m]=g;function _(y){let b=this.opts.uriResolver.resolve;if(y=ro(g?b(g,y):y),c.has(y))throw d(y);c.add(y);let w=this.refs[y];return typeof w=="string"&&(w=this.refs[w]),typeof w=="object"?u(l,w.schema,y):y!==ro(h)&&(y[0]==="#"?(u(l,a[y],y),a[y]=l):this.refs[y]=h),y}function x(y){if(typeof y=="string"){if(!UN.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(l,m,f){if(m!==void 0&&!NN(l,m))throw d(f)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Et.getSchemaRefs=HN});var Ei=D(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.getData=gn.KeywordCxt=gn.validateFunctionCode=void 0;var bk=JS(),yk=bi(),kh=mh(),Kc=bi(),ZN=nk(),wi=ck(),Sh=lk(),Z=te(),Y=jr(),BN=Si(),zr=pe(),ki=vi();function qN(t){if(wk(t)&&(Ek(t),kk(t))){GN(t);return}Sk(t,()=>(0,bk.topBoolOrEmptySchema)(t))}gn.validateFunctionCode=qN;function Sk({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,Z._)`${Y.default.data}, ${Y.default.valCxt}`,n.$async,()=>{t.code((0,Z._)`"use strict"; ${_k(r,s)}`),WN(t,s),t.code(o)}):t.func(e,(0,Z._)`${Y.default.data}, ${VN(s)}`,n.$async,()=>t.code(_k(r,s)).code(o))}function VN(t){return(0,Z._)`{${Y.default.instancePath}="", ${Y.default.parentData}, ${Y.default.parentDataProperty}, ${Y.default.rootData}=${Y.default.data}${t.dynamicRef?(0,Z._)`, ${Y.default.dynamicAnchors}={}`:Z.nil}}={}`}function WN(t,e){t.if(Y.default.valCxt,()=>{t.var(Y.default.instancePath,(0,Z._)`${Y.default.valCxt}.${Y.default.instancePath}`),t.var(Y.default.parentData,(0,Z._)`${Y.default.valCxt}.${Y.default.parentData}`),t.var(Y.default.parentDataProperty,(0,Z._)`${Y.default.valCxt}.${Y.default.parentDataProperty}`),t.var(Y.default.rootData,(0,Z._)`${Y.default.valCxt}.${Y.default.rootData}`),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,Z._)`${Y.default.valCxt}.${Y.default.dynamicAnchors}`)},()=>{t.var(Y.default.instancePath,(0,Z._)`""`),t.var(Y.default.parentData,(0,Z._)`undefined`),t.var(Y.default.parentDataProperty,(0,Z._)`undefined`),t.var(Y.default.rootData,Y.default.data),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,Z._)`{}`)})}function GN(t){let{schema:e,opts:r,gen:n}=t;Sk(t,()=>{r.$comment&&e.$comment&&Tk(t),QN(t),n.let(Y.default.vErrors,null),n.let(Y.default.errors,0),r.unevaluated&&KN(t),$k(t),rD(t)})}function KN(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Z._)`${r}.evaluated`),e.if((0,Z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Z._)`${t.evaluated}.props`,(0,Z._)`undefined`)),e.if((0,Z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Z._)`${t.evaluated}.items`,(0,Z._)`undefined`))}function _k(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Z._)`/*# sourceURL=${r} */`:Z.nil}function JN(t,e){if(wk(t)&&(Ek(t),kk(t))){YN(t,e);return}(0,bk.boolOrEmptySchema)(t,e)}function kk({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 wk(t){return typeof t.schema!="boolean"}function YN(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&Tk(t),eD(t),tD(t);let o=n.const("_errs",Y.default.errors);$k(t,o),n.var(e,(0,Z._)`${o} === ${Y.default.errors}`)}function Ek(t){(0,zr.checkUnknownRules)(t),XN(t)}function $k(t,e){if(t.opts.jtd)return xk(t,[],!1,e);let r=(0,yk.getSchemaTypes)(t.schema),n=(0,yk.coerceAndCheckDataType)(t,r);xk(t,r,!n,e)}function XN(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,zr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function QN(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,zr.checkStrictMode)(t,"default is ignored in the schema root")}function eD(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,BN.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function tD(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Tk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,Z._)`${Y.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,Z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Z._)`${Y.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function rD(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,Z._)`${Y.default.errors} === 0`,()=>e.return(Y.default.data),()=>e.throw((0,Z._)`new ${s}(${Y.default.vErrors})`)):(e.assign((0,Z._)`${n}.errors`,Y.default.vErrors),o.unevaluated&&nD(t),e.return((0,Z._)`${Y.default.errors} === 0`))}function nD({gen:t,evaluated:e,props:r,items:n}){r instanceof Z.Name&&t.assign((0,Z._)`${e}.props`,r),n instanceof Z.Name&&t.assign((0,Z._)`${e}.items`,n)}function xk(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,zr.schemaHasRulesButRef)(o,d))){s.block(()=>Rk(t,"$ref",d.all.$ref.definition));return}c.jtd||sD(t,e),s.block(()=>{for(let m of d.rules)l(m);l(d.post)});function l(m){(0,kh.shouldUseGroup)(o,m)&&(m.type?(s.if((0,Kc.checkDataType)(m.type,i,c.strictNumbers)),vk(t,m),e.length===1&&e[0]===m.type&&r&&(s.else(),(0,Kc.reportTypeError)(t)),s.endIf()):vk(t,m),a||s.if((0,Z._)`${Y.default.errors} === ${n||0}`))}}function vk(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,ZN.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,kh.shouldUseRule)(n,o)&&Rk(t,o.keyword,o.definition,e.type)})}function sD(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(oD(t,e),t.opts.allowUnionTypes||iD(t,e),aD(t,t.dataTypes))}function oD(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Pk(t.dataTypes,r)||wh(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),uD(t,e)}}function iD(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&wh(t,"use allowUnionTypes to allow union type keyword")}function aD(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,kh.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>cD(e,i))&&wh(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function cD(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Pk(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function uD(t,e){let r=[];for(let n of t.dataTypes)Pk(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function wh(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,zr.checkStrictMode)(t,e,t.opts.strictTypes)}var Jc=class{constructor(e,r,n){if((0,wi.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,zr.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",Ck(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,wi.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",Y.default.errors))}result(e,r,n){this.failResult((0,Z.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,Z.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,Z._)`${r} !== undefined && (${(0,Z.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?ki.reportExtraError:ki.reportError)(this,this.def.error,r)}$dataError(){(0,ki.reportError)(this,this.def.$dataError||ki.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ki.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=Z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Z.nil,r=Z.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,Z.or)((0,Z._)`${s} === undefined`,r)),e!==Z.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,Z.or)(i(),a());function i(){if(n.length){if(!(r instanceof Z.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Z._)`${(0,Kc.checkDataTypes)(c,r,o.opts.strictNumbers,Kc.DataType.Wrong)}`}return Z.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,Z._)`!${c}(${r})`}return Z.nil}}subschema(e,r){let n=(0,Sh.getSubschema)(this.it,e);(0,Sh.extendSubschemaData)(n,this.it,e),(0,Sh.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return JN(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=zr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=zr.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,Z.Name)),!0}};gn.KeywordCxt=Jc;function Rk(t,e,r,n){let s=new Jc(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,wi.funcKeywordCode)(s,r):"macro"in r?(0,wi.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,wi.funcKeywordCode)(s,r)}var lD=/^\/(?:[^~]|~0|~1)*$/,dD=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ck(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return Y.default.rootData;if(t[0]==="/"){if(!lD.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Y.default.rootData}else{let u=dD.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(s=u[2],s==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(o=r[e-d],!s)return o}let i=o,a=s.split("/");for(let u of a)u&&(o=(0,Z._)`${o}${(0,Z.getProperty)((0,zr.unescapeJsonPointer)(u))}`,i=(0,Z._)`${i} && ${o}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}gn.getData=Ck});var Yc=D($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});var Eh=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};$h.default=Eh});var $i=D(Rh=>{"use strict";Object.defineProperty(Rh,"__esModule",{value:!0});var Th=Si(),Ph=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Th.resolveUrl)(e,r,n),this.missingSchema=(0,Th.normalizeId)((0,Th.getFullPath)(e,this.missingRef))}};Rh.default=Ph});var Qc=D(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.resolveSchema=Jt.getCompilingSchema=Jt.resolveRef=Jt.compileSchema=Jt.SchemaEnv=void 0;var ur=te(),pD=Yc(),is=jr(),lr=Si(),Ok=pe(),mD=Ei(),no=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,lr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Jt.SchemaEnv=no;function Oh(t){let e=Ik.call(this,t);if(e)return e;let r=(0,lr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new ur.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:pD.default,code:(0,ur._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:is.default.data,parentData:is.default.parentData,parentDataProperty:is.default.parentDataProperty,dataNames:[is.default.data],dataPathArr:[ur.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ur.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ur.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ur._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,mD.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(is.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${is.default.self}`,`${is.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:h}=u;f.evaluated={props:p instanceof ur.Name?void 0:p,items:h instanceof ur.Name?void 0:h,dynamicProps:p instanceof ur.Name,dynamicItems:h instanceof ur.Name},f.source&&(f.source.evaluated=(0,ur.stringify)(f.evaluated))}return t.validate=f,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}Jt.compileSchema=Oh;function fD(t,e,r){var n;r=(0,lr.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=yD.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new no({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=hD.call(this,o)}Jt.resolveRef=fD;function hD(t){return(0,lr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Oh.call(this,t)}function Ik(t){for(let e of this._compilations)if(gD(e,t))return e}Jt.getCompilingSchema=Ik;function gD(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function yD(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Xc.call(this,t,e)}function Xc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,lr._getFullPath)(this.opts.uriResolver,r),s=(0,lr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return Ch.call(this,r,t);let o=(0,lr.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Xc.call(this,t,i);return typeof a?.schema!="object"?void 0:Ch.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Oh.call(this,i),o===(0,lr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,lr.resolveUrl)(this.opts.uriResolver,s,u)),new no({schema:a,schemaId:c,root:t,baseId:s})}return Ch.call(this,r,i)}}Jt.resolveSchema=Xc;var _D=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ch(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Ok.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!_D.has(a)&&u&&(e=(0,lr.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Ok.schemaHasRulesButRef)(r,this.RULES)){let a=(0,lr.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Xc.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new no({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var Ak=D((uV,xD)=>{xD.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 Ah=D((lV,jk)=>{"use strict";var vD=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Dk=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 Ih(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 bD=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Nk(t){return t.length=0,!0}function SD(t,e,r){if(t.length){let n=Ih(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function kD(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=SD;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!a(s,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(o=!0),n.push(":");continue}else if(u==="%"){if(!a(s,n,r))break;a=Nk}else{s.push(u);continue}}return s.length&&(a===Nk?r.zone=s.join(""):i?n.push(s.join("")):n.push(Ih(s))),r.address=n.join(""),r}function Mk(t){if(wD(t,":")<2)return{host:t,isIPV6:!1};let e=kD(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 wD(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function ED(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===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(s===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 $D(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 TD(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Dk(r)){let n=Mk(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}jk.exports={nonSimpleDomain:bD,recomposeAuthority:TD,normalizeComponentEncoding:$D,removeDotSegments:ED,isIPv4:Dk,isUUID:vD,normalizeIPv6:Mk,stringArrayToHexStripped:Ih}});var Hk=D((dV,Uk)=>{"use strict";var{isUUID:PD}=Ah(),RD=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,CD=["http","https","ws","wss","urn","urn:uuid"];function OD(t){return CD.indexOf(t)!==-1}function Nh(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 zk(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Lk(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 ID(t){return t.secure=Nh(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function AD(t){if((t.port===(Nh(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 ND(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(RD);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=Dh(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function DD(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(),s=`${r}:${e.nid||n}`,o=Dh(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function MD(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!PD(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function jD(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Fk={scheme:"http",domainHost:!0,parse:zk,serialize:Lk},zD={scheme:"https",domainHost:Fk.domainHost,parse:zk,serialize:Lk},eu={scheme:"ws",domainHost:!0,parse:ID,serialize:AD},LD={scheme:"wss",domainHost:eu.domainHost,parse:eu.parse,serialize:eu.serialize},FD={scheme:"urn",parse:ND,serialize:DD,skipNormalize:!0},UD={scheme:"urn:uuid",parse:MD,serialize:jD,skipNormalize:!0},tu={http:Fk,https:zD,ws:eu,wss:LD,urn:FD,"urn:uuid":UD};Object.setPrototypeOf(tu,null);function Dh(t){return t&&(tu[t]||tu[t.toLowerCase()])||void 0}Uk.exports={wsIsSecure:Nh,SCHEMES:tu,isValidSchemeName:OD,getSchemeHandler:Dh}});var qk=D((pV,nu)=>{"use strict";var{normalizeIPv6:HD,removeDotSegments:Ti,recomposeAuthority:ZD,normalizeComponentEncoding:ru,isIPv4:BD,nonSimpleDomain:qD}=Ah(),{SCHEMES:VD,getSchemeHandler:Zk}=Hk();function WD(t,e){return typeof t=="string"?t=Er(Lr(t,e),e):typeof t=="object"&&(t=Lr(Er(t,e),e)),t}function GD(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=Bk(Lr(t,n),Lr(e,n),n,!0);return n.skipEscape=!0,Er(s,n)}function Bk(t,e,r,n){let s={};return n||(t=Lr(Er(t,r),r),e=Lr(Er(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ti(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ti(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Ti(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=Ti(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function KD(t,e,r){return typeof t=="string"?(t=unescape(t),t=Er(ru(Lr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Er(ru(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Er(ru(Lr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Er(ru(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Er(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),s=[],o=Zk(n.scheme||r.scheme);o&&o.serialize&&o.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&&s.push(r.scheme,":");let i=ZD(r);if(i!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(i),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=Ti(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var JD=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Lr(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},s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(JD);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(BD(n.host)===!1){let c=HD(n.host);n.host=c.host.toLowerCase(),s=c.isIPV6}else s=!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=Zk(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&qD(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 Mh={SCHEMES:VD,normalize:WD,resolve:GD,resolveComponent:Bk,equal:KD,serialize:Er,parse:Lr};nu.exports=Mh;nu.exports.default=Mh;nu.exports.fastUri=Mh});var Wk=D(jh=>{"use strict";Object.defineProperty(jh,"__esModule",{value:!0});var Vk=qk();Vk.code='require("ajv/dist/runtime/uri").default';jh.default=Vk});var t0=D(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.CodeGen=Qe.Name=Qe.nil=Qe.stringify=Qe.str=Qe._=Qe.KeywordCxt=void 0;var YD=Ei();Object.defineProperty(Qe,"KeywordCxt",{enumerable:!0,get:function(){return YD.KeywordCxt}});var so=te();Object.defineProperty(Qe,"_",{enumerable:!0,get:function(){return so._}});Object.defineProperty(Qe,"str",{enumerable:!0,get:function(){return so.str}});Object.defineProperty(Qe,"stringify",{enumerable:!0,get:function(){return so.stringify}});Object.defineProperty(Qe,"nil",{enumerable:!0,get:function(){return so.nil}});Object.defineProperty(Qe,"Name",{enumerable:!0,get:function(){return so.Name}});Object.defineProperty(Qe,"CodeGen",{enumerable:!0,get:function(){return so.CodeGen}});var XD=Yc(),Xk=$i(),QD=ph(),Pi=Qc(),eM=te(),Ri=Si(),su=bi(),Lh=pe(),Gk=Ak(),tM=Wk(),Qk=(t,e)=>new RegExp(t,e);Qk.code="new RegExp";var rM=["removeAdditional","useDefaults","coerceTypes"],nM=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),sM={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."},oM={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Kk=200;function iM(t){var e,r,n,s,o,i,a,c,u,d,l,m,f,p,h,g,_,x,y,b,w,O,C,T,z;let P=t.strict,I=(e=t.code)===null||e===void 0?void 0:e.optimize,V=I===!0||I===void 0?1:I||0,oe=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Qk,he=(s=t.uriResolver)!==null&&s!==void 0?s:tM.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:P)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:P)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:P)!==null&&d!==void 0?d:"log",strictTuples:(m=(l=t.strictTuples)!==null&&l!==void 0?l:P)!==null&&m!==void 0?m:"log",strictRequired:(p=(f=t.strictRequired)!==null&&f!==void 0?f:P)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:V,regExp:oe}:{optimize:V,regExp:oe},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Kk,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:Kk,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(x=t.messages)!==null&&x!==void 0?x:!0,inlineRefs:(y=t.inlineRefs)!==null&&y!==void 0?y:!0,schemaId:(b=t.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(w=t.addUsedSchema)!==null&&w!==void 0?w:!0,validateSchema:(O=t.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(C=t.validateFormats)!==null&&C!==void 0?C:!0,unicodeRegExp:(T=t.unicodeRegExp)!==null&&T!==void 0?T:!0,int32range:(z=t.int32range)!==null&&z!==void 0?z:!0,uriResolver:he}}var Ci=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,...iM(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new eM.ValueScope({scope:{},prefixes:nM,es5:r,lines:n}),this.logger=pM(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,QD.getRules)(),Jk.call(this,sM,e,"NOT SUPPORTED"),Jk.call(this,oM,e,"DEPRECATED","warn"),this._metaOpts=lM.call(this),e.formats&&cM.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&uM.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),aM.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Gk;n==="id"&&(s={...Gk},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[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 s=n(r);return"$async"in n||(this.errors=n.errors),s}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 s.call(this,e,r);async function s(d,l){await o.call(this,d.$schema);let m=this._addSchema(d,l);return m.validate||i.call(this,m)}async function o(d){d&&!this.getSchema(d)&&await s.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof Xk.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await o.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Ri.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!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 s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=Yk.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Pi.SchemaEnv({schema:{},schemaId:n});if(r=Pi.resolveSchema.call(this,s,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=Yk.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,Ri.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(fM.call(this,n,r),!r)return(0,Lh.eachItem)(n,o=>zh.call(this,o)),this;gM.call(this,r);let s={...r,type:(0,su.getJSONTypes)(r.type),schemaType:(0,su.getJSONTypes)(r.schemaType)};return(0,Lh.eachItem)(n,s.type.length===0?o=>zh.call(this,o,s):o=>s.type.forEach(i=>zh.call(this,o,s,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 s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,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(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=i[a];u&&d&&(i[a]=e0(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=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,Ri.normalizeId)(i||n);let u=Ri.getSchemaRefs.call(this,e,n);return c=new Pi.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&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):Pi.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{Pi.compileSchema.call(this,e)}finally{this.opts=r}}};Ci.ValidationError=XD.default;Ci.MissingRefError=Xk.default;Qe.default=Ci;function Jk(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function Yk(t){return t=(0,Ri.normalizeId)(t),this.schemas[t]||this.refs[t]}function aM(){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 cM(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function uM(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 lM(){let t={...this.opts};for(let e of rM)delete t[e];return t}var dM={log(){},warn(){},error(){}};function pM(t){if(t===!1)return dM;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 mM=/^[a-z_$][a-z0-9_$:-]*$/i;function fM(t,e){let{RULES:r}=this;if((0,Lh.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!mM.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 zh(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,su.getJSONTypes)(e.type),schemaType:(0,su.getJSONTypes)(e.schemaType)}};e.before?hM.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function hM(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function gM(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=e0(e)),t.validateSchema=this.compile(e,!0))}var yM={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function e0(t){return{anyOf:[t,yM]}}});var r0=D(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});var _M={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Fh.default=_M});var i0=D(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.callRef=as.getValidate=void 0;var xM=$i(),n0=Kt(),$t=te(),oo=jr(),s0=Qc(),ou=pe(),vM={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return l();let d=s0.resolveRef.call(c,u,s,r);if(d===void 0)throw new xM.default(n.opts.uriResolver,s,r);if(d instanceof s0.SchemaEnv)return m(d);return f(d);function l(){if(o===u)return iu(t,i,o,o.$async);let p=e.scopeValue("root",{ref:u});return iu(t,(0,$t._)`${p}.validate`,u,u.$async)}function m(p){let h=o0(t,p);iu(t,h,p,p.$async)}function f(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,$t.stringify)(p)}:{ref:p}),g=e.name("valid"),_=t.subschema({schema:p,dataTypes:[],schemaPath:$t.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(_),t.ok(g)}}};function o0(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,$t._)`${r.scopeValue("wrapper",{ref:e})}.validate`}as.getValidate=o0;function iu(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?oo.default.this:$t.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=s.let("valid");s.try(()=>{s.code((0,$t._)`await ${(0,n0.callValidateCode)(t,e,u)}`),f(e),i||s.assign(p,!0)},h=>{s.if((0,$t._)`!(${h} instanceof ${o.ValidationError})`,()=>s.throw(h)),m(h),i||s.assign(p,!1)}),t.ok(p)}function l(){t.result((0,n0.callValidateCode)(t,e,u),()=>f(e),()=>m(e))}function m(p){let h=(0,$t._)`${p}.errors`;s.assign(oo.default.vErrors,(0,$t._)`${oo.default.vErrors} === null ? ${h} : ${oo.default.vErrors}.concat(${h})`),s.assign(oo.default.errors,(0,$t._)`${oo.default.vErrors}.length`)}function f(p){var h;if(!o.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=ou.mergeEvaluated.props(s,g.props,o.props));else{let _=s.var("props",(0,$t._)`${p}.evaluated.props`);o.props=ou.mergeEvaluated.props(s,_,o.props,$t.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=ou.mergeEvaluated.items(s,g.items,o.items));else{let _=s.var("items",(0,$t._)`${p}.evaluated.items`);o.items=ou.mergeEvaluated.items(s,_,o.items,$t.Name)}}}as.callRef=iu;as.default=vM});var a0=D(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});var bM=r0(),SM=i0(),kM=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",bM.default,SM.default];Uh.default=kM});var c0=D(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});var au=te(),yn=au.operators,cu={maximum:{okStr:"<=",ok:yn.LTE,fail:yn.GT},minimum:{okStr:">=",ok:yn.GTE,fail:yn.LT},exclusiveMaximum:{okStr:"<",ok:yn.LT,fail:yn.GTE},exclusiveMinimum:{okStr:">",ok:yn.GT,fail:yn.LTE}},wM={message:({keyword:t,schemaCode:e})=>(0,au.str)`must be ${cu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,au._)`{comparison: ${cu[t].okStr}, limit: ${e}}`},EM={keyword:Object.keys(cu),type:"number",schemaType:"number",$data:!0,error:wM,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,au._)`${r} ${cu[e].fail} ${n} || isNaN(${r})`)}};Hh.default=EM});var u0=D(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});var Oi=te(),$M={message:({schemaCode:t})=>(0,Oi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Oi._)`{multipleOf: ${t}}`},TM={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:$M,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Oi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Oi._)`${i} !== parseInt(${i})`;t.fail$data((0,Oi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Zh.default=TM});var d0=D(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});function l0(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}Bh.default=l0;l0.code='require("ajv/dist/runtime/ucs2length").default'});var p0=D(qh=>{"use strict";Object.defineProperty(qh,"__esModule",{value:!0});var cs=te(),PM=pe(),RM=d0(),CM={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,cs.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,cs._)`{limit: ${t}}`},OM={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:CM,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?cs.operators.GT:cs.operators.LT,i=s.opts.unicode===!1?(0,cs._)`${r}.length`:(0,cs._)`${(0,PM.useFunc)(t.gen,RM.default)}(${r})`;t.fail$data((0,cs._)`${i} ${o} ${n}`)}};qh.default=OM});var m0=D(Vh=>{"use strict";Object.defineProperty(Vh,"__esModule",{value:!0});var IM=Kt(),AM=pe(),io=te(),NM={message:({schemaCode:t})=>(0,io.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,io._)`{pattern: ${t}}`},DM={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:NM,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,io._)`new RegExp`:(0,AM.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,io._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,io._)`!${d}`)}else{let c=(0,IM.usePattern)(t,s);t.fail$data((0,io._)`!${c}.test(${r})`)}}};Vh.default=DM});var f0=D(Wh=>{"use strict";Object.defineProperty(Wh,"__esModule",{value:!0});var Ii=te(),MM={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ii.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ii._)`{limit: ${t}}`},jM={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:MM,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Ii.operators.GT:Ii.operators.LT;t.fail$data((0,Ii._)`Object.keys(${r}).length ${s} ${n}`)}};Wh.default=jM});var h0=D(Gh=>{"use strict";Object.defineProperty(Gh,"__esModule",{value:!0});var Ai=Kt(),Ni=te(),zM=pe(),LM={message:({params:{missingProperty:t}})=>(0,Ni.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ni._)`{missingProperty: ${t}}`},FM={keyword:"required",type:"object",schemaType:"array",$data:!0,error:LM,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:p}=t.it;for(let h of r)if(f?.[h]===void 0&&!p.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,zM.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(Ni.nil,l);else for(let f of r)(0,Ai.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(c||o){let p=e.let("valid",!0);t.block$data(p,()=>m(f,p)),t.ok(p)}else e.if((0,Ai.checkMissingProp)(t,r,f)),(0,Ai.reportMissingProp)(t,f),e.else()}function l(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Ai.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function m(f,p){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(p,(0,Ai.propertyInData)(e,s,f,a.ownProperties)),e.if((0,Ni.not)(p),()=>{t.error(),e.break()})},Ni.nil)}}};Gh.default=FM});var g0=D(Kh=>{"use strict";Object.defineProperty(Kh,"__esModule",{value:!0});var Di=te(),UM={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Di.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Di._)`{limit: ${t}}`},HM={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:UM,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Di.operators.GT:Di.operators.LT;t.fail$data((0,Di._)`${r}.length ${s} ${n}`)}};Kh.default=HM});var uu=D(Jh=>{"use strict";Object.defineProperty(Jh,"__esModule",{value:!0});var y0=vh();y0.code='require("ajv/dist/runtime/equal").default';Jh.default=y0});var _0=D(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});var Yh=bi(),et=te(),ZM=pe(),BM=uu(),qM={message:({params:{i:t,j:e}})=>(0,et.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,et._)`{i: ${t}, j: ${e}}`},VM={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:qM,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let c=e.let("valid"),u=o.items?(0,Yh.getSchemaTypes)(o.items):[];t.block$data(c,d,(0,et._)`${i} === false`),t.ok(c);function d(){let p=e.let("i",(0,et._)`${r}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,et._)`${p} > 1`,()=>(l()?m:f)(p,h))}function l(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function m(p,h){let g=e.name("item"),_=(0,Yh.checkDataTypes)(u,g,a.opts.strictNumbers,Yh.DataType.Wrong),x=e.const("indices",(0,et._)`{}`);e.for((0,et._)`;${p}--;`,()=>{e.let(g,(0,et._)`${r}[${p}]`),e.if(_,(0,et._)`continue`),u.length>1&&e.if((0,et._)`typeof ${g} == "string"`,(0,et._)`${g} += "_"`),e.if((0,et._)`typeof ${x}[${g}] == "number"`,()=>{e.assign(h,(0,et._)`${x}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,et._)`${x}[${g}] = ${p}`)})}function f(p,h){let g=(0,ZM.useFunc)(e,BM.default),_=e.name("outer");e.label(_).for((0,et._)`;${p}--;`,()=>e.for((0,et._)`${h} = ${p}; ${h}--;`,()=>e.if((0,et._)`${g}(${r}[${p}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};Xh.default=VM});var x0=D(eg=>{"use strict";Object.defineProperty(eg,"__esModule",{value:!0});var Qh=te(),WM=pe(),GM=uu(),KM={message:"must be equal to constant",params:({schemaCode:t})=>(0,Qh._)`{allowedValue: ${t}}`},JM={keyword:"const",$data:!0,error:KM,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Qh._)`!${(0,WM.useFunc)(e,GM.default)}(${r}, ${s})`):t.fail((0,Qh._)`${o} !== ${r}`)}};eg.default=JM});var v0=D(tg=>{"use strict";Object.defineProperty(tg,"__esModule",{value:!0});var Mi=te(),YM=pe(),XM=uu(),QM={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Mi._)`{allowedValues: ${t}}`},ej={keyword:"enum",schemaType:"array",$data:!0,error:QM,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,YM.useFunc)(e,XM.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let f=e.const("vSchema",o);d=(0,Mi.or)(...s.map((p,h)=>m(f,h)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",o,f=>e.if((0,Mi._)`${u()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function m(f,p){let h=s[p];return typeof h=="object"&&h!==null?(0,Mi._)`${u()}(${r}, ${f}[${p}])`:(0,Mi._)`${r} === ${h}`}}};tg.default=ej});var b0=D(rg=>{"use strict";Object.defineProperty(rg,"__esModule",{value:!0});var tj=c0(),rj=u0(),nj=p0(),sj=m0(),oj=f0(),ij=h0(),aj=g0(),cj=_0(),uj=x0(),lj=v0(),dj=[tj.default,rj.default,nj.default,sj.default,oj.default,ij.default,aj.default,cj.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},uj.default,lj.default];rg.default=dj});var sg=D(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.validateAdditionalItems=void 0;var us=te(),ng=pe(),pj={message:({params:{len:t}})=>(0,us.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,us._)`{limit: ${t}}`},mj={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:pj,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,ng.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}S0(t,n)}};function S0(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,us._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,us._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,ng.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,us._)`${a} <= ${e.length}`);r.if((0,us.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:ng.Type.Num},u),i.allErrors||r.if((0,us.not)(u),()=>r.break())})}}ji.validateAdditionalItems=S0;ji.default=mj});var og=D(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.validateTuple=void 0;var k0=te(),lu=pe(),fj=Kt(),hj={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return w0(t,"additionalItems",e);r.items=!0,!(0,lu.alwaysValidSchema)(r,e)&&t.ok((0,fj.validateArray)(t))}};function w0(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;d(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=lu.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,k0._)`${o}.length`);r.forEach((l,m)=>{(0,lu.alwaysValidSchema)(a,l)||(n.if((0,k0._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function d(l){let{opts:m,errSchemaPath:f}=a,p=r.length,h=p===l.minItems&&(p===l.maxItems||l[e]===!1);if(m.strictTuples&&!h){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,lu.checkStrictMode)(a,g,m.strictTuples)}}}zi.validateTuple=w0;zi.default=hj});var E0=D(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});var gj=og(),yj={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,gj.validateTuple)(t,"items")};ig.default=yj});var T0=D(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});var $0=te(),_j=pe(),xj=Kt(),vj=sg(),bj={message:({params:{len:t}})=>(0,$0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,$0._)`{limit: ${t}}`},Sj={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:bj,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,_j.alwaysValidSchema)(n,e)&&(s?(0,vj.validateAdditionalItems)(t,s):t.ok((0,xj.validateArray)(t)))}};ag.default=Sj});var P0=D(cg=>{"use strict";Object.defineProperty(cg,"__esModule",{value:!0});var Yt=te(),du=pe(),kj={message:({params:{min:t,max:e}})=>e===void 0?(0,Yt.str)`must contain at least ${t} valid item(s)`:(0,Yt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Yt._)`{minContains: ${t}}`:(0,Yt._)`{minContains: ${t}, maxContains: ${e}}`},wj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:kj,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:c,maxContains:u}=n;o.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,Yt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,du.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,du.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,du.alwaysValidSchema)(o,r)){let h=(0,Yt._)`${d} >= ${i}`;a!==void 0&&(h=(0,Yt._)`${h} && ${d} <= ${a}`),t.pass(h);return}o.items=!0;let l=e.name("valid");a===void 0&&i===1?f(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,Yt._)`${s}.length > 0`,m)):(e.let(l,!1),m()),t.result(l,()=>t.reset());function m(){let h=e.name("_valid"),g=e.let("count",0);f(h,()=>e.if(h,()=>p(g)))}function f(h,g){e.forRange("i",0,d,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:du.Type.Num,compositeRule:!0},h),g()})}function p(h){e.code((0,Yt._)`${h}++`),a===void 0?e.if((0,Yt._)`${h} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,Yt._)`${h} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,Yt._)`${h} >= ${i}`,()=>e.assign(l,!0)))}}};cg.default=wj});var O0=D($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.validateSchemaDeps=$r.validatePropertyDeps=$r.error=void 0;var ug=te(),Ej=pe(),Li=Kt();$r.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,ug.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,ug._)`{property: ${t},
|
|
69
69
|
missingProperty: ${n},
|
|
70
70
|
depsCount: ${e},
|
|
71
|
-
deps: ${r}}`};var gj={keyword:"dependencies",type:"object",schemaType:"object",error:Er.error,code(t){let[e,r]=yj(t);$0(t,e),T0(t,r)}};function yj({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function $0(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,zi.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of a)(0,zi.checkReportMissingProp)(t,u)}):(r.if((0,ig._)`${c} && (${(0,zi.checkMissingProp)(t,a,o)})`),(0,zi.reportMissingProp)(t,o),r.else())}}Er.validatePropertyDeps=$0;function T0(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,hj.alwaysValidSchema)(o,e[a])||(r.if((0,zi.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Er.validateSchemaDeps=T0;Er.default=gj});var C0=D(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});var R0=te(),_j=de(),xj={message:"property name must be valid",params:({params:t})=>(0,R0._)`{propertyName: ${t.propertyName}}`},vj={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:xj,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,_j.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,R0.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};ag.default=vj});var ug=D(cg=>{"use strict";Object.defineProperty(cg,"__esModule",{value:!0});var pu=Gt(),ur=te(),bj=Mr(),mu=de(),Sj={message:"must NOT have additional properties",params:({params:t})=>(0,ur._)`{additionalProperty: ${t.additionalProperty}}`},kj={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Sj,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,mu.alwaysValidSchema)(i,r))return;let u=(0,pu.allSchemaProperties)(n.properties),d=(0,pu.allSchemaProperties)(n.patternProperties);l(),t.ok((0,ur._)`${o} === ${bj.default.errors}`);function l(){e.forIn("key",s,g=>{!u.length&&!d.length?p(g):e.if(m(g),()=>p(g))})}function m(g){let y;if(u.length>8){let x=(0,mu.schemaRefOrVal)(i,n.properties,"properties");y=(0,pu.isOwnProperty)(e,x,g)}else u.length?y=(0,ur.or)(...u.map(x=>(0,ur._)`${g} === ${x}`)):y=ur.nil;return d.length&&(y=(0,ur.or)(y,...d.map(x=>(0,ur._)`${(0,pu.usePattern)(t,x)}.test(${g})`))),(0,ur.not)(y)}function f(g){e.code((0,ur._)`delete ${s}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,mu.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,ur.not)(y),()=>{t.reset(),f(g)})):(h(g,y),a||e.if((0,ur.not)(y),()=>e.break()))}}function h(g,y,x){let _={keyword:"additionalProperties",dataProp:g,dataPropType:mu.Type.Str};x===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,y)}}};cg.default=kj});var A0=D(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});var wj=wi(),O0=Gt(),lg=de(),I0=ug(),Ej={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&I0.default.code(new wj.KeywordCxt(o,I0.default,"additionalProperties"));let i=(0,O0.allSchemaProperties)(r);for(let l of i)o.definedProperties.add(l);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=lg.mergeEvaluated.props(e,(0,lg.toHash)(i),o.props));let a=i.filter(l=>!(0,lg.alwaysValidSchema)(o,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,O0.propertyInData)(e,s,l,o.opts.ownProperties)),d(l),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return o.opts.useDefaults&&!o.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};dg.default=Ej});var j0=D(pg=>{"use strict";Object.defineProperty(pg,"__esModule",{value:!0});var N0=Gt(),fu=te(),D0=de(),M0=de(),$j={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,N0.allSchemaProperties)(r),c=a.filter(h=>(0,D0.alwaysValidSchema)(o,r[h]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,d=e.name("valid");o.props!==!0&&!(o.props instanceof fu.Name)&&(o.props=(0,M0.evaluatedPropsToName)(e,o.props));let{props:l}=o;m();function m(){for(let h of a)u&&f(h),o.allErrors?p(h):(e.var(d,!0),p(h),e.if(d))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,D0.checkStrictMode)(o,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",n,g=>{e.if((0,fu._)`${(0,N0.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:M0.Type.Str},d),o.opts.unevaluated&&l!==!0?e.assign((0,fu._)`${l}[${g}]`,!0):!y&&!o.allErrors&&e.if((0,fu.not)(d),()=>e.break())})})}}};pg.default=$j});var z0=D(mg=>{"use strict";Object.defineProperty(mg,"__esModule",{value:!0});var Tj=de(),Pj={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Tj.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};mg.default=Pj});var L0=D(fg=>{"use strict";Object.defineProperty(fg,"__esModule",{value:!0});var Rj=Gt(),Cj={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Rj.validateUnion,error:{message:"must match a schema in anyOf"}};fg.default=Cj});var F0=D(hg=>{"use strict";Object.defineProperty(hg,"__esModule",{value:!0});var hu=te(),Oj=de(),Ij={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,hu._)`{passingSchemas: ${t.passing}}`},Aj={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Ij,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=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(){o.forEach((d,l)=>{let m;(0,Oj.alwaysValidSchema)(s,d)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,hu._)`${c} && ${i}`).assign(i,!1).assign(a,(0,hu._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),m&&t.mergeEvaluated(m,hu.Name)})})}}};hg.default=Aj});var U0=D(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var Nj=de(),Dj={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 s=e.name("valid");r.forEach((o,i)=>{if((0,Nj.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};gg.default=Dj});var B0=D(yg=>{"use strict";Object.defineProperty(yg,"__esModule",{value:!0});var gu=te(),Z0=de(),Mj={message:({params:t})=>(0,gu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,gu._)`{failingKeyword: ${t.ifClause}}`},jj={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Mj,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Z0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=H0(n,"then"),o=H0(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),s&&o){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,u("then",d),u("else",d))}else s?e.if(a,u("then")):e.if((0,gu.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let m=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(m,i),l?e.assign(l,(0,gu._)`${d}`):t.setParams({ifClause:d})}}}};function H0(t,e){let r=t.schema[e];return r!==void 0&&!(0,Z0.alwaysValidSchema)(t,r)}yg.default=jj});var q0=D(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});var zj=de(),Lj={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,zj.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};_g.default=Lj});var V0=D(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var Fj=tg(),Uj=S0(),Hj=rg(),Zj=w0(),Bj=E0(),qj=P0(),Vj=C0(),Wj=ug(),Gj=A0(),Kj=j0(),Jj=z0(),Yj=L0(),Xj=F0(),Qj=U0(),ez=B0(),tz=q0();function rz(t=!1){let e=[Jj.default,Yj.default,Xj.default,Qj.default,ez.default,tz.default,Vj.default,Wj.default,qj.default,Gj.default,Kj.default];return t?e.push(Uj.default,Zj.default):e.push(Fj.default,Hj.default),e.push(Bj.default),e}xg.default=rz});var W0=D(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});var Ue=te(),nz={message:({schemaCode:t})=>(0,Ue.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ue._)`{format: ${t}}`},sz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:nz,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;s?m():f();function m(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),h=r.const("fDef",(0,Ue._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Ue._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,Ue._)`${h}.type || "string"`).assign(y,(0,Ue._)`${h}.validate`),()=>r.assign(g,(0,Ue._)`"string"`).assign(y,h)),t.fail$data((0,Ue.or)(x(),_()));function x(){return c.strictSchema===!1?Ue.nil:(0,Ue._)`${i} && !${y}`}function _(){let b=d.$async?(0,Ue._)`(${h}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Ue._)`${y}(${n})`,w=(0,Ue._)`(typeof ${y} == "function" ? ${b} : ${y}.test(${n}))`;return(0,Ue._)`${y} && ${y} !== true && ${g} === ${e} && !${w}`}}function f(){let p=l.formats[o];if(!p){x();return}if(p===!0)return;let[h,g,y]=_(p);h===e&&t.pass(b());function x(){if(c.strictSchema===!1){l.logger.warn(w());return}throw new Error(w());function w(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function _(w){let I=w instanceof RegExp?(0,Ue.regexpCode)(w):c.code.formats?(0,Ue._)`${c.code.formats}${(0,Ue.getProperty)(o)}`:void 0,C=r.scopeValue("formats",{key:o,ref:w,code:I});return typeof w=="object"&&!(w instanceof RegExp)?[w.type||"string",w.validate,(0,Ue._)`${C}.validate`]:["string",w,C]}function b(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Ue._)`await ${y}(${n})`}return typeof g=="function"?(0,Ue._)`${y}(${n})`:(0,Ue._)`${y}.test(${n})`}}}};vg.default=sz});var G0=D(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});var oz=W0(),iz=[oz.default];bg.default=iz});var K0=D(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.contentVocabulary=oo.metadataVocabulary=void 0;oo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];oo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Y0=D(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});var az=s0(),cz=_0(),uz=V0(),lz=G0(),J0=K0(),dz=[az.default,cz.default,(0,uz.default)(),lz.default,J0.metadataVocabulary,J0.contentVocabulary];Sg.default=dz});var Q0=D(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});yu.DiscrError=void 0;var X0;(function(t){t.Tag="tag",t.Mapping="mapping"})(X0||(yu.DiscrError=X0={}))});var tw=D(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});var io=te(),kg=Q0(),ew=Qc(),pz=Ei(),mz=de(),fz={message:({params:{discrError:t,tagName:e}})=>t===kg.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,io._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},hz={keyword:"discriminator",type:"object",schemaType:"object",error:fz,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.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,io._)`${r}${(0,io.getProperty)(a)}`);e.if((0,io._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:kg.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let f=m();e.if(!1);for(let p in f)e.elseIf((0,io._)`${u} === ${p}`),e.assign(c,l(f[p]));e.else(),t.error(!1,{discrError:kg.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(f){let p=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},p);return t.mergeEvaluated(h,io.Name),p}function m(){var f;let p={},h=y(s),g=!0;for(let b=0;b<i.length;b++){let w=i[b];if(w?.$ref&&!(0,mz.schemaHasRulesButRef)(w,o.self.RULES)){let C=w.$ref;if(w=ew.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,C),w instanceof ew.SchemaEnv&&(w=w.schema),w===void 0)throw new pz.default(o.opts.uriResolver,o.baseId,C)}let I=(f=w?.properties)===null||f===void 0?void 0:f[a];if(typeof I!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(w)),x(I,b)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:b}){return Array.isArray(b)&&b.includes(a)}function x(b,w){if(b.const)_(b.const,w);else if(b.enum)for(let I of b.enum)_(I,w);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(b,w){if(typeof b!="string"||b in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[b]=w}}}};wg.default=hz});var rw=D((FV,gz)=>{gz.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 $g=D((Re,Eg)=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.MissingRefError=Re.ValidationError=Re.CodeGen=Re.Name=Re.nil=Re.stringify=Re.str=Re._=Re.KeywordCxt=Re.Ajv=void 0;var yz=Xk(),_z=Y0(),xz=tw(),nw=rw(),vz=["/properties"],_u="http://json-schema.org/draft-07/schema",ao=class extends yz.default{_addVocabularies(){super._addVocabularies(),_z.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(xz.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(nw,vz):nw;this.addMetaSchema(e,_u,!1),this.refs["http://json-schema.org/schema"]=_u}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_u)?_u:void 0)}};Re.Ajv=ao;Eg.exports=Re=ao;Eg.exports.Ajv=ao;Object.defineProperty(Re,"__esModule",{value:!0});Re.default=ao;var bz=wi();Object.defineProperty(Re,"KeywordCxt",{enumerable:!0,get:function(){return bz.KeywordCxt}});var co=te();Object.defineProperty(Re,"_",{enumerable:!0,get:function(){return co._}});Object.defineProperty(Re,"str",{enumerable:!0,get:function(){return co.str}});Object.defineProperty(Re,"stringify",{enumerable:!0,get:function(){return co.stringify}});Object.defineProperty(Re,"nil",{enumerable:!0,get:function(){return co.nil}});Object.defineProperty(Re,"Name",{enumerable:!0,get:function(){return co.Name}});Object.defineProperty(Re,"CodeGen",{enumerable:!0,get:function(){return co.CodeGen}});var Sz=Yc();Object.defineProperty(Re,"ValidationError",{enumerable:!0,get:function(){return Sz.default}});var kz=Ei();Object.defineProperty(Re,"MissingRefError",{enumerable:!0,get:function(){return kz.default}})});var dw=D(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.formatNames=Tr.fastFormats=Tr.fullFormats=void 0;function $r(t,e){return{validate:t,compare:e}}Tr.fullFormats={date:$r(aw,Cg),time:$r(Pg(!0),Og),"date-time":$r(sw(!0),uw),"iso-time":$r(Pg(),cw),"iso-date-time":$r(sw(),lw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Rz,"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:Mz,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:Cz,int32:{type:"number",validate:Az},int64:{type:"number",validate:Nz},float:{type:"number",validate:iw},double:{type:"number",validate:iw},password:!0,binary:!0};Tr.fastFormats={...Tr.fullFormats,date:$r(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Cg),time:$r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Og),"date-time":$r(/^\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,uw),"iso-time":$r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,cw),"iso-date-time":$r(/^\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,lw),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};Tr.formatNames=Object.keys(Tr.fullFormats);function wz(t){return t%4===0&&(t%100!==0||t%400===0)}var Ez=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,$z=[0,31,28,31,30,31,30,31,31,30,31,30,31];function aw(t){let e=Ez.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&wz(r)?29:$z[n])}function Cg(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Tg=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Pg(t){return function(r){let n=Tg.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let l=o-d*c,m=s-u*c-(l<0?1:0);return(m===23||m===-1)&&(l===59||l===-1)&&i<61}}function Og(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 cw(t,e){if(!(t&&e))return;let r=Tg.exec(t),n=Tg.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 Rg=/t|\s/i;function sw(t){let e=Pg(t);return function(n){let s=n.split(Rg);return s.length===2&&aw(s[0])&&e(s[1])}}function uw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function lw(t,e){if(!(t&&e))return;let[r,n]=t.split(Rg),[s,o]=e.split(Rg),i=Cg(r,s);if(i!==void 0)return i||Og(n,o)}var Tz=/\/|:/,Pz=/^(?:[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 Rz(t){return Tz.test(t)&&Pz.test(t)}var ow=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Cz(t){return ow.lastIndex=0,ow.test(t)}var Oz=-(2**31),Iz=2**31-1;function Az(t){return Number.isInteger(t)&&t<=Iz&&t>=Oz}function Nz(t){return Number.isInteger(t)}function iw(){return!0}var Dz=/[^\\]\\Z/;function Mz(t){if(Dz.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var pw=D(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.formatLimitDefinition=void 0;var jz=$g(),lr=te(),yn=lr.operators,xu={formatMaximum:{okStr:"<=",ok:yn.LTE,fail:yn.GT},formatMinimum:{okStr:">=",ok:yn.GTE,fail:yn.LT},formatExclusiveMaximum:{okStr:"<",ok:yn.LT,fail:yn.GTE},formatExclusiveMinimum:{okStr:">",ok:yn.GT,fail:yn.LTE}},zz={message:({keyword:t,schemaCode:e})=>(0,lr.str)`should be ${xu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,lr._)`{comparison: ${xu[t].okStr}, limit: ${e}}`};uo.formatLimitDefinition={keyword:Object.keys(xu),type:"string",schemaType:"string",$data:!0,error:zz,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let c=new jz.KeywordCxt(o,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,lr._)`${m}[${c.schemaCode}]`);t.fail$data((0,lr.or)((0,lr._)`typeof ${f} != "object"`,(0,lr._)`${f} instanceof RegExp`,(0,lr._)`typeof ${f}.compare != "function"`,l(f)))}function d(){let m=c.schema,f=a.formats[m];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${s}": format "${m}" does not define "compare" function`);let p=e.scopeValue("formats",{key:m,ref:f,code:i.code.formats?(0,lr._)`${i.code.formats}${(0,lr.getProperty)(m)}`:void 0});t.fail$data(l(p))}function l(m){return(0,lr._)`${m}.compare(${r}, ${n}) ${xu[s].fail} 0`}},dependencies:["format"]};var Lz=t=>(t.addKeyword(uo.formatLimitDefinition),t);uo.default=Lz});var gw=D((Li,hw)=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});var lo=dw(),Fz=pw(),Ig=te(),mw=new Ig.Name("fullFormats"),Uz=new Ig.Name("fastFormats"),Ag=(t,e={keywords:!0})=>{if(Array.isArray(e))return fw(t,e,lo.fullFormats,mw),t;let[r,n]=e.mode==="fast"?[lo.fastFormats,Uz]:[lo.fullFormats,mw],s=e.formats||lo.formatNames;return fw(t,s,r,n),e.keywords&&(0,Fz.default)(t),t};Ag.get=(t,e="full")=>{let n=(e==="fast"?lo.fastFormats:lo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function fw(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Ig._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}hw.exports=Li=Ag;Object.defineProperty(Li,"__esModule",{value:!0});Li.default=Ag});function Hz(){let t=new yw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,_w.default)(t),t}var yw,_w,vu,xw=v(()=>{yw=Eo($g(),1),_w=Eo(gw(),1);vu=class{constructor(e){this._ajv=e??Hz()}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 bu,vw=v(()=>{Xn();bu=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 s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(d=>d.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(d=>d.type==="tool_use");if(i){if(o.some(d=>d.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 d=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(o.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(d.size!==l.size||![...d].every(m=>l.has(m)))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},ui,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){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 o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Ws,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 bw(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 Sw(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 kw=v(()=>{});var Su,ww=v(()=>{OS();Xn();xw();Yo();vw();kw();Su=class extends zc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ci.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new vu,this.setRequestHandler(Wm,n=>this._oninitialize(n)),this.setNotificationHandler(Gm,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(tf,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ci.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new bu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=CS(this._capabilities,e)}setRequestHandler(e,r){let s=on(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(Zt(s)){let a=s;o=a._zod?.def?.value??a.value}else{let a=s;o=a._def?.value??a.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(c,u)=>{let d=sn(Vs,c);if(!d.success){let p=d.error instanceof Error?d.error.message:String(d.error);throw new F(q.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=d.data,m=await Promise.resolve(r(c,u));if(l.task){let p=sn(Us,m);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new F(q.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let f=sn($c,m);if(!f.success){let p=f.error instanceof Error?f.error.message:String(f.error);throw new F(q.InvalidParams,`Invalid tools/call result: ${p}`)}return f.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){Sw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&bw(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:Cb.includes(r)?r:Hm,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"},mc)}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],s=Array.isArray(n.content)?n.content:[n.content],o=s.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(o){if(s.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(l=>l.type==="tool_use").map(l=>l.id)),d=new Set(s.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(u.size!==d.size||![...u].every(l=>d.has(l)))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},rf,r):this.request({method:"sampling/createMessage",params:e},ui,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 s=e;return this.request({method:"elicitation/create",params:s},Ws,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},Ws,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new F(q.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof F?i:new F(q.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}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},nf,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 Ng(t){return!!t&&typeof t=="object"&&$w in t}function Tw(t){return t[$w]?.complete}var $w,Ew,Pw=v(()=>{$w=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Ew||(Ew={}))});var Rw=v(()=>{});function Bz(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"),!Zz.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);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 qz(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 Dg(t){let e=Bz(t);return qz(t,e.warnings),e.isValid}var Zz,Cw=v(()=>{Zz=/^[A-Za-z0-9._-]{1,128}$/});var ku,Ow=v(()=>{ku=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let s={taskSupport:"required",...r.execution};if(s.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,s,r._meta,n)}}});var Mg=v(()=>{ja();ja()});function Nw(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Dw(t){return"_def"in t||"_zod"in t||Nw(t)}function jg(t){return typeof t!="object"||t===null||Dw(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Nw)}function Iw(t){if(t){if(jg(t))return Yn(t);if(!Dw(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function Wz(t){let e=on(t);return e?Object.entries(e).map(([r,n])=>{let s=tb(n),o=rb(n);return{name:r,description:s,required:!o}}):[]}function _n(t){let r=on(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ac(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Aw(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var wu,Vz,Fi,Mw=v(()=>{ww();Yo();Uf();Xn();Pw();Rw();Cw();Ow();Mg();wu=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 Su(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ku(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(_n(Ec)),this.server.assertCanSetRequestHandler(_n(Vs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ec,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let s=Ls(r.inputSchema);return s?zf(s,{strictUnions:!0,pipeStrategy:"input"}):Vz})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=Ls(r.outputSchema);s&&(n.outputSchema=zf(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Vs,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new F(q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new F(q.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=n.execution?.taskSupport,i="createTask"in n.handler;if((o==="required"||o==="optional")&&!i)throw new F(q.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new F(q.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&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 s||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof F&&n.code===q.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 o=Ls(e.inputSchema)??e.inputSchema,i=await oc(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=ic(a);throw new F(q.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 F(q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=Ls(e.outputSchema),o=await oc(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=ic(i);throw new F(q.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(r,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(r,n))}else{let i=s;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 s=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,i={...n,taskStore:n.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),c=a.task.taskId,u=a.task,d=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(m=>setTimeout(m,d));let l=await n.taskStore.getTask(c);if(!l)throw new F(q.InternalError,`Task ${c} not found during polling`);u=l}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(_n(Tc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Tc,async e=>{switch(e.params.ref.type){case"ref/prompt":return Vb(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Wb(e),this.handleResourceCompletion(e,e.params.ref);default:throw new F(q.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new F(q.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new F(q.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Fi;let o=on(n.argsSchema)?.[e.params.argument.name];if(!Ng(o))return Fi;let i=Tw(o);if(!i)return Fi;let a=await i(e.params.argument.value,e.params.context);return Aw(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 Fi;throw new F(q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return Fi;let o=await s(e.params.argument.value,e.params.context);return Aw(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(_n(Zs)),this.server.assertCanSetRequestHandler(_n(Bs)),this.server.assertCanSetRequestHandler(_n(kc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Zs,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(r);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...n,...s]}}),this.server.setRequestHandler(Bs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(kc,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new F(q.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(n.toString());if(i)return o.readCallback(n,i,r)}throw new F(q.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(_n(qs)),this.server.assertCanSetRequestHandler(_n(wc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(qs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?Wz(r.argsSchema):void 0}))})),this.server.setRequestHandler(wc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new F(q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new F(q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=Ls(n.argsSchema),o=await oc(s,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=ic(c);throw new F(q.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=o.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());let o=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,s,o);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,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){let i={name:e,title:r,metadata:s,readCallback:o,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,s,o){let i={resourceTemplate:n,title:r,metadata:s,readCallback:o,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,s,o){let i={title:r,description:n,argsSchema:s===void 0?void 0:Yn(s),callback:o,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=Yn(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,s&&Object.values(s).some(c=>{let u=c instanceof vt?c._def?.innerType:c;return Ng(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,c,u){Dg(e);let d={title:r,description:n,inputSchema:Iw(s),outputSchema:Iw(o),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(typeof l.name=="string"&&Dg(l.name),delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=d)),typeof l.title<"u"&&(d.title=l.title),typeof l.description<"u"&&(d.description=l.description),typeof l.paramsSchema<"u"&&(d.inputSchema=Yn(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=Yn(l.outputSchema)),typeof l.callback<"u"&&(d.handler=l.callback),typeof l.annotations<"u"&&(d.annotations=l.annotations),typeof l._meta<"u"&&(d._meta=l._meta),typeof l.enabled<"u"&&(d.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(jg(c))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!jg(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,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,s,o,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 s;r.length>1&&(s=r.shift());let o=r[0],i=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=r,a=this._createRegisteredPrompt(e,s,o,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()}},Vz={type:"object",properties:{}};Fi={completion:{values:[],hasMore:!1}}});function Gz(t){return zb.parse(JSON.parse(t))}function jw(t){return JSON.stringify(t)+`
|
|
72
|
-
`}var Eu,
|
|
73
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
74
|
-
${t}`}function
|
|
71
|
+
deps: ${r}}`};var $j={keyword:"dependencies",type:"object",schemaType:"object",error:$r.error,code(t){let[e,r]=Tj(t);R0(t,e),C0(t,r)}};function Tj({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function R0(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Li.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of a)(0,Li.checkReportMissingProp)(t,u)}):(r.if((0,ug._)`${c} && (${(0,Li.checkMissingProp)(t,a,o)})`),(0,Li.reportMissingProp)(t,o),r.else())}}$r.validatePropertyDeps=R0;function C0(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,Ej.alwaysValidSchema)(o,e[a])||(r.if((0,Li.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}$r.validateSchemaDeps=C0;$r.default=$j});var A0=D(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});var I0=te(),Pj=pe(),Rj={message:"property name must be valid",params:({params:t})=>(0,I0._)`{propertyName: ${t.propertyName}}`},Cj={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Rj,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,Pj.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,I0.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};lg.default=Cj});var pg=D(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});var pu=Kt(),dr=te(),Oj=jr(),mu=pe(),Ij={message:"must NOT have additional properties",params:({params:t})=>(0,dr._)`{additionalProperty: ${t.additionalProperty}}`},Aj={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Ij,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,mu.alwaysValidSchema)(i,r))return;let u=(0,pu.allSchemaProperties)(n.properties),d=(0,pu.allSchemaProperties)(n.patternProperties);l(),t.ok((0,dr._)`${o} === ${Oj.default.errors}`);function l(){e.forIn("key",s,g=>{!u.length&&!d.length?p(g):e.if(m(g),()=>p(g))})}function m(g){let _;if(u.length>8){let x=(0,mu.schemaRefOrVal)(i,n.properties,"properties");_=(0,pu.isOwnProperty)(e,x,g)}else u.length?_=(0,dr.or)(...u.map(x=>(0,dr._)`${g} === ${x}`)):_=dr.nil;return d.length&&(_=(0,dr.or)(_,...d.map(x=>(0,dr._)`${(0,pu.usePattern)(t,x)}.test(${g})`))),(0,dr.not)(_)}function f(g){e.code((0,dr._)`delete ${s}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,mu.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(h(g,_,!1),e.if((0,dr.not)(_),()=>{t.reset(),f(g)})):(h(g,_),a||e.if((0,dr.not)(_),()=>e.break()))}}function h(g,_,x){let y={keyword:"additionalProperties",dataProp:g,dataPropType:mu.Type.Str};x===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};dg.default=Aj});var M0=D(fg=>{"use strict";Object.defineProperty(fg,"__esModule",{value:!0});var Nj=Ei(),N0=Kt(),mg=pe(),D0=pg(),Dj={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&D0.default.code(new Nj.KeywordCxt(o,D0.default,"additionalProperties"));let i=(0,N0.allSchemaProperties)(r);for(let l of i)o.definedProperties.add(l);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=mg.mergeEvaluated.props(e,(0,mg.toHash)(i),o.props));let a=i.filter(l=>!(0,mg.alwaysValidSchema)(o,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,N0.propertyInData)(e,s,l,o.opts.ownProperties)),d(l),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return o.opts.useDefaults&&!o.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};fg.default=Dj});var F0=D(hg=>{"use strict";Object.defineProperty(hg,"__esModule",{value:!0});var j0=Kt(),fu=te(),z0=pe(),L0=pe(),Mj={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,j0.allSchemaProperties)(r),c=a.filter(h=>(0,z0.alwaysValidSchema)(o,r[h]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,d=e.name("valid");o.props!==!0&&!(o.props instanceof fu.Name)&&(o.props=(0,L0.evaluatedPropsToName)(e,o.props));let{props:l}=o;m();function m(){for(let h of a)u&&f(h),o.allErrors?p(h):(e.var(d,!0),p(h),e.if(d))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,z0.checkStrictMode)(o,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",n,g=>{e.if((0,fu._)`${(0,j0.usePattern)(t,h)}.test(${g})`,()=>{let _=c.includes(h);_||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:L0.Type.Str},d),o.opts.unevaluated&&l!==!0?e.assign((0,fu._)`${l}[${g}]`,!0):!_&&!o.allErrors&&e.if((0,fu.not)(d),()=>e.break())})})}}};hg.default=Mj});var U0=D(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var jj=pe(),zj={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,jj.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};gg.default=zj});var H0=D(yg=>{"use strict";Object.defineProperty(yg,"__esModule",{value:!0});var Lj=Kt(),Fj={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Lj.validateUnion,error:{message:"must match a schema in anyOf"}};yg.default=Fj});var Z0=D(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});var hu=te(),Uj=pe(),Hj={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,hu._)`{passingSchemas: ${t.passing}}`},Zj={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Hj,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=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(){o.forEach((d,l)=>{let m;(0,Uj.alwaysValidSchema)(s,d)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,hu._)`${c} && ${i}`).assign(i,!1).assign(a,(0,hu._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),m&&t.mergeEvaluated(m,hu.Name)})})}}};_g.default=Zj});var B0=D(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var Bj=pe(),qj={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 s=e.name("valid");r.forEach((o,i)=>{if((0,Bj.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};xg.default=qj});var W0=D(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});var gu=te(),V0=pe(),Vj={message:({params:t})=>(0,gu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,gu._)`{failingKeyword: ${t.ifClause}}`},Wj={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Vj,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,V0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=q0(n,"then"),o=q0(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),s&&o){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,u("then",d),u("else",d))}else s?e.if(a,u("then")):e.if((0,gu.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let m=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(m,i),l?e.assign(l,(0,gu._)`${d}`):t.setParams({ifClause:d})}}}};function q0(t,e){let r=t.schema[e];return r!==void 0&&!(0,V0.alwaysValidSchema)(t,r)}vg.default=Wj});var G0=D(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});var Gj=pe(),Kj={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Gj.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};bg.default=Kj});var K0=D(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});var Jj=sg(),Yj=E0(),Xj=og(),Qj=T0(),ez=P0(),tz=O0(),rz=A0(),nz=pg(),sz=M0(),oz=F0(),iz=U0(),az=H0(),cz=Z0(),uz=B0(),lz=W0(),dz=G0();function pz(t=!1){let e=[iz.default,az.default,cz.default,uz.default,lz.default,dz.default,rz.default,nz.default,tz.default,sz.default,oz.default];return t?e.push(Yj.default,Qj.default):e.push(Jj.default,Xj.default),e.push(ez.default),e}Sg.default=pz});var J0=D(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});var He=te(),mz={message:({schemaCode:t})=>(0,He.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,He._)`{format: ${t}}`},fz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:mz,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;s?m():f();function m(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),h=r.const("fDef",(0,He._)`${p}[${i}]`),g=r.let("fType"),_=r.let("format");r.if((0,He._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,He._)`${h}.type || "string"`).assign(_,(0,He._)`${h}.validate`),()=>r.assign(g,(0,He._)`"string"`).assign(_,h)),t.fail$data((0,He.or)(x(),y()));function x(){return c.strictSchema===!1?He.nil:(0,He._)`${i} && !${_}`}function y(){let b=d.$async?(0,He._)`(${h}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,He._)`${_}(${n})`,w=(0,He._)`(typeof ${_} == "function" ? ${b} : ${_}.test(${n}))`;return(0,He._)`${_} && ${_} !== true && ${g} === ${e} && !${w}`}}function f(){let p=l.formats[o];if(!p){x();return}if(p===!0)return;let[h,g,_]=y(p);h===e&&t.pass(b());function x(){if(c.strictSchema===!1){l.logger.warn(w());return}throw new Error(w());function w(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function y(w){let O=w instanceof RegExp?(0,He.regexpCode)(w):c.code.formats?(0,He._)`${c.code.formats}${(0,He.getProperty)(o)}`:void 0,C=r.scopeValue("formats",{key:o,ref:w,code:O});return typeof w=="object"&&!(w instanceof RegExp)?[w.type||"string",w.validate,(0,He._)`${C}.validate`]:["string",w,C]}function b(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,He._)`await ${_}(${n})`}return typeof g=="function"?(0,He._)`${_}(${n})`:(0,He._)`${_}.test(${n})`}}}};kg.default=fz});var Y0=D(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});var hz=J0(),gz=[hz.default];wg.default=gz});var X0=D(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.contentVocabulary=ao.metadataVocabulary=void 0;ao.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ao.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ew=D(Eg=>{"use strict";Object.defineProperty(Eg,"__esModule",{value:!0});var yz=a0(),_z=b0(),xz=K0(),vz=Y0(),Q0=X0(),bz=[yz.default,_z.default,(0,xz.default)(),vz.default,Q0.metadataVocabulary,Q0.contentVocabulary];Eg.default=bz});var rw=D(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});yu.DiscrError=void 0;var tw;(function(t){t.Tag="tag",t.Mapping="mapping"})(tw||(yu.DiscrError=tw={}))});var sw=D(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});var co=te(),$g=rw(),nw=Qc(),Sz=$i(),kz=pe(),wz={message:({params:{discrError:t,tagName:e}})=>t===$g.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,co._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Ez={keyword:"discriminator",type:"object",schemaType:"object",error:wz,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.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,co._)`${r}${(0,co.getProperty)(a)}`);e.if((0,co._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:$g.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let f=m();e.if(!1);for(let p in f)e.elseIf((0,co._)`${u} === ${p}`),e.assign(c,l(f[p]));e.else(),t.error(!1,{discrError:$g.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(f){let p=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},p);return t.mergeEvaluated(h,co.Name),p}function m(){var f;let p={},h=_(s),g=!0;for(let b=0;b<i.length;b++){let w=i[b];if(w?.$ref&&!(0,kz.schemaHasRulesButRef)(w,o.self.RULES)){let C=w.$ref;if(w=nw.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,C),w instanceof nw.SchemaEnv&&(w=w.schema),w===void 0)throw new Sz.default(o.opts.uriResolver,o.baseId,C)}let O=(f=w?.properties)===null||f===void 0?void 0:f[a];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||_(w)),x(O,b)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function _({required:b}){return Array.isArray(b)&&b.includes(a)}function x(b,w){if(b.const)y(b.const,w);else if(b.enum)for(let O of b.enum)y(O,w);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function y(b,w){if(typeof b!="string"||b in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[b]=w}}}};Tg.default=Ez});var ow=D((e6,$z)=>{$z.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 Rg=D((Re,Pg)=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.MissingRefError=Re.ValidationError=Re.CodeGen=Re.Name=Re.nil=Re.stringify=Re.str=Re._=Re.KeywordCxt=Re.Ajv=void 0;var Tz=t0(),Pz=ew(),Rz=sw(),iw=ow(),Cz=["/properties"],_u="http://json-schema.org/draft-07/schema",uo=class extends Tz.default{_addVocabularies(){super._addVocabularies(),Pz.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Rz.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(iw,Cz):iw;this.addMetaSchema(e,_u,!1),this.refs["http://json-schema.org/schema"]=_u}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_u)?_u:void 0)}};Re.Ajv=uo;Pg.exports=Re=uo;Pg.exports.Ajv=uo;Object.defineProperty(Re,"__esModule",{value:!0});Re.default=uo;var Oz=Ei();Object.defineProperty(Re,"KeywordCxt",{enumerable:!0,get:function(){return Oz.KeywordCxt}});var lo=te();Object.defineProperty(Re,"_",{enumerable:!0,get:function(){return lo._}});Object.defineProperty(Re,"str",{enumerable:!0,get:function(){return lo.str}});Object.defineProperty(Re,"stringify",{enumerable:!0,get:function(){return lo.stringify}});Object.defineProperty(Re,"nil",{enumerable:!0,get:function(){return lo.nil}});Object.defineProperty(Re,"Name",{enumerable:!0,get:function(){return lo.Name}});Object.defineProperty(Re,"CodeGen",{enumerable:!0,get:function(){return lo.CodeGen}});var Iz=Yc();Object.defineProperty(Re,"ValidationError",{enumerable:!0,get:function(){return Iz.default}});var Az=$i();Object.defineProperty(Re,"MissingRefError",{enumerable:!0,get:function(){return Az.default}})});var fw=D(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.formatNames=Pr.fastFormats=Pr.fullFormats=void 0;function Tr(t,e){return{validate:t,compare:e}}Pr.fullFormats={date:Tr(lw,Ag),time:Tr(Og(!0),Ng),"date-time":Tr(aw(!0),pw),"iso-time":Tr(Og(),dw),"iso-date-time":Tr(aw(),mw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Lz,"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:Vz,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:Fz,int32:{type:"number",validate:Zz},int64:{type:"number",validate:Bz},float:{type:"number",validate:uw},double:{type:"number",validate:uw},password:!0,binary:!0};Pr.fastFormats={...Pr.fullFormats,date:Tr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Ag),time:Tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ng),"date-time":Tr(/^\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,pw),"iso-time":Tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,dw),"iso-date-time":Tr(/^\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,mw),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};Pr.formatNames=Object.keys(Pr.fullFormats);function Nz(t){return t%4===0&&(t%100!==0||t%400===0)}var Dz=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Mz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function lw(t){let e=Dz.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&Nz(r)?29:Mz[n])}function Ag(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Cg=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Og(t){return function(r){let n=Cg.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let l=o-d*c,m=s-u*c-(l<0?1:0);return(m===23||m===-1)&&(l===59||l===-1)&&i<61}}function Ng(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 dw(t,e){if(!(t&&e))return;let r=Cg.exec(t),n=Cg.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 Ig=/t|\s/i;function aw(t){let e=Og(t);return function(n){let s=n.split(Ig);return s.length===2&&lw(s[0])&&e(s[1])}}function pw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function mw(t,e){if(!(t&&e))return;let[r,n]=t.split(Ig),[s,o]=e.split(Ig),i=Ag(r,s);if(i!==void 0)return i||Ng(n,o)}var jz=/\/|:/,zz=/^(?:[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 Lz(t){return jz.test(t)&&zz.test(t)}var cw=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Fz(t){return cw.lastIndex=0,cw.test(t)}var Uz=-(2**31),Hz=2**31-1;function Zz(t){return Number.isInteger(t)&&t<=Hz&&t>=Uz}function Bz(t){return Number.isInteger(t)}function uw(){return!0}var qz=/[^\\]\\Z/;function Vz(t){if(qz.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var hw=D(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.formatLimitDefinition=void 0;var Wz=Rg(),pr=te(),_n=pr.operators,xu={formatMaximum:{okStr:"<=",ok:_n.LTE,fail:_n.GT},formatMinimum:{okStr:">=",ok:_n.GTE,fail:_n.LT},formatExclusiveMaximum:{okStr:"<",ok:_n.LT,fail:_n.GTE},formatExclusiveMinimum:{okStr:">",ok:_n.GT,fail:_n.LTE}},Gz={message:({keyword:t,schemaCode:e})=>(0,pr.str)`should be ${xu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,pr._)`{comparison: ${xu[t].okStr}, limit: ${e}}`};po.formatLimitDefinition={keyword:Object.keys(xu),type:"string",schemaType:"string",$data:!0,error:Gz,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let c=new Wz.KeywordCxt(o,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,pr._)`${m}[${c.schemaCode}]`);t.fail$data((0,pr.or)((0,pr._)`typeof ${f} != "object"`,(0,pr._)`${f} instanceof RegExp`,(0,pr._)`typeof ${f}.compare != "function"`,l(f)))}function d(){let m=c.schema,f=a.formats[m];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${s}": format "${m}" does not define "compare" function`);let p=e.scopeValue("formats",{key:m,ref:f,code:i.code.formats?(0,pr._)`${i.code.formats}${(0,pr.getProperty)(m)}`:void 0});t.fail$data(l(p))}function l(m){return(0,pr._)`${m}.compare(${r}, ${n}) ${xu[s].fail} 0`}},dependencies:["format"]};var Kz=t=>(t.addKeyword(po.formatLimitDefinition),t);po.default=Kz});var xw=D((Fi,_w)=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});var mo=fw(),Jz=hw(),Dg=te(),gw=new Dg.Name("fullFormats"),Yz=new Dg.Name("fastFormats"),Mg=(t,e={keywords:!0})=>{if(Array.isArray(e))return yw(t,e,mo.fullFormats,gw),t;let[r,n]=e.mode==="fast"?[mo.fastFormats,Yz]:[mo.fullFormats,gw],s=e.formats||mo.formatNames;return yw(t,s,r,n),e.keywords&&(0,Jz.default)(t),t};Mg.get=(t,e="full")=>{let n=(e==="fast"?mo.fastFormats:mo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function yw(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Dg._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}_w.exports=Fi=Mg;Object.defineProperty(Fi,"__esModule",{value:!0});Fi.default=Mg});function Xz(){let t=new vw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,bw.default)(t),t}var vw,bw,vu,Sw=v(()=>{vw=$o(Rg(),1),bw=$o(xw(),1);vu=class{constructor(e){this._ajv=e??Xz()}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 bu,kw=v(()=>{Qn();bu=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 s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(d=>d.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(d=>d.type==="tool_use");if(i){if(o.some(d=>d.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 d=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(o.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(d.size!==l.size||![...d].every(m=>l.has(m)))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},li,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){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 o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Ks,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 ww(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 Ew(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 $w=v(()=>{});var Su,Tw=v(()=>{NS();Qn();Sw();Xo();kw();$w();Su=class extends zc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ui.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new vu,this.setRequestHandler(Jm,n=>this._oninitialize(n)),this.setNotificationHandler(Ym,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(sf,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ui.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new bu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=AS(this._capabilities,e)}setRequestHandler(e,r){let s=an(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(Bt(s)){let a=s;o=a._zod?.def?.value??a.value}else{let a=s;o=a._def?.value??a.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(c,u)=>{let d=on(Gs,c);if(!d.success){let p=d.error instanceof Error?d.error.message:String(d.error);throw new F(q.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=d.data,m=await Promise.resolve(r(c,u));if(l.task){let p=on(Zs,m);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new F(q.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let f=on($c,m);if(!f.success){let p=f.error instanceof Error?f.error.message:String(f.error);throw new F(q.InvalidParams,`Invalid tools/call result: ${p}`)}return f.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){Ew(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&ww(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:Ab.includes(r)?r:qm,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"},mc)}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],s=Array.isArray(n.content)?n.content:[n.content],o=s.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(o){if(s.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(l=>l.type==="tool_use").map(l=>l.id)),d=new Set(s.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(u.size!==d.size||![...u].every(l=>d.has(l)))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},of,r):this.request({method:"sampling/createMessage",params:e},li,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 s=e;return this.request({method:"elicitation/create",params:s},Ks,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},Ks,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new F(q.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof F?i:new F(q.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}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},af,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 jg(t){return!!t&&typeof t=="object"&&Rw in t}function Cw(t){return t[Rw]?.complete}var Rw,Pw,Ow=v(()=>{Rw=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Pw||(Pw={}))});var Iw=v(()=>{});function eL(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"),!Qz.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);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 tL(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 zg(t){let e=eL(t);return tL(t,e.warnings),e.isValid}var Qz,Aw=v(()=>{Qz=/^[A-Za-z0-9._-]{1,128}$/});var ku,Nw=v(()=>{ku=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let s={taskSupport:"required",...r.execution};if(s.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,s,r._meta,n)}}});var Lg=v(()=>{ja();ja()});function jw(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function zw(t){return"_def"in t||"_zod"in t||jw(t)}function Fg(t){return typeof t!="object"||t===null||zw(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(jw)}function Dw(t){if(t){if(Fg(t))return Xn(t);if(!zw(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function nL(t){let e=an(t);return e?Object.entries(e).map(([r,n])=>{let s=sb(n),o=ob(n);return{name:r,description:s,required:!o}}):[]}function xn(t){let r=an(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ac(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Mw(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var wu,rL,Ui,Lw=v(()=>{Tw();Xo();Bf();Qn();Ow();Iw();Aw();Nw();Lg();wu=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 Su(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ku(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(xn(Ec)),this.server.assertCanSetRequestHandler(xn(Gs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ec,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let s=Us(r.inputSchema);return s?Uf(s,{strictUnions:!0,pipeStrategy:"input"}):rL})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=Us(r.outputSchema);s&&(n.outputSchema=Uf(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Gs,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new F(q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new F(q.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=n.execution?.taskSupport,i="createTask"in n.handler;if((o==="required"||o==="optional")&&!i)throw new F(q.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new F(q.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&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 s||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof F&&n.code===q.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 o=Us(e.inputSchema)??e.inputSchema,i=await oc(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=ic(a);throw new F(q.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 F(q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=Us(e.outputSchema),o=await oc(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=ic(i);throw new F(q.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(r,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(r,n))}else{let i=s;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 s=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,i={...n,taskStore:n.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),c=a.task.taskId,u=a.task,d=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(m=>setTimeout(m,d));let l=await n.taskStore.getTask(c);if(!l)throw new F(q.InternalError,`Task ${c} not found during polling`);u=l}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(xn(Tc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Tc,async e=>{switch(e.params.ref.type){case"ref/prompt":return Kb(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Jb(e),this.handleResourceCompletion(e,e.params.ref);default:throw new F(q.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new F(q.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new F(q.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Ui;let o=an(n.argsSchema)?.[e.params.argument.name];if(!jg(o))return Ui;let i=Cw(o);if(!i)return Ui;let a=await i(e.params.argument.value,e.params.context);return Mw(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 Ui;throw new F(q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return Ui;let o=await s(e.params.argument.value,e.params.context);return Mw(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(xn(qs)),this.server.assertCanSetRequestHandler(xn(Vs)),this.server.assertCanSetRequestHandler(xn(kc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(qs,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(r);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...n,...s]}}),this.server.setRequestHandler(Vs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(kc,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new F(q.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(n.toString());if(i)return o.readCallback(n,i,r)}throw new F(q.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(xn(Ws)),this.server.assertCanSetRequestHandler(xn(wc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ws,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?nL(r.argsSchema):void 0}))})),this.server.setRequestHandler(wc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new F(q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new F(q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=Us(n.argsSchema),o=await oc(s,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=ic(c);throw new F(q.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=o.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());let o=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,s,o);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,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){let i={name:e,title:r,metadata:s,readCallback:o,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,s,o){let i={resourceTemplate:n,title:r,metadata:s,readCallback:o,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,s,o){let i={title:r,description:n,argsSchema:s===void 0?void 0:Xn(s),callback:o,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=Xn(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,s&&Object.values(s).some(c=>{let u=c instanceof vt?c._def?.innerType:c;return jg(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,c,u){zg(e);let d={title:r,description:n,inputSchema:Dw(s),outputSchema:Dw(o),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(typeof l.name=="string"&&zg(l.name),delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=d)),typeof l.title<"u"&&(d.title=l.title),typeof l.description<"u"&&(d.description=l.description),typeof l.paramsSchema<"u"&&(d.inputSchema=Xn(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=Xn(l.outputSchema)),typeof l.callback<"u"&&(d.handler=l.callback),typeof l.annotations<"u"&&(d.annotations=l.annotations),typeof l._meta<"u"&&(d._meta=l._meta),typeof l.enabled<"u"&&(d.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Fg(c))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Fg(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,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,s,o,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 s;r.length>1&&(s=r.shift());let o=r[0],i=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=r,a=this._createRegisteredPrompt(e,s,o,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()}},rL={type:"object",properties:{}};Ui={completion:{values:[],hasMore:!1}}});function sL(t){return Ub.parse(JSON.parse(t))}function Fw(t){return JSON.stringify(t)+`
|
|
72
|
+
`}var Eu,Uw=v(()=>{Qn();Eu=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
73
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),sL(r)}clear(){this._buffer=void 0}}});import Hw from"node:process";var $u,Zw=v(()=>{Uw();$u=class{constructor(e=Hw.stdin,r=Hw.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Eu,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}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(r=>{let n=Fw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var Xw={};Fe(Xw,{PolyglotExecutor:()=>fo,buildScriptFilename:()=>Kw,buildShellScriptContent:()=>Yw,buildSpawnOptions:()=>Jw});import{spawn as oL,execSync as iL,execFileSync as Ww}from"node:child_process";import{mkdtempSync as aL,writeFileSync as Bw,rmSync as qw,existsSync as Vw}from"node:fs";import{join as Tu,resolve as Gw}from"node:path";import{tmpdir as cL}from"node:os";function Kw(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";return n.includes("powershell")||n.includes("pwsh")?"script.ps1":"script"}return`script.${uL[t]}`}function Jw(t){return{windowsHide:t==="win32"}}function lL(t){return`'${t.replace(/'/g,"'\\''")}'`}function Yw(t,e,r){return r==="win32"||!e?t:`export PATH=${lL(e)}
|
|
74
|
+
${t}`}function Ug(t){if(Xt&&t.pid)try{iL(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var Xt,uL,dL,fo,Hg=v(()=>{"use strict";ha();Xt=process.platform==="win32",uL={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs"};dL=(()=>{if(Xt)return process.env.TEMP??process.env.TMP??cL();try{let t=Ww(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:Gw(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();fo=class{#e;#t;#n;#o=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let r=e?.projectRoot;typeof r=="function"?this.#t=r:typeof r=="string"?this.#t=()=>r:this.#t=()=>process.cwd(),this.#n=e?.runtimes??xs()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(Xt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:r,code:n,timeout:s,background:o=!1}=e,i=aL(Tu(dL,".ctx-mode-"));try{let a=this.#a(i,n,r),c=r_(this.#n,r,a);if(c[0]==="__rust_compile_run__")return await this.#c(a,i,s);let u=r==="shell"?this.#s:i,d=await this.#i(c,u,i,s,o);if(!d.backgrounded)try{qw(i,{recursive:!0,force:!0})}catch{}return d}catch(a){try{qw(i,{recursive:!0,force:!0})}catch{}throw a}}async executeFile(e){let{path:r,language:n,code:s,timeout:o}=e,i=Gw(this.#s,r),a=this.#l(i,n,s);return this.execute({language:n,code:a,timeout:o})}#a(e,r,n){n==="go"&&!r.includes("package ")&&(r=`package main
|
|
75
75
|
|
|
76
76
|
import "fmt"
|
|
77
77
|
|
|
@@ -79,12 +79,12 @@ func main() {
|
|
|
79
79
|
${r}
|
|
80
80
|
}
|
|
81
81
|
`),n==="php"&&!r.trimStart().startsWith("<?")&&(r=`<?php
|
|
82
|
-
${r}`),n==="elixir"&&
|
|
82
|
+
${r}`),n==="elixir"&&Vw(Tu(this.#s,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify(Tu(this.#s,"_build/dev/lib"))}, "*/ebin"))
|
|
83
83
|
|> Enum.each(&Code.prepend_path/1)
|
|
84
84
|
|
|
85
|
-
${r}`);let s=Tu(e,
|
|
86
|
-
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([o],r,r,n)}async#i(e,r,n,s,o=!1){return new Promise(i=>{let a=
|
|
87
|
-
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:
|
|
85
|
+
${r}`);let s=Tu(e,Kw(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?Bw(s,Yw(r,process.env.PATH,process.platform),{encoding:"utf-8",mode:448}):Bw(s,r,"utf-8"),s}async#c(e,r,n){let s=Xt?".exe":"",o=e.replace(/\.rs$/,"")+s;try{Ww("rustc",[e,"-o",o],{cwd:r,timeout:n===void 0?6e4:Math.min(n,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
|
|
86
|
+
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([o],r,r,n)}async#i(e,r,n,s,o=!1){return new Promise(i=>{let a=Xt&&["tsx","ts-node","elixir","bun"].includes(e[0]),c=e[0],u;Xt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Xt?e.slice(1).map(x=>x.replace(/\\/g,"/")):e.slice(1);let d=oL(c,u,{cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),shell:a,detached:!Xt,...Jw(process.platform)}),l=!1,m=!1,f=s===void 0?void 0:setTimeout(()=>{if(l=!0,o){m=!0,d.pid&&this.#o.add(d.pid),d.unref(),d.stdout.destroy(),d.stderr.destroy();let x=Buffer.concat(p).toString("utf-8"),y=Buffer.concat(h).toString("utf-8");i({stdout:x,stderr:y,exitCode:0,timedOut:!0,backgrounded:!0})}else Ug(d)},s),p=[],h=[],g=0,_=!1;d.stdout.on("data",x=>{g+=x.length,g<=this.#e?p.push(x):_||(_=!0,Ug(d))}),d.stderr.on("data",x=>{g+=x.length,g<=this.#e?h.push(x):_||(_=!0,Ug(d))}),d.on("close",x=>{if(clearTimeout(f),m)return;let y=Buffer.concat(p).toString("utf-8"),b=Buffer.concat(h).toString("utf-8");_&&(b+=`
|
|
87
|
+
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:y,stderr:b,exitCode:l?1:x??1,timedOut:l})}),d.on("error",x=>{clearTimeout(f),!m&&i({stdout:"",stderr:x.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=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","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"]),s={};for(let[o,i]of Object.entries(process.env))i!==void 0&&!n.has(o)&&!o.startsWith("BASH_FUNC_")&&(s[o]=i);if(s.TMPDIR=e,s.HOME=r,s.LANG="en_US.UTF-8",s.PYTHONDONTWRITEBYTECODE="1",s.PYTHONUNBUFFERED="1",s.PYTHONUTF8="1",s.NO_COLOR="1",Xt&&!s.PATH&&s.Path&&(s.PATH=s.Path,delete s.Path),s.PATH||(s.PATH=Xt?"":"/usr/local/bin:/usr/bin:/bin"),Xt){s.MSYS_NO_PATHCONV="1",s.MSYS2_ARG_CONV_EXCL="*";let o="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";s.PATH.includes(o)||(s.PATH=`${o};${i};${s.PATH}`)}if(!s.SSL_CERT_FILE){let o=Xt?[]:["/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 o)if(Vw(i)){s.SSL_CERT_FILE=i;break}}return s}#l(e,r,n){let s=JSON.stringify(e);switch(r){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${s};
|
|
88
88
|
const file_path = FILE_CONTENT_PATH;
|
|
89
89
|
const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
|
|
90
90
|
${n}`;case"python":return`FILE_CONTENT_PATH = ${s}
|
|
@@ -139,7 +139,7 @@ FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
|
|
|
139
139
|
${n}`;case"elixir":return`file_content_path = ${s}
|
|
140
140
|
file_path = file_content_path
|
|
141
141
|
file_content = File.read!(file_content_path)
|
|
142
|
-
${n}`}}}});import{cpus as
|
|
142
|
+
${n}`}}}});import{cpus as pL}from"node:os";async function Zg(t,e){let{concurrency:r,capByCpuCount:n=!1,onSettled:s}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let o=Math.max(1,r),i=n?Math.max(1,pL().length):o,a=Math.min(o,i,t.length),c=a<o,u=new Array(t.length),d=0;async function l(){for(;;){let f=d++;if(f>=t.length)return;try{let p=await t[f].run();u[f]={status:"fulfilled",value:p}}catch(p){u[f]={status:"rejected",reason:p}}s?.(f,u[f])}}let m=[];for(let f=0;f<a;f++)m.push(l());return await Promise.allSettled(m),{settled:u,effectiveConcurrency:a,capped:c}}var Qw=v(()=>{"use strict"});var nE={};Fe(nE,{BunSQLiteAdapter:()=>Pu,NodeSQLiteAdapter:()=>Ru,SQLiteBase:()=>Zi,applyWALPragmas:()=>go,cleanOrphanedWALFiles:()=>yo,closeDB:()=>_o,defaultDBPath:()=>qg,deleteDBFiles:()=>Cu,isSQLiteCorruptionError:()=>Ou,loadDatabase:()=>Qt,nodeSqliteHasFts5:()=>tE,renameCorruptDB:()=>rE,withRetry:()=>vn});import{createRequire as mL}from"node:module";import{existsSync as fL,unlinkSync as eE,renameSync as hL}from"node:fs";import{tmpdir as gL}from"node:os";import{join as yL}from"node:path";function tE(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 Qt(){if(!ho){let t=mL(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;ho=function(n,s){let o=new e(n,{readonly:s?.readonly,create:!0}),i=new Pu(o);return s?.timeout&&i.pragma(`busy_timeout = ${s.timeout}`),i}}else if(process.platform==="linux"){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&tE(e)?ho=function(n,s){let o=new e(n,{readOnly:s?.readonly??!1});return new Ru(o)}:ho=t("better-sqlite3")}else ho=t("better-sqlite3")}return ho}function go(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function yo(t){if(!fL(t))for(let e of["-wal","-shm"])try{eE(t+e)}catch{}}function Cu(t){for(let e of["","-wal","-shm"])try{eE(t+e)}catch{}}function _o(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function qg(t="context-mode"){return yL(gL(),`${t}-${process.pid}.db`)}function vn(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(s){let o=s instanceof Error?s.message:String(s);if(!o.includes("SQLITE_BUSY")&&!o.includes("database is locked"))throw s;if(r=s instanceof Error?s:new Error(o),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 Ou(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 rE(t){let e=Date.now();for(let r of["","-wal","-shm"])try{hL(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var Pu,Ru,ho,Hi,Bg,Zi,xo=v(()=>{"use strict";Pu=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 s=Object.values(n[0]);return s.length===1?s[0]:n[0]}exec(e){let r="",n=null;for(let o=0;o<e.length;o++){let i=e[o];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 s=r.trim();return s&&this.#e.prepare(s).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let s=r.get(...n);return s===null?void 0:s},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},Ru=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 s=Object.values(n[0]);return s.length===1?s[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()}},ho=null;Hi=Symbol.for("__context_mode_live_dbs__"),Bg=(()=>{let t=globalThis;return t[Hi]||(t[Hi]=new Set,process.on("exit",()=>{for(let e of t[Hi])_o(e);t[Hi].clear()})),t[Hi]})(),Zi=class{#e;#t;constructor(e){let r=Qt();this.#e=e,yo(e);let n;try{n=new r(e,{timeout:3e4}),go(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(Ou(o)){rE(e),yo(e);try{n=new r(e,{timeout:3e4}),go(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw s}this.#t=n,Bg.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){Bg.delete(this.#t),_o(this.#t)}withRetry(e){return vn(e)}cleanup(){Bg.delete(this.#t),_o(this.#t),Cu(this.#e)}}});import{readFileSync as sE,readdirSync as lE,unlinkSync as Wg,existsSync as Vg,statSync as Iu,openSync as oE,fstatSync as iE,closeSync as aE}from"node:fs";import{createHash as cE}from"node:crypto";import{tmpdir as dE}from"node:os";import{join as Gg}from"node:path";function pE(t){let e=new Set,r=[];for(let n of t){let s=n.toLowerCase();e.has(s)||(e.add(s),r.push(n))}return r}function _L(t,e="AND"){let r=pE(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(o=>o.length>0&&!["AND","OR","NOT","NEAR"].includes(o.toUpperCase())));if(r.length===0)return'""';let n=r.filter(o=>!vo.has(o.toLowerCase()));return(n.length>0?n:r).map(o=>`"${o}"`).join(e==="OR"?" OR ":" ")}function xL(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=pE(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let s=n.filter(i=>!vo.has(i.toLowerCase()));return(s.length>0?s:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function vL(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,s)=>s);for(let n=1;n<=t.length;n++){let s=[n];for(let o=1;o<=e.length;o++)s[o]=t[n-1]===e[o-1]?r[o-1]:1+Math.min(r[o],s[o-1],r[o-1]);r=s}return r[e.length]}function bL(t){return t<=4?1:t<=12?2:3}function Kg(){let t=dE(),e=0;try{let r=lE(t);for(let n of r){let s=n.match(/^context-mode-(\d+)\.db$/);if(!s)continue;let o=parseInt(s[1],10);if(o!==process.pid)try{process.kill(o,0)}catch{let i=Gg(t,n);for(let a of["","-wal","-shm"])try{Wg(i+a)}catch{}e++}}}catch{}return e}function Jg(t,e){let r=0;try{if(!Vg(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=lE(t).filter(o=>o.endsWith(".db"));for(let o of s)try{let i=Gg(t,o),c=Iu(i).mtimeMs<n;if(!c){let u=i+"-wal";if(Vg(u))try{let d=Iu(u);d.size>0&&Date.now()-d.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Wg(i+u)}catch{}r++}}catch{}}catch{}return r}function SL(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function kL(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,s=Math.min(t.length,e.length)-1;for(let o=0;o<s;o++){let i=t[o],a=t[o+1],c=e[o].length,u=0;for(let d of i){let l=d+c,m=l+r;for(;u<a.length&&a[u]<l;)u++;u<a.length&&a[u]<=m&&(n++,u++)}}return n}function wL(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t.map(s=>[...s].sort((o,i)=>o-i)),r=new Array(e.length).fill(0),n=1/0;for(;;){let s=1/0,o=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<s&&(s=u,i=c),u>o&&(o=u)}let a=o-s;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var vo,uE,Au,mE=v(()=>{"use strict";xo();vo=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"]);uE=4096;Au=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#m;#f;#h;#g;#y;#_;#x;#v;#b;#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=Qt();this.#t=e??Gg(dE(),`context-mode-${process.pid}.db`),yo(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),go(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(Ou(o)){Cu(this.#t),yo(this.#t);try{n=new r(this.#t,{timeout:3e4}),go(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw s}this.#e=n,this.#H(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{Wg(this.#t+e)}catch{}}#H(){this.#e.exec(`
|
|
143
143
|
CREATE TABLE IF NOT EXISTS sources (
|
|
144
144
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
145
145
|
label TEXT NOT NULL,
|
|
@@ -379,22 +379,22 @@ ${n}`}}}});import{cpus as rL}from"node:os";async function Fg(t,e){let{concurrenc
|
|
|
379
379
|
(SELECT COUNT(*) FROM sources) AS sources,
|
|
380
380
|
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
381
381
|
(SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
|
|
382
|
-
`),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:s}=e,o=typeof r=="string"&&r.length>0;if(!o&&!n)throw new Error("Either content or path must be provided");let i;if(o)i=r;else{let l=
|
|
382
|
+
`),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:s}=e,o=typeof r=="string"&&r.length>0;if(!o&&!n)throw new Error("Either content or path must be provided");let i;if(o)i=r;else{let l=oE(n,"r");try{if(!iE(l).isFile())throw new Error(`refusing to index ${n}: not a regular file`);i=sE(l,"utf-8")}finally{aE(l)}}let a=s??n??"untitled",c=this.#V(i),u=n??void 0,d=u?cE("sha256").update(i).digest("hex"):void 0;return vn(()=>this.#d(c,a,i,u,d))}indexPlainText(e,r,n=20){if(!e||e.trim().length===0)return this.#d([],r,"");let s=this.#W(e,n);return vn(()=>this.#d(s.map(o=>({...o,hasCode:!1})),r,e))}indexJSON(e,r,n=uE){if(!e||e.trim().length===0)return this.indexPlainText("",r);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,r)}let o=[];return this.#U(s,[],o,n),o.length===0?this.indexPlainText(e,r):vn(()=>this.#d(o,r,e))}#d(e,r,n,s,o){let i=e.filter(u=>u.hasCode).length,c=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#m.run(r),e.length===0){let m=this.#o.run(r,s??null,o??null);return Number(m.lastInsertRowid)}let u=this.#s.run(r,e.length,i,s??null,o??null),d=Number(u.lastInsertRowid),l=new Date().toISOString();for(let m of e){let f=m.hasCode?"code":"prose";this.#a.run(m.title,m.content,d,f,null,null,null,l),this.#c.run(m.title,m.content,d,f,null,null,null,l)}return d})();return n&&this.#q(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#F(),{sourceId:c,label:r,totalChunks:e.length,codeChunks:i}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0}))}#p(e,r){return r==="exact"?e:`%${e}%`}search(e,r=3,n,s="AND",o,i="like"){let a=_L(e,s),c,u;return n&&o?(c=i==="exact"?this.#k:this.#S,u=[a,this.#p(n,i),o,r]):n?(c=i==="exact"?this.#g:this.#h,u=[a,this.#p(n,i),r]):o?(c=this.#b,u=[a,o,r]):(c=this.#f,u=[a,r]),vn(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,s="AND",o,i="like"){let a=xL(e,s);if(!a)return[];let c,u;return n&&o?(c=i==="exact"?this.#$:this.#E,u=[a,this.#p(n,i),o,r]):n?(c=i==="exact"?this.#x:this.#_,u=[a,this.#p(n,i),r]):o?(c=this.#w,u=[a,o,r]):(c=this.#y,u=[a,r]),vn(()=>this.#j(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;if(this.#r.has(r)){let u=this.#r.get(r)??null;return this.#r.delete(r),this.#r.set(r,u),u}let n=bL(r.length),s=this.#v.all(r.length-n,r.length+n),o=null,i=n+1,a=!1;for(let{word:u}of s){if(u===r){a=!0;break}let d=vL(r,u);d<i&&(i=d,o=u)}let c=a?null:i<=n?o: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(r,c),c}#z(e,r,n,s,o="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",s,o),u=this.searchTrigram(e,a,n,"OR",s,o),d=new Map,l=m=>`${m.source}::${m.title}`;for(let[m,f]of c.entries()){let p=l(f),h=d.get(p);h?h.score+=1/(60+m+1):d.set(p,{result:f,score:1/(60+m+1)})}for(let[m,f]of u.entries()){let p=l(f),h=d.get(p);h?h.score+=1/(60+m+1):d.set(p,{result:f,score:1/(60+m+1)})}return Array.from(d.values()).sort((m,f)=>f.score-m.score).slice(0,r).map(({result:m,score:f})=>({...m,rank:-f}))}#L(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),s=n.filter(i=>!vo.has(i)),o=s.length>0?s:n;return e.map(i=>{let a=i.title.toLowerCase(),c=o.filter(f=>a.includes(f)).length,u=i.contentType==="code"?.6:.3,d=c>0?u*(c/o.length):0,l=0,m=0;if(o.length>=2){let f=i.content.toLowerCase(),p=o.map(h=>SL(f,h));if(!p.some(h=>h.length===0)){l=1/(1+wL(p)/Math.max(f.length,1));let g=kL(p,o);m=.5*Math.min(1,g/4)}}return{result:i,boost:d+l+m}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,r=3,n,s,o="like"){this.#B();let i=this.#z(e,r,n,s,o);if(i.length>0)return this.#L(i,e).map(m=>({...m,matchLayer:"rrf"}));let a=e.toLowerCase().trim().split(/\s+/).filter(l=>l.length>=3&&!vo.has(l)),c=a.join(" "),d=a.map(l=>this.fuzzyCorrect(l)??l).join(" ");if(d!==c){let l=this.#z(d,r,n,s,o);if(l.length>0)return this.#L(l,d).map(f=>({...f,matchLayer:"rrf-fuzzy"}))}return[]}lastRefreshCount=0;#B(){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 r of e)try{if(!Vg(r.file_path)||this.#n&&this.#n(r.file_path))continue;let n=Iu(r.file_path).mtime,s=new Date(r.indexed_at+"Z");if(n<=s)continue;let o=oE(r.file_path,"r"),i;try{if(!iE(o).isFile())continue;i=sE(o,"utf-8")}finally{aE(o)}if(cE("sha256").update(i).digest("hex")===r.content_hash)continue;this.index({content:i,path:r.file_path,source:r.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let r=this.#I.get(e);return r?{label:r.label,chunkCount:r.chunk_count,codeChunkCount:r.code_chunk_count,indexedAt:r.indexed_at,filePath:r.file_path??null,contentHash:r.content_hash??null}:null}listSources(){return this.#T.all()}getChunksBySource(e){return this.#P.all(e).map(n=>({title:n.title,content:n.content,source:n.label,rank:0,contentType:n.content_type}))}getDistinctiveTerms(e,r=40){let n=this.#R.get(e);if(!n||n.chunk_count<3)return[];let s=n.chunk_count,o=2,i=Math.max(3,Math.ceil(s*.4)),a=new Map;for(let d of this.#C.iterate(e)){let l=new Set(d.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(m=>m.length>=3&&!vo.has(m)));for(let m of l)a.set(m,(a.get(m)??0)+1)}return Array.from(a.entries()).filter(([,d])=>d>=o&&d<=i).map(([d,l])=>{let m=Math.log(s/l),f=Math.min(d.length/20,.5),p=/[_]/.test(d),h=d.length>=12,g=p?1.5:h?.8:0;return{word:d,score:m+f+g}}).sort((d,l)=>l.score-d.score).slice(0,r).map(d=>d.word)}getStats(){let e=this.#O.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(s=>(this.#A.run(s),this.#N.run(s),this.#D.run(s)))(e).changes}getDBSizeBytes(){try{return Iu(this.#t).size}catch{return 0}}#F(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#F(),_o(this.#e)}#q(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(o=>o.length>=3&&!vo.has(o)),n=[...new Set(r)],s=0;this.#e.transaction(()=>{for(let o of n){let i=this.#i.run(o);s+=i.changes}})(),s>0&&this.#r.clear()}#V(e,r=uE){let n=[],s=e.split(`
|
|
383
383
|
`),o=[],i=[],a="",c=()=>{let d=i.join(`
|
|
384
|
-
`).trim();if(d.length===0)return;let l=this.#Y(o,a),m=i.some(
|
|
384
|
+
`).trim();if(d.length===0)return;let l=this.#Y(o,a),m=i.some(_=>/^`{3,}/.test(_));if(Buffer.byteLength(d)<=r){n.push({title:l,content:d,hasCode:m}),i=[];return}let f=d.split(/\n\n+/),p=[],h=1,g=()=>{if(p.length===0)return;let _=p.join(`
|
|
385
385
|
|
|
386
|
-
`).trim();if(
|
|
386
|
+
`).trim();if(_.length===0)return;let x=f.length>1?`${l} (${h})`:l;h++,n.push({title:x,content:_,hasCode:_.includes("```")}),p=[]};for(let _ of f){p.push(_);let x=p.join(`
|
|
387
387
|
|
|
388
|
-
`);Buffer.byteLength(x)>r&&p.length>1&&(p.pop(),g(),p=[
|
|
388
|
+
`);Buffer.byteLength(x)>r&&p.length>1&&(p.pop(),g(),p=[_])}g(),i=[]},u=0;for(;u<s.length;){let d=s[u];if(/^[-_*]{3,}\s*$/.test(d)){c(),u++;continue}let l=d.match(/^(#{1,4})\s+(.+)$/);if(l){c();let f=l[1].length,p=l[2].trim();for(;o.length>0&&o[o.length-1].level>=f;)o.pop();o.push({level:f,text:p}),a=p,i.push(d),u++;continue}let m=d.match(/^(`{3,})(.*)?$/);if(m){let f=m[1],p=[d];for(u++;u<s.length;){if(p.push(s[u]),s[u].startsWith(f)&&s[u].trim()===f){u++;break}u++}i.push(...p);continue}i.push(d),u++}return c(),n}#W(e,r){let n=e.split(/\n\s*\n/);if(n.length>=3&&n.length<=200&&n.every(c=>Buffer.byteLength(c)<5e3))return n.map((c,u)=>{let d=c.trim();return{title:d.split(`
|
|
389
389
|
`)[0].slice(0,80)||`Section ${u+1}`,content:d}}).filter(c=>c.content.length>0);let s=e.split(`
|
|
390
390
|
`);if(s.length<=r)return[{title:"Output",content:e}];let o=[],a=Math.max(r-2,1);for(let c=0;c<s.length;c+=a){let u=s.slice(c,c+r);if(u.length===0)break;let d=c+1,l=Math.min(c+u.length,s.length),m=u[0]?.trim().slice(0,80);o.push({title:m||`Lines ${d}-${l}`,content:u.join(`
|
|
391
|
-
`)})}return o}#U(e,r,n,s){let o=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=s&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:o,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,[...r,c],n,s);return}n.push({title:o,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#J(e,r,n,s);return}n.push({title:o,content:i,hasCode:!1})}#G(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],s=r;for(let o of n)if(o in s&&(typeof s[o]=="string"||typeof s[o]=="number"))return o;return null}#K(e,r,n,s,o){let i=e?`${e} > `:"";if(!o)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[o]);return s.length===1?`${i}${a(s[0])}`:s.length<=3?i+s.map(a).join(", "):`${i}${a(s[0])}\u2026${a(s[s.length-1])}`}#J(e,r,n,s){let o=r.length>0?r.join(" > "):"(root)",i=this.#G(e),a=[],c=0,u=d=>{if(a.length===0)return;let l=this.#K(o,c,d,a,i);n.push({title:l,content:JSON.stringify(a,null,2),hasCode:!0})};for(let d=0;d<e.length;d++){a.push(e[d]);let l=JSON.stringify(a,null,2);Buffer.byteLength(l)>s&&a.length>1&&(a.pop(),u(d-1),a=[e[d]],c=d)}u(c+a.length-1)}#Y(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}}});function
|
|
391
|
+
`)})}return o}#U(e,r,n,s){let o=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=s&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:o,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,[...r,c],n,s);return}n.push({title:o,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#J(e,r,n,s);return}n.push({title:o,content:i,hasCode:!1})}#G(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],s=r;for(let o of n)if(o in s&&(typeof s[o]=="string"||typeof s[o]=="number"))return o;return null}#K(e,r,n,s,o){let i=e?`${e} > `:"";if(!o)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[o]);return s.length===1?`${i}${a(s[0])}`:s.length<=3?i+s.map(a).join(", "):`${i}${a(s[0])}\u2026${a(s[s.length-1])}`}#J(e,r,n,s){let o=r.length>0?r.join(" > "):"(root)",i=this.#G(e),a=[],c=0,u=d=>{if(a.length===0)return;let l=this.#K(o,c,d,a,i);n.push({title:l,content:JSON.stringify(a,null,2),hasCode:!0})};for(let d=0;d<e.length;d++){a.push(e[d]);let l=JSON.stringify(a,null,2);Buffer.byteLength(l)>s&&a.length>1&&(a.pop(),u(d-1),a=[e[d]],c=d)}u(c+a.length-1)}#Y(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}}});function Yg(t,e){return t===void 0?e:`${t}::${e}`}var fE=v(()=>{"use strict"});import{readFileSync as gE,realpathSync as EL}from"node:fs";import{resolve as Bi}from"node:path";function yE(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function $L(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function TL(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function hE(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function PL(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let s=t.slice(0,n),o=t.slice(n+1),i=TL(s),a=hE(o);r=`^${i}(\\s${a})?$`}else r=`^${hE(t)}$`;return new RegExp(r,e?"i":"")}function RL(t,e=!1){let r="",n=0;for(;n<t.length;)t[n]==="*"&&t[n+1]==="*"?n+2<t.length&&t[n+2]==="/"?(r+="(.*/)?",n+=3):(r+=".*",n+=2):t[n]==="*"?(r+="[^/]*",n++):t[n]==="?"?(r+="[^/]",n++):(r+=t[n].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),n++);return new RegExp(`^${r}$`,e?"i":"")}function CL(t,e,r=!1){for(let n of e){let s=yE(n);if(s&&PL(s,r).test(t))return n}return null}function OL(t){let e=[],r="",n=!1,s=!1,o=!1;for(let i=0;i<t.length;i++){let a=t[i],c=i>0?t[i-1]:"";a==="'"&&!s&&!o&&c!=="\\"?(n=!n,r+=a):a==='"'&&!n&&!o&&c!=="\\"?(s=!s,r+=a):a==="`"&&!n&&!s&&c!=="\\"?(o=!o,r+=a):!n&&!s&&!o?a===";"?(e.push(r.trim()),r=""):a==="|"&&t[i+1]==="|"||a==="&"&&t[i+1]==="&"?(e.push(r.trim()),r="",i++):a==="|"?(e.push(r.trim()),r=""):r+=a:r+=a}return r.trim()&&e.push(r.trim()),e.filter(i=>i.length>0)}function Xg(t){let e;try{e=gE(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let s=o=>Array.isArray(o)?o.filter(i=>typeof i=="string"&&yE(i)!==null):[];return{allow:s(n.allow),deny:s(n.deny),ask:s(n.ask)}}function Qg(t,e){let r=[];if(t){let s=Bi(t,".claude","settings.local.json"),o=Xg(s);o&&r.push(o);let i=Bi(t,".claude","settings.json"),a=Xg(i);a&&r.push(a)}let n=e!==void 0?[e]:El();for(let s of n){let o=Xg(s);o&&r.push(o)}return r}function ey(t,e,r){let n=[],s=i=>{let a;try{a=gE(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 d=[];for(let l of u){if(typeof l!="string")continue;let m=$L(l);m&&m.tool===t&&d.push(m.glob)}return d};if(e){let i=s(Bi(e,".claude","settings.local.json"));i!==null&&n.push(i);let a=s(Bi(e,".claude","settings.json"));a!==null&&n.push(a)}let o=r!==void 0?[r]:El();for(let i of o){let a=s(i);a!==null&&n.push(a)}return n}function ty(t,e,r=process.platform==="win32"){let n=OL(t);for(let s of n)for(let o of e){let i=CL(s,o.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function ry(t,e,r=process.platform==="win32",n){let s=i=>i.replace(/\\/g,"/"),o=new Set;if(o.add(s(t)),n){let i=Bi(n,t);o.add(s(i));try{o.add(s(EL(i)))}catch{}}for(let i of e)for(let a of i){let c=RL(s(a),r);for(let u of o)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function AL(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let o=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);o.length>0&&e.push(o.join(" "))}return e}function _E(t,e){let r=IL[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let s of r){s.lastIndex=0;let o;for(;(o=s.exec(t))!==null;){let i=o[o.length-1];i&&n.push(i)}}return e==="python"&&n.push(...AL(t)),n}var IL,xE=v(()=>{"use strict";Kr();IL={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]}});function ny(t){let{language:e,exitCode:r,stdout:n,stderr:s}=t,o=e==="shell"&&r===1&&n.trim().length>0;return{isError:!o,output:o?n:`Exit code: ${r}
|
|
392
392
|
|
|
393
393
|
stdout:
|
|
394
394
|
${n}
|
|
395
395
|
|
|
396
396
|
stderr:
|
|
397
|
-
${s}`}}var
|
|
397
|
+
${s}`}}var vE=v(()=>{"use strict"});import{execFileSync as NL}from"node:child_process";function DL(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=NL("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function ML(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??DL,n=e(),s=r();return()=>{let o=e();return!(o!==n||o===0||o===1||!Number.isNaN(s)&&s>1&&r()===1)}}function bE(t){let e=t.checkIntervalMs??3e4,r=t.isParentAlive??jL,n=!1,s=()=>{n||(n=!0,t.onShutdown())},o=setInterval(()=>{r()||s()},e);o.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,s);let a=()=>{r()||s()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{n=!0,clearInterval(o);for(let c of i)process.removeListener(c,s);process.stdin.removeListener("end",a)}}var jL,SE=v(()=>{"use strict";jL=ML()});import{createHash as Vi}from"node:crypto";import{execFileSync as zL}from"node:child_process";import{existsSync as Du,realpathSync as LL,renameSync as sy}from"node:fs";import{join as Mu}from"node:path";function Wi(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function kE(t){let e=t;try{e=LL.native(t)}catch{}let r=Wi(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function $E(t,e){return zL("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function FL(t){let e=$E(t,["rev-parse","--show-toplevel"]);return e.length>0?Wi(e):null}function UL(t){let e=$E(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?Wi(e):null}function oy(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(qi&&qi.projectDir===t&&qi.envSuffix===e)return qi.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=FL(t),s=UL(t);if(n&&s){let o=kE(n),i=kE(s);o!==i&&(r=`__${Vi("sha256").update(o).digest("hex").slice(0,8)}`)}}catch{}return qi={projectDir:t,envSuffix:e,suffix:r},r}function ls(t){return Vi("sha256").update(Wi(t)).digest("hex").slice(0,16)}function ds(t){let e=Wi(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Vi("sha256").update(r).digest("hex").slice(0,16)}function TE(t){let{projectDir:e,contentDir:r}=t,n=ds(e),s=Mu(r,`${n}.db`);if(Du(s))return s;let o=ls(e);if(o===n)return s;let i=Mu(r,`${o}.db`);if(Du(i))try{sy(i,s);for(let a of["-wal","-shm"])try{sy(i+a,s+a)}catch{}}catch{}return s}function ju(t){return HL({...t,ext:".db"})}function HL(t){let{projectDir:e,sessionsDir:r,ext:n}=t,s=t.suffix??oy(e),o=ds(e),i=Mu(r,`${o}${s}${n}`);if(Du(i))return i;let a=ls(e);if(a===o)return i;let c=Mu(r,`${a}${s}${n}`);if(Du(c))try{sy(c,i)}catch{}return i}function Nu(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}var qi,wE,EE,B,Fr,Gi=v(()=>{"use strict";xo();wE=1e3,EE=5;B={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",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"},Fr=class extends Zi{constructor(e){super(e?.dbPath??qg("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let r=this.db.pragma("table_xinfo(session_events)").find(n=>n.name==="data_hash");r&&r.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
|
|
398
398
|
CREATE TABLE IF NOT EXISTS session_events (
|
|
399
399
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
400
400
|
session_id TEXT NOT NULL,
|
|
@@ -512,17 +512,17 @@ ${s}`}}var yE=v(()=>{"use strict"});import{execFileSync as wL}from"node:child_pr
|
|
|
512
512
|
FROM tool_calls WHERE session_id = ?`),e(B.getToolCallByTool,`SELECT tool, calls, bytes_returned
|
|
513
513
|
FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(B.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
514
514
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
515
|
-
FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",s,o){let i=
|
|
516
|
-
`)}for(let f of m){if(o.length>=e)break;try{let p;try{if(p=
|
|
515
|
+
FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",s,o){let i=Vi("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),a=String(s?.projectDir??r.project_dir??"").trim(),c=String(s?.source??r.attribution_source??"unknown"),u=Number(s?.confidence??r.attribution_confidence??0),d=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,l=Nu(o?.bytesAvoided),m=Nu(o?.bytesReturned),f=this.db.transaction(()=>{if(this.stmt(B.checkDuplicate).get(e,EE,r.type,i))return;this.stmt(B.getEventCount).get(e).cnt>=wE&&this.stmt(B.evictLowestPriority).run(e),this.stmt(B.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,d,l,m,n,i),this.stmt(B.updateMetaLastEvent).run(e)});this.withRetry(()=>f())}bulkInsertEvents(e,r,n="PostToolUse",s,o){if(!r||r.length===0)return;if(r.length===1){this.insertEvent(e,r[0],n,s?.[0],o?.[0]);return}let i=r.map((c,u)=>{let d=Vi("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),l=s?.[u],m=String(l?.projectDir??c.project_dir??"").trim(),f=String(l?.source??c.attribution_source??"unknown"),p=Number(l?.confidence??c.attribution_confidence??0),h=Number.isFinite(p)?Math.max(0,Math.min(1,p)):0,g=o?.[u],_=Nu(g?.bytesAvoided),x=Nu(g?.bytesReturned);return{event:c,dataHash:d,projectDir:m,attributionSource:f,attributionConfidence:h,bytesAvoided:_,bytesReturned:x}}),a=this.db.transaction(()=>{let c=this.stmt(B.getEventCount).get(e).cnt;for(let u of i)this.stmt(B.checkDuplicate).get(e,EE,u.event.type,u.dataHash)||(c>=wE?this.stmt(B.evictLowestPriority).run(e):c++,this.stmt(B.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,n,u.dataHash));this.stmt(B.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,r){let n=r?.limit??1e3,s=r?.type,o=r?.minPriority;return s&&o!==void 0?this.stmt(B.getEventsByTypeAndPriority).all(e,s,o,n):s?this.stmt(B.getEventsByType).all(e,s,n):o!==void 0?this.stmt(B.getEventsByPriority).all(e,o,n):this.stmt(B.getEvents).all(e,n)}getEventCount(e){return this.stmt(B.getEventCount).get(e).cnt}getEventBytesSummary(e){let r=this.stmt(B.getEventBytesSummary).get(e);return{bytesAvoided:Number(r?.bytes_avoided??0),bytesReturned:Number(r?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(B.getLatestAttributedProject).get(e)?.project_dir||null}searchEvents(e,r,n,s){try{let o=e.replace(/[%_]/g,a=>"\\"+a),i=s??null;return this.stmt(B.searchEvents).all(n,o,o,i,i,r)}catch{return[]}}ensureSession(e,r){this.stmt(B.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(B.getSessionStats).get(e)??null}incrementCompactCount(e){this.stmt(B.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(B.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(B.getResume).get(e)??null}markResumeConsumed(e){this.stmt(B.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(B.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.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,r,n=0){let s=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(B.incrementToolCall).run(e,r,s)}catch{}}getToolCallStats(e){try{let r=this.stmt(B.getToolCallTotals).get(e),n=this.stmt(B.getToolCallByTool).all(e),s={};for(let o of n)s[o.tool]={calls:o.calls,bytesReturned:o.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:s}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(B.deleteEvents).run(e),this.stmt(B.deleteResume).run(e),this.stmt(B.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(B.getOldSessions).all(r);for(let{session_id:s}of n)this.deleteSession(s);return n.length}}});import{unlinkSync as ZL}from"node:fs";import{join as iy}from"node:path";function ay(t,e){try{return ZL(t),e.push(t),!0}catch{return!1}}function zu(t,e){let r=!1;for(let n of BL)ay(`${t}${n}`,e)&&n===""&&(r=!0);return r}function PE(t){let{projectDir:e,sessionsDir:r,storePath:n,contentDir:s,legacyContentDir:o,contentHash:i}=t,a=[],c=[],u=!1;if(n&&zu(n,c)&&(u=!0),s){let g=ds(e),_=ls(e),x=g===_?[g]:[g,_];for(let y of x){let b=iy(s,`${y}.db`);zu(b,c)&&(u=!0)}}if(u&&a.push("knowledge base (FTS5)"),o){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let g=iy(o,`${i}.db`);zu(g,c)}let d=oy(e),l=ds(e),m=ls(e),f=l===m?[l]:[l,m],p=!1,h=!1;for(let g of f){let _=iy(r,`${g}${d}`);zu(`${_}.db`,c)&&(p=!0),ay(`${_}-events.md`,c)&&(h=!0),ay(`${_}.cleanup`,c)}return p&&a.push("session events DB"),h&&a.push("session events markdown"),{deleted:a,wipedPaths:c}}var BL,RE=v(()=>{"use strict";Gi();BL=["","-wal","-shm"]});import{existsSync as qL}from"node:fs";function cy(t,e){try{if(!qL(t))return;let r=new Fr({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function CE(t){cy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{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 OE(t){cy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{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 IE(t){cy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{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 AE=v(()=>{"use strict";Gi()});import{existsSync as NE}from"node:fs";function DE(t,e,r){try{if(!NE(t))return;let n=new Fr({dbPath:t});try{let s=n.getLatestSessionId();if(!s)return;n.incrementToolCall(s,e,r)}finally{n.close()}}catch{}}function ME(t){try{if(!NE(t))return null;let e=new Fr({dbPath:t});try{let r=e.getLatestSessionId();if(!r)return null;let n=e.getToolCallStats(r),s={},o={};for(let[a,c]of Object.entries(n.byTool))s[a]=c.calls,o[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(r);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(s).length===0&&Object.keys(o).length===0?{calls:s,bytesReturned:o,sessionStart:i}:{calls:s,bytesReturned:o,sessionStart:i}}finally{e.close()}}catch{return null}}var jE=v(()=>{"use strict";Gi()});import{existsSync as uy,readFileSync as VL,readdirSync as WL,statSync as GL}from"node:fs";import{join as Ki,isAbsolute as KL}from"node:path";function FE(t,e=5,r,n,s){let o=[],i=s?.getInstructionFiles()??["CLAUDE.md"],a=s?.getConfigDir(),u=(a?LE(r,a):null)??n??qe(),d=s?.getMemoryDir(),l=d?LE(r,d):Ki(u,"memory"),m=[];if(r)for(let f of i){let p=Ki(r,f);uy(p)&&m.push({path:p,label:`project/${f}`})}if(u&&u!==r)for(let f of i){let p=Ki(u,f);uy(p)&&m.push({path:p,label:`user/${f}`})}if(l&&uy(l))try{let f=WL(l).filter(p=>p.endsWith(".md"));for(let p of f)m.push({path:Ki(l,p),label:`memory/${p}`})}catch(f){zE&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${f}
|
|
516
|
+
`)}for(let f of m){if(o.length>=e)break;try{let p;try{if(p=GL(f.path),p.size>1e6)continue}catch{continue}let h=VL(f.path,"utf-8"),g=h.toLowerCase();for(let _ of t){if(o.length>=e)break;let y=_.toLowerCase().split(/\s+/).filter(w=>w.length>=3);if(y.some(w=>{try{return new RegExp(`\\b${w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(h)}catch{return g.includes(w)}})){let w=y.reduce((I,V)=>{let oe=g.indexOf(V);return oe>=0&&(I<0||oe<I)?oe:I},-1),O=Math.max(0,w-200),C=Math.min(h.length,w+500),T=h.lastIndexOf(`
|
|
517
517
|
|
|
518
|
-
`,
|
|
518
|
+
`,O),z=h.indexOf(`
|
|
519
519
|
|
|
520
|
-
`,C);T>=0&&(
|
|
521
|
-
`)}}return o.slice(0,e)}function
|
|
522
|
-
`)}if(s==="timeline"){try{if(a){let f=a.searchEvents(e,r,c||"",o);l.push(...f.map(p=>({title:`[${p.category}] ${p.type}`,content:p.data,source:"prior-session",origin:"prior-session",timestamp:p.created_at})))}}catch(f){
|
|
523
|
-
`)}try{let f=
|
|
524
|
-
`)}}for(let f of l)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return s==="timeline"&&l.sort((f,p)=>(f.timestamp||"").localeCompare(p.timestamp||"")),l.slice(0,r)}var
|
|
525
|
-
`).slice(0,10))if(
|
|
520
|
+
`,C);T>=0&&(O=T+2),z>=0&&(C=z);let P=h.slice(O,C).trim();o.push({title:`[auto-memory] ${f.label}`,content:P,source:f.label,origin:"auto-memory",timestamp:p.mtime.toISOString()});break}}}catch(p){zE&&process.stderr.write(`[ctx] auto-memory file read failed: ${p}
|
|
521
|
+
`)}}return o.slice(0,e)}function LE(t,e){return e?KL(e)||!t?e:Ki(t,e):t??""}var zE,UE=v(()=>{"use strict";Kr();zE=process.env.DEBUG?.includes("context-mode")});function HE(t){let{query:e,limit:r,store:n,sort:s="relevance",source:o,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:d}=t,l=[],m=new Date().toISOString();try{let f=n.searchWithFallback(e,r,o,i);l.push(...f.map(p=>({title:p.title,content:p.content,source:p.source,origin:"current-session",timestamp:p.timestamp||m,rank:p.rank,matchLayer:p.matchLayer,highlighted:p.highlighted,contentType:p.contentType})))}catch(f){ly&&process.stderr.write(`[ctx] ContentStore search failed: ${f}
|
|
522
|
+
`)}if(s==="timeline"){try{if(a){let f=a.searchEvents(e,r,c||"",o);l.push(...f.map(p=>({title:`[${p.category}] ${p.type}`,content:p.data,source:"prior-session",origin:"prior-session",timestamp:p.created_at})))}}catch(f){ly&&process.stderr.write(`[ctx] SessionDB search failed: ${f}
|
|
523
|
+
`)}try{let f=FE([e],r,c,u,d);l.push(...f)}catch(f){ly&&process.stderr.write(`[ctx] auto-memory search failed: ${f}
|
|
524
|
+
`)}}for(let f of l)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return s==="timeline"&&l.sort((f,p)=>(f.timestamp||"").localeCompare(p.timestamp||"")),l.slice(0,r)}var ly,ZE=v(()=>{"use strict";UE();ly=process.env.DEBUG?.includes("context-mode")});import*as Tt from"node:fs";import*as py from"node:path";function dy(t){return t?/[/\\]\.claude[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function JL(t){if(!Tt.existsSync(t.projectsRoot))return;let e,r=0;try{for(let n of Tt.readdirSync(t.projectsRoot)){let s=py.join(t.projectsRoot,n),o;try{o=Tt.statSync(s)}catch{continue}if(!o.isDirectory())continue;let i;try{i=Tt.readdirSync(s)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=py.join(s,a);try{let u=Tt.statSync(c).mtimeMs;u>r&&(r=u,e=c)}catch{}}}}catch{return}if(e)try{let n=Tt.openSync(e,"r");try{let s=Buffer.alloc(8192),o=Tt.readSync(n,s,0,s.length,0),i=s.subarray(0,o).toString("utf-8");for(let a of i.split(`
|
|
525
|
+
`).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{Tt.closeSync(n)}}catch{}}function BE(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:s}=t,o=[e.CLAUDE_PROJECT_DIR,e.GEMINI_PROJECT_DIR,e.VSCODE_CWD,e.OPENCODE_PROJECT_DIR,e.PI_PROJECT_DIR,e.IDEA_INITIAL_DIRECTORY,e.CURSOR_CWD,e.CONTEXT_MODE_PROJECT_DIR];for(let i of o)if(i&&!dy(i))return i;if(s){let i=JL({projectsRoot:s});if(i&&!dy(i))return i}return n&&!dy(n)?n:r}var qE=v(()=>{"use strict"});import{execFileSync as YL}from"node:child_process";import{existsSync as ps,readdirSync as bo,statSync as XL}from"node:fs";import{homedir as Hu}from"node:os";import{join as Nt,sep as QL}from"node:path";function QE(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let s=0;s<3;s++){if((r[s]??0)>(n[s]??0))return!0;if((r[s]??0)<(n[s]??0))return!1}return!1}function tF(t){let e=t?.home??Hu();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([n,s])=>{let o=Nt(e,...s,"context-mode");return{name:n,sessionsDir:Nt(o,"sessions"),contentDir:Nt(o,"content")}})}function rF(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function Ji(t){let e=qe(),r=t?.sessionsDir??Nt(e,"context-mode","sessions"),n=t?.memoryRoot??Nt(e,"projects"),s=0,o=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(ps(r)){let f=[];try{f=bo(r).filter(p=>p.endsWith(".db"))}catch{}if(f.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():Qt()}catch{}if(p)for(let h of f){let g=Nt(r,h);try{let _=new p(g,{readonly:!0});try{let x=_.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),y=_.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();s+=x?.cnt??0,o+=y?.cnt??0;try{let b=_.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let w of b)w.category&&(u[w.category]=(u[w.category]??0)+(w.cnt??0))}catch{}try{let b=_.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();b?.bytes&&(i+=b.bytes)}catch{}try{let b=_.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(b?.t){let w=b.t.endsWith("Z")?b.t:b.t+"Z",O=Date.parse(w);Number.isFinite(O)&&O<a&&(a=O)}}catch{}try{let b=_.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let w of b)w.p&&c.add(w.p)}catch{}}finally{_.close()}}catch{}}}}let d=0,l=0,m={};if(ps(n)){let f=[];try{f=bo(n).filter(p=>{try{return XL(Nt(n,p)).isDirectory()}catch{return!1}})}catch{}for(let p of f){let h=Nt(n,p,"memory");if(!ps(h))continue;let g=[];try{g=bo(h).filter(_=>_.endsWith(".md"))}catch{continue}if(g.length!==0){l++,d+=g.length;for(let _ of g){let x=rF(_);m[x]=(m[x]??0)+1}}}}return{totalEvents:s,totalSessions:o,autoMemoryCount:d,autoMemoryProjects:l,autoMemoryByPrefix:m,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function e$(t){let e=t.sessionsDir??Nt(Hu(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!ps(e))return n;let s=[];try{s=bo(e).filter(y=>!(!y.endsWith(".db")||t.worktreeHash&&!y.startsWith(t.worktreeHash)))}catch{return n}if(s.length===0)return n;let o=null;try{o=t.loadDatabase?t.loadDatabase():Qt()}catch{return n}if(!o)return n;let i={},a=0,c=0,u=0,d=0,l=Number.POSITIVE_INFINITY,m=0,f=0,p=new Map,h=y=>Math.floor(y/864e5)*864e5;for(let y of s){let b=Nt(e,y),w=!1;try{let O=new o(b,{readonly:!0});try{let C=O.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let z of C)z.category&&(i[z.category]=(i[z.category]??0)+(z.cnt??0),a+=z.cnt??0,w=!0);let T=O.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(T?.mn){let z=Date.parse(T.mn+(T.mn.endsWith("Z")?"":"Z"));Number.isFinite(z)&&z<l&&(l=z)}if(T?.mx){let z=Date.parse(T.mx+(T.mx.endsWith("Z")?"":"Z"));Number.isFinite(z)&&z>m&&(m=z)}try{let z=O.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(r);for(let P of z){if(!P.sec)continue;let I=parseInt(P.sec,10)*1e3;if(!Number.isFinite(I))continue;let V=h(I),oe=p.get(V)??{count:0,rescueBytes:0};oe.count+=P.cnt??0,p.set(V,oe)}}catch{}try{let z=O.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(r);if(z?.bytes&&(u+=z.bytes),z?.n&&(d+=z.n),z?.lastSec){let P=parseInt(z.lastSec,10)*1e3;if(Number.isFinite(P)&&P>f&&(f=P),Number.isFinite(P)&&(z?.bytes??0)>0){let I=h(P),V=p.get(I)??{count:0,rescueBytes:0};V.rescueBytes=Math.max(V.rescueBytes,z.bytes),p.set(I,V)}}}catch{}}finally{O.close()}}catch{}w&&c++}let g=l<m?(m-l)/864e5:0,_=Object.entries(i).filter(([,y])=>y>0).map(([y,b])=>({category:y,count:b,label:Lu[y]||y})).sort((y,b)=>b.count-y.count),x=[...p.entries()].sort((y,b)=>y[0]-b[0]).map(([y,b])=>({ms:y,count:b.count,...b.rescueBytes>0?{rescueBytes:b.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:d,byCategory:_,firstEventMs:Number.isFinite(l)?l:0,lastEventMs:m>0?m:0,lastRescueMs:f>0?f:void 0,byDay:x}}function my(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,totalSavedTokens:0},r=t.sessionsDir??Nt(Hu(),".claude","context-mode","sessions");if(!ps(r))return e;let n=[];try{n=bo(r).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let s=null;try{s=t.loadDatabase?t.loadDatabase():Qt()}catch{return e}if(!s)return e;let o=0,i=0,a=0,c=0;for(let d of n){let l=Nt(r,d);try{let m=new s(l,{readonly:!0});try{if(t.sessionId){let f=m.prepare(`SELECT
|
|
526
526
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
527
527
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
528
528
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
@@ -530,41 +530,41 @@ ${s}`}}var yE=v(()=>{"use strict"});import{execFileSync as wL}from"node:child_pr
|
|
|
530
530
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
531
531
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
532
532
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
533
|
-
FROM session_events`).get();f&&(o+=Number(f.data_bytes??0),i+=Number(f.bytes_avoided??0),a+=Number(f.bytes_returned??0));try{let p=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();p?.bytes&&(c+=Number(p.bytes))}catch{}}}finally{m.close()}}catch{}}let u=Math.floor((o+i+c)/4);return{eventDataBytes:o,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,totalSavedTokens:u}}function GL(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(!ds(t.sessionsDir))return n;let s=[];try{s=xo(t.sessionsDir).filter(d=>d.endsWith(".db"))}catch{return n}if(s.length===0)return n;let o=null;try{o=e()}catch{return n}if(!o)return n;let i=new Set,a=new Set;for(let d of s){let l=At(t.sessionsDir,d);try{let m=new o(l,{readonly:!0});try{let f=m.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();f&&(n.eventCount+=Number(f.cnt??0),n.dataBytes+=Number(f.bytes??0));try{let p=m.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=m.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(n.rescueBytes+=Number(p.bytes))}catch{}try{let p=m.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let h=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h<n.firstMs&&(n.firstMs=h)}if(p?.mx){let h=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>n.lastMs&&(n.lastMs=h)}}catch{}try{let p=m.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let h of p)h.p&&i.add(h.p)}catch{}try{let p=m.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of p)h.s&&a.add(h.s)}catch{}}finally{m.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 Zu(t){let e=qL({home:t?.home}),r=t?.loadDatabase??Xt,n={...WL,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},s=[],o=0,i=0,a=0;for(let c of e){if(!ds(c.sessionsDir))continue;let u=GL(c,r,n);s.push(u),o+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:o,totalSessions:i,totalBytes:a,perAdapter:s}}function Fu(t){return KL[t]??t}function tt(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 JL(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 YL(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(!e){if(process.platform==="darwin")try{let n=UL("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-"))}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{locale:e||"en-US",tz:r||"UTC"}}function ZE(t){let e=Hu();return e?t===e?"~":t.startsWith(e+ZL)?"~"+t.slice(e.length):t:t}function XL(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*15/1e6,s=(h,g=2)=>h.toFixed(g),o=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,d=(e*3/1e6).toFixed(2),l=(e*2.5/1e6).toFixed(2),m=(e*1.25/1e6).toFixed(2),f=(e*.8/1e6).toFixed(2),p=[];return p.push(` $${s(n)} of Opus 4 tokens your team didn't burn.`),p.push(` context-mode kept ${tt(t)} out of context \u2014 that's ${o} months of Cursor Pro paid for itself.`),c>0&&u>0&&(p.push(""),p.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p.push(""),p.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)"),p}function QL(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:s,cwd:o,locale:i,tz:a,now:c,version:u,latestVersion:d}=t,l=[],m=e.events*GE,f=Math.round((e.snapshotBytes??0)/4),p=m+f,h=s?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(r?.totalEvents??0)*GE,x=Math.round((r?.rescueBytes??0)/4),_=y+x,b=s?.lifetime?.totalSavedTokens??0,w=Math.max(_,b),I=Math.max(1,Math.round(w*.02)),C=n?.totalBytes&&n.totalBytes>0?n.totalBytes:w*4,T=s?.conversation?s.conversation.eventDataBytes+s.conversation.bytesAvoided+s.conversation.snapshotBytes:g*4,z=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`,P=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,O=P>0?Math.max(1,Math.round((c-P)/864e5)):0,V=n?.totalSessions??r?.totalSessions??1,oe=n?.perAdapter.filter(Ze=>Ze.isReal).length??0,fe;if(n&&oe>=2)fe=`across ${oe} AI tools`;else if(n&&oe===1){let Ze=n.perAdapter.find(qr=>qr.isReal);fe=`in ${Ze?Fu(Ze.name):"Claude Code"}`}else fe="in Claude Code";O>0?l.push(` Across ${O} days you ran ${dr(V)} conversations ${fe}.`):l.push(` You ran ${dr(V)} conversations ${fe}.`);let yt=O>0?C/O:0;l.push(` context-mode kept ${tt(C)} out of your context window \u2014 about ${tt(yt)} every single day.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),l.push("");let Dt=e.firstEventMs&&e.firstEventMs>0?BE(e.firstEventMs,i,a):"";if(Dt?l.push(` This conversation started ${Dt} in ${ZE(o)}.`):l.push(` This conversation lives in ${ZE(o)}.`),l.push(` ${z}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ze=e.lastRescueMs&&e.lastRescueMs>0?BE(e.lastRescueMs,i,a):"",qr=Math.round(e.snapshotBytes/1024);Ze?l.push(` On ${Ze}, /compact fired \u2014 ${qr} KB rescued from snapshot.`):l.push(` /compact fired \u2014 ${qr} KB rescued from snapshot.`),l.push(" Without that, you'd be re-explaining everything to a blank model right now.")}l.push("");let _t=Math.max(1,Math.round(g*.02)),fs=vn(g,g,32),nl=vn(_t,g,32),sl=g>0?(1-_t/g)*100:0;if(l.push(` Without context-mode ${tt(T).padStart(8)} ${fs} ${dr(g).padStart(7)} tokens`),l.push(` With context-mode ${tt(Math.max(1,Math.round(T*.02))).padStart(8)} ${nl} ${dr(_t).padStart(7)} tokens`),l.push(` ${sl.toFixed(0)}% kept out of context \xB7 your AI ran ${Math.max(1,Math.round(g/_t))}\xD7 longer before /compact fired`),l.push(""),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;l.push(` How that ${tt(T)} built up \u2014 ${Ze} days, ${e.byDay.length} active:`),l.push(""),l.push(...tF(e.byDay,i,a))}l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),l.push("");let R$=e.byCategory.reduce((Ze,qr)=>Ze+qr.count,0).toLocaleString(i);l.push(` ${R$} things \u2014 files, errors, decisions, agent runs:`),l.push("");let C$=e.byCategory[0]?.count??1;for(let Ze of e.byCategory)l.push(` ${Ze.label.padEnd(26)} ${String(Ze.count).padStart(5)} ${vn(Ze.count,C$,28)}`);l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),l.push("");let Ty=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Py=P>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(P)):"",Ry=r?.distinctProjects??0,O$=r?.totalEvents??n?.totalEvents??0;if(l.push(` This chat: ${tt(T)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Ty?` \xB7 started ${Ty}`:""}.`),l.push(` All your work: ${tt(C)} kept out \xB7 ${O$.toLocaleString(i)} captures across ${Ry} project${Ry===1?"":"s"}${Py?` \xB7 since ${Py}`:""}.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),l.push(""),l.push(...XL(C,w,O)),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),l.push(""),r&&r.autoMemoryCount>0){l.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let Ze=Object.entries(r.autoMemoryByPrefix).sort((ra,na)=>na[1]-ra[1]),qr=Ze.length>0?Ze[0][1]:1;for(let[ra,na]of Ze){let A$=XE[ra]??ra;l.push(` ${A$.padEnd(26)} ${String(na).padStart(2)} ${vn(na,qr,20)}`)}}else l.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");l.push(""),l.push(""),l.push(" Your AI talks less, remembers more, costs less."),l.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),l.push("");let I$=u?`v${u}`:"context-mode";return l.push(` ${I$}`),u&&d&&d!=="unknown"&&JE(d,u)&&l.push(` Update available: v${u} -> v${d} | ctx_upgrade`),eF(l)}function eF(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 tF(t,e,r){if(t.length===0)return[];let n=[...t].sort((m,f)=>m.ms-f.ms),s=n[0],o=n[n.length-1],i=Math.max(1,o.ms-s.ms),a=n[0];for(let m of n)m.count>a.count&&(a=m);let c=56,u=Array.from({length:c},()=>"\u2500");for(let m of n){let f=Math.round((m.ms-s.ms)/i*(c-1)),p="\u25CF";m===a&&(p="\u2588"),(m.rescueBytes??0)>0&&(p="\u25C6"),u[f]=p}let d=m=>{let f=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(m)),p=(f.find(g=>g.type==="month")?.value??"").toLowerCase(),h=f.find(g=>g.type==="day")?.value??"";return`${p} ${h}`},l=[];l.push(` ${d(s.ms)} ${u.join("")} ${d(o.ms)}`),l.push("");for(let m of n){let f=d(m.ms).padEnd(7),p=`${m.count} captures`,h=m===a?" \u2190 peak":"",g=(m.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((m.rescueBytes??0)/1024)} KB`:"";l.push(` ${f} ${p}${h}${g}`)}return l.push(""),l.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),l}function BE(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let s=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),o=l=>s.find(m=>m.type===l)?.value??"",i=o("day"),a=o("month"),c=o("year"),u=o("hour"),d=o("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${d} (${r})`}function dr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Uu(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Bu).toFixed(2)}`}function vn(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 qE(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,s=[];s.push("");let o=e?.multiAdapter,i=o?.perAdapter.filter(h=>h.isReal).length??0,a=o?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=o?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let h=i>=2?" everywhere":"";s.push(` All your work${h} \xB7 ${dr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${dr(c)} conversations`)}else{s.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&r>0?1:c,g=h===1?"1 session":`${dr(h)} sessions`,y=a*256+r;s.push(` ${dr(a)} events \xB7 ${g} \xB7 ~${Uu(y)} saved lifetime`)}s.push("");let d=e?.lifetime?.categoryCounts,l;d&&Object.keys(d).length>0?l=Object.entries(d).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:Lu[h]||h})).sort((h,g)=>g.count-h.count):l=(t.by_category??[]).filter(h=>h&&h.count>0);let m=l.slice(0,n),f=m.length>0?m[0].count:1;for(let h of m)s.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${vn(h.count,f,30)}`);let p=Math.max(0,l.length-n);return p>0&&s.push(` ... ${p} more categor${p===1?"y":"ies"}`),s}function VE(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((s,o)=>o[1]-s[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[s,o]of r){let i=XE[s]??s;e.push(` ${i.padEnd(26)} ${String(o).padStart(2)} ${vn(o,n,20)}`)}return e}function WE(t,e){let r=[],n=Uu(t),s=(e?.totalEvents??0)*256+t,o=Uu(s);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${o} lifetime`),r.push("\u2500".repeat(65)),r}function KE(t){if(!t)return[];let e=t.perAdapter.filter(s=>s.isReal),r=t.perAdapter.filter(s=>!s.isReal);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 s=16,o=10,i=10,a=16;n.push(` ${"Tool".padEnd(s)}${"Captures".padStart(o)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,d)=>d.dataBytes+d.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let d=u.dataBytes+u.rescueBytes,l=u.eventCount>0?dr(u.eventCount):"\u2014",m=tt(u.dataBytes),f=tt(d);n.push(` ${Fu(u.name).padEnd(s)}${l.padStart(o)}${m.padStart(i)}${f.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let s=r.map(o=>Fu(o.name)).join(", ");n.push(` Skipped (${r.length}): ${s}`),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 qu(t,e,r,n){let s=[],o=JL(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,d=n?.multiAdapter,l=d?.perAdapter.filter(I=>I.isReal).length??0;if(d&&l>0){let I=d.totalSessions||i?.totalSessions||0,C=i?.firstEventMs??0,T=C>0?Math.max(1,Math.round((Date.now()-C)/864e5)):0,z=T>0?`Across ${T} day${T===1?"":"s"} `:"",P=I>0?`you ran ${dr(I)} conversation${I===1?"":"s"} `:"you ran ",O;if(l>=2)O=`across ${l} AI tools`;else{let V=d.perAdapter.find(oe=>oe.isReal);O=`in ${V?Fu(V.name):"Claude Code"}`}s.push(`${z}${P}${O}.`),s.push("")}if(c&&c.events>0){s.length>0&&(s.length=0);let I=YL(),C=n?.cwd??process.cwd(),T=n?.now??Date.now(),z=n?.locale??I.locale,P=n?.tz??I.tz;return s.push(...QL({conversation:c,lifetime:i,multiAdapter:d,realBytes:u,cwd:C,locale:z,tz:P,now:T,version:e,latestVersion:r})),s.join(`
|
|
534
|
-
`)}let m=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),f=t.savings.total_bytes_returned,p=t.savings.total_calls,h=m+f,g=h>0?m/h*100:0,
|
|
535
|
-
`)}s.push(`${
|
|
536
|
-
`)}var Lu,
|
|
533
|
+
FROM session_events`).get();f&&(o+=Number(f.data_bytes??0),i+=Number(f.bytes_avoided??0),a+=Number(f.bytes_returned??0));try{let p=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();p?.bytes&&(c+=Number(p.bytes))}catch{}}}finally{m.close()}}catch{}}let u=Math.floor((o+i+c)/4);return{eventDataBytes:o,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,totalSavedTokens:u}}function sF(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(!ps(t.sessionsDir))return n;let s=[];try{s=bo(t.sessionsDir).filter(d=>d.endsWith(".db"))}catch{return n}if(s.length===0)return n;let o=null;try{o=e()}catch{return n}if(!o)return n;let i=new Set,a=new Set;for(let d of s){let l=Nt(t.sessionsDir,d);try{let m=new o(l,{readonly:!0});try{let f=m.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();f&&(n.eventCount+=Number(f.cnt??0),n.dataBytes+=Number(f.bytes??0));try{let p=m.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=m.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(n.rescueBytes+=Number(p.bytes))}catch{}try{let p=m.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let h=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h<n.firstMs&&(n.firstMs=h)}if(p?.mx){let h=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>n.lastMs&&(n.lastMs=h)}}catch{}try{let p=m.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let h of p)h.p&&i.add(h.p)}catch{}try{let p=m.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of p)h.s&&a.add(h.s)}catch{}}finally{m.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 Zu(t){let e=tF({home:t?.home}),r=t?.loadDatabase??Qt,n={...nF,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},s=[],o=0,i=0,a=0;for(let c of e){if(!ps(c.sessionsDir))continue;let u=sF(c,r,n);s.push(u),o+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:o,totalSessions:i,totalBytes:a,perAdapter:s}}function Fu(t){return oF[t]??t}function tt(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 iF(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 aF(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(!e){if(process.platform==="darwin")try{let n=YL("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-"))}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{locale:e||"en-US",tz:r||"UTC"}}function VE(t){let e=Hu();return e?t===e?"~":t.startsWith(e+QL)?"~"+t.slice(e.length):t:t}function cF(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*15/1e6,s=(h,g=2)=>h.toFixed(g),o=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,d=(e*3/1e6).toFixed(2),l=(e*2.5/1e6).toFixed(2),m=(e*1.25/1e6).toFixed(2),f=(e*.8/1e6).toFixed(2),p=[];return p.push(` $${s(n)} of Opus 4 tokens your team didn't burn.`),p.push(` context-mode kept ${tt(t)} out of context \u2014 that's ${o} months of Cursor Pro paid for itself.`),c>0&&u>0&&(p.push(""),p.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p.push(""),p.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)"),p}function uF(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:s,cwd:o,locale:i,tz:a,now:c,version:u,latestVersion:d}=t,l=[],m=e.events*YE,f=Math.round((e.snapshotBytes??0)/4),p=m+f,h=s?.conversation?.totalSavedTokens??0,g=Math.max(p,h),_=(r?.totalEvents??0)*YE,x=Math.round((r?.rescueBytes??0)/4),y=_+x,b=s?.lifetime?.totalSavedTokens??0,w=Math.max(y,b),O=Math.max(1,Math.round(w*.02)),C=n?.totalBytes&&n.totalBytes>0?n.totalBytes:w*4,T=s?.conversation?s.conversation.eventDataBytes+s.conversation.bytesAvoided+s.conversation.snapshotBytes:g*4,z=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`,P=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,I=P>0?Math.max(1,Math.round((c-P)/864e5)):0,V=n?.totalSessions??r?.totalSessions??1,oe=n?.perAdapter.filter(Be=>Be.isReal).length??0,he;if(n&&oe>=2)he=`across ${oe} AI tools`;else if(n&&oe===1){let Be=n.perAdapter.find(Vr=>Vr.isReal);he=`in ${Be?Fu(Be.name):"Claude Code"}`}else he="in Claude Code";I>0?l.push(` Across ${I} days you ran ${mr(V)} conversations ${he}.`):l.push(` You ran ${mr(V)} conversations ${he}.`);let yt=I>0?C/I:0;l.push(` context-mode kept ${tt(C)} out of your context window \u2014 about ${tt(yt)} every single day.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),l.push("");let Mt=e.firstEventMs&&e.firstEventMs>0?WE(e.firstEventMs,i,a):"";if(Mt?l.push(` This conversation started ${Mt} in ${VE(o)}.`):l.push(` This conversation lives in ${VE(o)}.`),l.push(` ${z}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Be=e.lastRescueMs&&e.lastRescueMs>0?WE(e.lastRescueMs,i,a):"",Vr=Math.round(e.snapshotBytes/1024);Be?l.push(` On ${Be}, /compact fired \u2014 ${Vr} KB rescued from snapshot.`):l.push(` /compact fired \u2014 ${Vr} KB rescued from snapshot.`),l.push(" Without that, you'd be re-explaining everything to a blank model right now.")}l.push("");let _t=Math.max(1,Math.round(g*.02)),gs=bn(g,g,32),sl=bn(_t,g,32),ol=g>0?(1-_t/g)*100:0;if(l.push(` Without context-mode ${tt(T).padStart(8)} ${gs} ${mr(g).padStart(7)} tokens`),l.push(` With context-mode ${tt(Math.max(1,Math.round(T*.02))).padStart(8)} ${sl} ${mr(_t).padStart(7)} tokens`),l.push(` ${ol.toFixed(0)}% kept out of context \xB7 your AI ran ${Math.max(1,Math.round(g/_t))}\xD7 longer before /compact fired`),l.push(""),e.byDay&&e.byDay.length>0){let Be=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;l.push(` How that ${tt(T)} built up \u2014 ${Be} days, ${e.byDay.length} active:`),l.push(""),l.push(...dF(e.byDay,i,a))}l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),l.push("");let I$=e.byCategory.reduce((Be,Vr)=>Be+Vr.count,0).toLocaleString(i);l.push(` ${I$} things \u2014 files, errors, decisions, agent runs:`),l.push("");let A$=e.byCategory[0]?.count??1;for(let Be of e.byCategory)l.push(` ${Be.label.padEnd(26)} ${String(Be.count).padStart(5)} ${bn(Be.count,A$,28)}`);l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),l.push("");let Cy=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Oy=P>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(P)):"",Iy=r?.distinctProjects??0,N$=r?.totalEvents??n?.totalEvents??0;if(l.push(` This chat: ${tt(T)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Cy?` \xB7 started ${Cy}`:""}.`),l.push(` All your work: ${tt(C)} kept out \xB7 ${N$.toLocaleString(i)} captures across ${Iy} project${Iy===1?"":"s"}${Oy?` \xB7 since ${Oy}`:""}.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),l.push(""),l.push(...cF(C,w,I)),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),l.push(""),r&&r.autoMemoryCount>0){l.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let Be=Object.entries(r.autoMemoryByPrefix).sort((na,sa)=>sa[1]-na[1]),Vr=Be.length>0?Be[0][1]:1;for(let[na,sa]of Be){let M$=t$[na]??na;l.push(` ${M$.padEnd(26)} ${String(sa).padStart(2)} ${bn(sa,Vr,20)}`)}}else l.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");l.push(""),l.push(""),l.push(" Your AI talks less, remembers more, costs less."),l.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),l.push("");let D$=u?`v${u}`:"context-mode";return l.push(` ${D$}`),u&&d&&d!=="unknown"&&QE(d,u)&&l.push(` Update available: v${u} -> v${d} | ctx_upgrade`),lF(l)}function lF(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 dF(t,e,r){if(t.length===0)return[];let n=[...t].sort((m,f)=>m.ms-f.ms),s=n[0],o=n[n.length-1],i=Math.max(1,o.ms-s.ms),a=n[0];for(let m of n)m.count>a.count&&(a=m);let c=56,u=Array.from({length:c},()=>"\u2500");for(let m of n){let f=Math.round((m.ms-s.ms)/i*(c-1)),p="\u25CF";m===a&&(p="\u2588"),(m.rescueBytes??0)>0&&(p="\u25C6"),u[f]=p}let d=m=>{let f=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(m)),p=(f.find(g=>g.type==="month")?.value??"").toLowerCase(),h=f.find(g=>g.type==="day")?.value??"";return`${p} ${h}`},l=[];l.push(` ${d(s.ms)} ${u.join("")} ${d(o.ms)}`),l.push("");for(let m of n){let f=d(m.ms).padEnd(7),p=`${m.count} captures`,h=m===a?" \u2190 peak":"",g=(m.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((m.rescueBytes??0)/1024)} KB`:"";l.push(` ${f} ${p}${h}${g}`)}return l.push(""),l.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),l}function WE(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let s=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),o=l=>s.find(m=>m.type===l)?.value??"",i=o("day"),a=o("month"),c=o("year"),u=o("hour"),d=o("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${d} (${r})`}function mr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Uu(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Bu).toFixed(2)}`}function bn(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 GE(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,s=[];s.push("");let o=e?.multiAdapter,i=o?.perAdapter.filter(h=>h.isReal).length??0,a=o?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=o?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let h=i>=2?" everywhere":"";s.push(` All your work${h} \xB7 ${mr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${mr(c)} conversations`)}else{s.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&r>0?1:c,g=h===1?"1 session":`${mr(h)} sessions`,_=a*256+r;s.push(` ${mr(a)} events \xB7 ${g} \xB7 ~${Uu(_)} saved lifetime`)}s.push("");let d=e?.lifetime?.categoryCounts,l;d&&Object.keys(d).length>0?l=Object.entries(d).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:Lu[h]||h})).sort((h,g)=>g.count-h.count):l=(t.by_category??[]).filter(h=>h&&h.count>0);let m=l.slice(0,n),f=m.length>0?m[0].count:1;for(let h of m)s.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${bn(h.count,f,30)}`);let p=Math.max(0,l.length-n);return p>0&&s.push(` ... ${p} more categor${p===1?"y":"ies"}`),s}function KE(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((s,o)=>o[1]-s[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[s,o]of r){let i=t$[s]??s;e.push(` ${i.padEnd(26)} ${String(o).padStart(2)} ${bn(o,n,20)}`)}return e}function JE(t,e){let r=[],n=Uu(t),s=(e?.totalEvents??0)*256+t,o=Uu(s);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${o} lifetime`),r.push("\u2500".repeat(65)),r}function XE(t){if(!t)return[];let e=t.perAdapter.filter(s=>s.isReal),r=t.perAdapter.filter(s=>!s.isReal);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 s=16,o=10,i=10,a=16;n.push(` ${"Tool".padEnd(s)}${"Captures".padStart(o)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,d)=>d.dataBytes+d.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let d=u.dataBytes+u.rescueBytes,l=u.eventCount>0?mr(u.eventCount):"\u2014",m=tt(u.dataBytes),f=tt(d);n.push(` ${Fu(u.name).padEnd(s)}${l.padStart(o)}${m.padStart(i)}${f.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let s=r.map(o=>Fu(o.name)).join(", ");n.push(` Skipped (${r.length}): ${s}`),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 qu(t,e,r,n){let s=[],o=iF(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,d=n?.multiAdapter,l=d?.perAdapter.filter(O=>O.isReal).length??0;if(d&&l>0){let O=d.totalSessions||i?.totalSessions||0,C=i?.firstEventMs??0,T=C>0?Math.max(1,Math.round((Date.now()-C)/864e5)):0,z=T>0?`Across ${T} day${T===1?"":"s"} `:"",P=O>0?`you ran ${mr(O)} conversation${O===1?"":"s"} `:"you ran ",I;if(l>=2)I=`across ${l} AI tools`;else{let V=d.perAdapter.find(oe=>oe.isReal);I=`in ${V?Fu(V.name):"Claude Code"}`}s.push(`${z}${P}${I}.`),s.push("")}if(c&&c.events>0){s.length>0&&(s.length=0);let O=aF(),C=n?.cwd??process.cwd(),T=n?.now??Date.now(),z=n?.locale??O.locale,P=n?.tz??O.tz;return s.push(...uF({conversation:c,lifetime:i,multiAdapter:d,realBytes:u,cwd:C,locale:z,tz:P,now:T,version:e,latestVersion:r})),s.join(`
|
|
534
|
+
`)}let m=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),f=t.savings.total_bytes_returned,p=t.savings.total_calls,h=m+f,g=h>0?m/h*100:0,_=Math.round(m/4),x=f>0?Math.max(1,Math.round(h/Math.max(f,1))):0;if(m===0){s.push(`context-mode ${o} ${p} calls`),s.push(""),p===0?s.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):s.push(`${tt(f)} entered context | 0 tokens saved`),s.push(...GE(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:0})),s.push(...XE(d)),s.push(...KE(i)),s.push(...JE(0,i)),s.push("");let O=e?`v${e}`:"context-mode";return s.push(O),e&&r&&r!=="unknown"&&QE(r,e)&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
|
|
535
|
+
`)}s.push(`${mr(_)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${o} \xB7 ~${Uu(_)} saved (Opus)`),s.push(""),s.push(`Without context-mode |${bn(h,h)}| ${tt(h)}`),s.push(`With context-mode |${bn(f,h)}| ${tt(f)}`),s.push(""),x>=2?s.push(`${tt(m)} kept out of your conversation \u2014 ${x}\xD7 longer sessions before compact.`):s.push(`${tt(m)} kept out of your conversation. Never entered context.`),s.push("");let y=[`${p} calls`];t.cache&&t.cache.hits>0&&y.push(`${t.cache.hits} cache hits (+${tt(t.cache.bytes_saved)})`),s.push(y.join(" \xB7 "));let b=t.savings.by_tool.filter(O=>O.calls>0);if(b.length>=2){s.push("");let O=b.map(C=>{let T=C.context_kb*1024,z=g<100?T/(1-g/100):T,P=Math.max(0,z-T);return{...C,returnedBytes:T,estimatedSaved:P}}).sort((C,T)=>T.estimatedSaved-C.estimatedSaved);for(let C of O){let T=C.tool.length>22?C.tool.slice(0,19)+"...":C.tool;s.push(` ${T.padEnd(22)} ${String(C.calls).padStart(4)} calls ${tt(C.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let O=a.filter(C=>C.median_concurrency!=null&&(C.max_concurrency??1)>1);if(O.length>0){s.push(""),s.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let C of O){let T=C.tool_name.replace(/^mcp__.*?__/,"");s.push(` ${T.padEnd(22)} ${C.calls} batches \xB7 ${C.median_concurrency} typical, ${C.max_concurrency} peak`)}}}s.push(...GE(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:_})),s.push(...XE(d)),s.push(...KE(i)),s.push(...JE(_,i)),s.push("");let w=e?`v${e}`:"context-mode";return s.push(w),e&&r&&r!=="unknown"&&r!==e&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
|
|
536
|
+
`)}var Lu,eF,So,nF,t$,oF,Bu,YE,r$=v(()=>{"use strict";xo();Kr();Lu={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"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"},eF={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"},So=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,r){let n=e-r,s=e>0?Math.round(n/e*1e3)/10:0;return{rawBytes:e,contextBytes:r,savedBytes:n,savedPercent:s}}static thinkInCodeComparison(e,r){let n=r>0?Math.round(e/r*10)/10:0;return{fileBytes:e,outputBytes:r,ratio:n}}static toolSavings(e){return e.map(r=>({...r,savedBytes:r.rawBytes-r.contextBytes}))}static sandboxIO(e,r){return{inputBytes:e,outputBytes:r}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let r=new Map;for(let s of e){let o;try{o=JSON.parse(s.data)}catch{continue}let i=typeof o.tool_name=="string"?o.tool_name:null;if(!i)continue;let a=r.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,o.truncated!==!0&&o.params&&typeof o.params=="object"){let c=o.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}r.set(i,a)}let n=[];for(let[s,o]of r){let i=null,a=null;if(o.concurrencies.length>0){let c=[...o.concurrencies].sort((d,l)=>d-l),u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}n.push({tool_name:s,calls:o.calls,median_concurrency:i,max_concurrency:a})}return n.sort((s,o)=>o.calls-s.calls||s.tool_name.localeCompare(o.tool_name)),n}queryAll(e){let n=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",s=Object.values(e.bytesReturned).reduce((I,V)=>I+V,0),o=Object.values(e.calls).reduce((I,V)=>I+V,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+s,c=a/Math.max(s,1),u=a>0?Math.round((1-s/a)*100):0,d=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),l=Array.from(d).sort().map(I=>({tool:I,calls:e.calls[I]||0,context_kb:Math.round((e.bytesReturned[I]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[I]||0)/4)})),f=((Date.now()-e.sessionStart)/6e4).toFixed(1),p;if(e.cacheHits>0||e.cacheBytesSaved>0){let I=a+e.cacheBytesSaved,V=I/Math.max(s,1),oe=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3)));p={hits:e.cacheHits,bytes_saved:e.cacheBytesSaved,ttl_hours_left:oe,total_with_cache:I,total_savings_ratio:V}}let h=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(n).cnt,g=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(n),x=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,y=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),b=y?!y.consumed:!1,w=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),O=new Map;for(let I of w){O.has(I.category)||O.set(I.category,new Set);let V=O.get(I.category);if(V.size<5){let oe=I.data;I.category==="file"?oe=I.data.split("/").pop()||I.data:(I.category==="prompt"||I.category==="user-prompt")&&(oe=oe.length>50?oe.slice(0,47)+"...":oe),oe.length>40&&(oe=oe.slice(0,37)+"..."),V.add(oe)}}let C=g.map(I=>({category:I.category,count:I.cnt,label:Lu[I.category]||I.category,preview:O.get(I.category)?Array.from(O.get(I.category)).join(", "):"",why:eF[I.category]||"Survives context resets"})),T=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),P=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(I=>I.cnt>0).map(I=>({category:I.category,count:I.cnt,label:Lu[I.category]||I.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(s/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:l,total_calls:o,total_bytes_returned:s,kept_out:i,total_processed:a},cache:p,session:{id:n,uptime_min:f},continuity:{total_events:h,by_category:C,compact_count:x,resume_ready:b},projectMemory:{total_events:T.cnt,session_count:T.sessions,by_category:P}}}};nF={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};t$={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},oF={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};Bu=15/1e6;YE=256});var E$={};Fe(E$,{browserOpenArgv:()=>w$,buildBatchNodeOptionsPrefix:()=>v$,buildFetchCode:()=>k$,classifyIp:()=>el,extractSnippet:()=>$y,formatBatchQueryResults:()=>x$,killProcessOnPort:()=>Py,openBrowserSync:()=>vy,positionsFromHighlight:()=>_$,runBatchCommands:()=>b$});import{createRequire as m$}from"node:module";import{existsSync as ze,unlinkSync as Xi,readdirSync as pF,readFileSync as by,writeFileSync as Sy,renameSync as mF,rmSync as Ku,mkdirSync as Qi,cpSync as fF,statSync as n$,symlinkSync as hF,lstatSync as gF}from"node:fs";import{execSync as s$,spawnSync as f$}from"node:child_process";import{join as Ce,dirname as er,resolve as ut,sep as yF,isAbsolute as _F}from"node:path";import{fileURLToPath as xF}from"node:url";import{homedir as Qu,tmpdir as ky,cpus as vF}from"node:os";import{request as bF}from"node:https";function SF(t){try{let e=ct();if(!ze(e))return;let r=pF(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let s=Ce(e,n);try{t.index({path:s,source:"session-events"}),Xi(s)}catch{}}}catch{}}function yy(){return qe()}async function kF(){if(Sn)return Sn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(No(),xd)),e=nr();return await t(e.platform)}catch{return null}}function ct(){if(Sn)return Sn.getSessionDir();try{let e=nr(),r=_d(e.platform);if(r){let n=Ce(Qu(),...r);r.length===1&&r[0]===".claude"?n=yy():r.length===1&&r[0]===".codex"&&(n=va());let s=Ce(n,"context-mode","sessions");return Qi(s,{recursive:!0}),s}}catch{}let t=Ce(yy(),"context-mode","sessions");return Qi(t,{recursive:!0}),t}function gr(){let t;try{nr().platform==="claude-code"&&(t=Ce(Qu(),".claude","projects"))}catch{}return BE({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:t})}function wF(t){return _F(t)?t:ut(gr(),t)}function ea(){return ju({projectDir:gr(),sessionsDir:ct()})}function _y(){let t=Ce(er(ct()),"content");return Qi(t,{recursive:!0}),TE({projectDir:gr(),contentDir:t})}function fs(){if(!fr){let t=_y();fr=new Au(t),fr.setDenyChecker(e=>{try{let r=gr(),n=ey("Read",r);return ry(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=er(_y());Jg(e,14),fr.cleanupStaleSources(14);let r=Ce(Qu(),".context-mode","content");ze(r)&&Jg(r,0)}catch{}Kg()}return SF(fr),fr}async function i$(){return new Promise(t=>{let e=bF("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",s=>{n+=s}),r.on("end",()=>{try{let s=JSON.parse(n);t(s.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function TF(){let t=Sn?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function PF(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let s=0;s<3;s++){if((r[s]??0)>(n[s]??0))return!0;if((r[s]??0)<(n[s]??0))return!1}return!1}function RF(){return!Zr||Zr==="unknown"?!1:PF(Zr,Hr)}function CF(){if(!RF())return!1;let t=Date.now();if(Vu>=EF){if(t-o$<$F)return!1;Vu=0}return Vu===0&&(o$=t),Vu++,!0}function OF(){if(!a$){a$=!0;try{let t=qe(),e=ut(t,"plugins","installed_plugins.json");if(!ze(e))return;let r=JSON.parse(by(e,"utf-8")),n=ut(t,"plugins","cache"),s=ze(ut(Dt,"package.json"))?Dt:er(Dt);for(let[o,i]of Object.entries(r.plugins??{}))if(o==="context-mode@context-mode")for(let a of i){let c=a.installPath;if(!c||ze(c)||!ut(c).startsWith(n+yF))continue;try{gF(c).isSymbolicLink()&&Xi(c)}catch{}let u=er(c);ze(u)||Qi(u,{recursive:!0}),ze(s)&&hF(s,c,process.platform==="win32"?"junction":void 0)}}catch{}}}function K(t,e){if(OF(),CF()&&e.content.length>0){let n=TF();e.content[0].text=`\u26A0\uFE0F context-mode v${Hr} outdated \u2192 v${Zr} available. Upgrade: ${n}
|
|
537
537
|
|
|
538
|
-
`+e.content[0].text}let r=e.content.reduce((n,s)=>n+Buffer.byteLength(s.text),0);return se.calls[t]=(se.calls[t]||0)+1,se.bytesReturned[t]=(se.bytesReturned[t]||0)+r,Ju(),setImmediate(()=>
|
|
538
|
+
`+e.content[0].text}let r=e.content.reduce((n,s)=>n+Buffer.byteLength(s.text),0);return se.calls[t]=(se.calls[t]||0)+1,se.bytesReturned[t]=(se.bytesReturned[t]||0)+r,Ju(),setImmediate(()=>DE(ea(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>CE({sessionDbPath:ea(),toolName:t,bytesReturned:r})),e}function hr(t,e="unknown"){se.bytesIndexed+=t,Ju(),t>0&&setImmediate(()=>OE({sessionDbPath:ea(),source:e,bytesAvoided:t}))}function h$(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`;return Ce(ct(),`stats-${t}.json`)}function Ju(){let t=Date.now();if(!(t-xy<IF)){xy=t;try{let e=Object.values(se.bytesReturned).reduce((l,m)=>l+m,0),r=Object.values(se.calls).reduce((l,m)=>l+m,0),n=se.bytesIndexed+se.bytesSandboxed+se.cacheBytesSaved,s=n+e,o=s>0?Math.round((1-e/s)*100):0,i=Math.round(n/4),a=Wu?.tokens??0;if(!Wu||t-Wu.computedAt>NF)try{a=(Ji({sessionsDir:ct()})?.totalEvents??0)*DF,Wu={tokens:a,computedAt:t}}catch{}let c={schemaVersion:AF,version:Hr,updated_at:t,session_start:se.sessionStart,uptime_ms:t-se.sessionStart,total_calls:r,bytes_returned:e,bytes_indexed:se.bytesIndexed,bytes_sandboxed:se.bytesSandboxed,cache_hits:se.cacheHits,cache_bytes_saved:se.cacheBytesSaved,kept_out:n,total_processed:s,reduction_pct:o,tokens_saved:i,dollars_saved_session:+(i*Bu).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*Bu).toFixed(2),by_tool:Object.fromEntries(Object.keys({...se.calls,...se.bytesReturned}).map(l=>[l,{calls:se.calls[l]||0,bytes:se.bytesReturned[l]||0}]))},u=h$(),d=`${u}.tmp`;Sy(d,JSON.stringify(c)),mF(d,u)}catch{}}}function Ey(t,e){try{let r=Qg(process.env.CLAUDE_PROJECT_DIR),n=ty(t,r);if(n.decision==="deny")return K(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function g$(t,e,r){try{let n=_E(t,e);if(n.length===0)return null;let s=Qg(process.env.CLAUDE_PROJECT_DIR);for(let o of n){let i=ty(o,s);if(i.decision==="deny")return K(r,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${o}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function y$(t,e){try{let r=gr(),n=ey("Read",r),s=ry(t,n,process.platform==="win32",r);if(s.denied)return K(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${s.matchedPattern}`}],isError:!0})}catch{}return null}function _$(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===zF){for(e.push(r),n++;n<t.length&&t[n]!==LF;)r++,n++;n<t.length&&n++}else r++,n++;return e}function $y(t,e,r=1500,n){if(t.length<=r)return t;let s=[];if(n)for(let u of _$(n))s.push(u);if(s.length===0){let u=e.toLowerCase().split(/\s+/).filter(l=>l.length>2),d=t.toLowerCase();for(let l of u){let m=d.indexOf(l);for(;m!==-1;)s.push(m),m=d.indexOf(l,m+1)}}if(s.length===0)return t.slice(0,r)+`
|
|
539
539
|
\u2026`;s.sort((u,d)=>u-d);let o=300,i=[];for(let u of s){let d=Math.max(0,u-o),l=Math.min(t.length,u+o);i.length>0&&d<=i[i.length-1][1]?i[i.length-1][1]=l:i.push([d,l])}let a=[],c=0;for(let[u,d]of i){if(c>=r)break;let l=t.slice(u,Math.min(d,u+(r-c)));a.push((u>0?"\u2026":"")+l+(d<t.length?"\u2026":"")),c+=l.length}return a.join(`
|
|
540
540
|
|
|
541
|
-
`)}function
|
|
541
|
+
`)}function x$(t,e,r,n=80*1024){let s=[],o=0;for(let i of e){if(o>n){s.push(`## ${i}
|
|
542
542
|
(output cap reached \u2014 use ctx_search(queries: ["${i}"]) for details)
|
|
543
|
-
`);continue}let a=t.searchWithFallback(i,3,r,void 0,"exact");if(s.push(`## ${i}`),s.push(""),a.length>0){for(let c of a){let u
|
|
543
|
+
`);continue}let a=t.searchWithFallback(i,3,r,void 0,"exact");if(s.push(`## ${i}`),s.push(""),a.length>0){for(let c of a){let u=$y(c.content,i,3e3,c.highlighted);s.push(`### ${c.title}`),s.push(u),s.push(""),o+=u.length+c.title.length}continue}s.push("No matching sections found."),s.push("")}return s.push("\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])`."),s}function FF(t){return`'${t.replace(/'/g,"'\\''")}'`}function UF(t){return`'${t.replace(/'/g,"''")}'`}function v$(t,e){let r=`--require ${e}`,n=t.toLowerCase(),s=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${UF(r)}; `:s==="cmd"||s==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${FF(r)} `}function c$(t,e,r){let n=e||"(no output)",s=n.matchAll(/__CM_FS__:(\d+)/g),o=0;for(let i of s)o+=parseInt(i[1]);return o>0&&(r?.(o),n=n.replace(/__CM_FS__:\d+\n?/g,"")),`# ${t}
|
|
544
544
|
|
|
545
545
|
${n}
|
|
546
|
-
`}async function
|
|
546
|
+
`}async function b$(t,e,r){let{timeout:n,concurrency:s,nodeOptsPrefix:o,onFsBytes:i}=e;if(s<=1){let l=[],m=Date.now(),f=!1;for(let p=0;p<t.length;p++){let h=t[p],g;if(n!==void 0){let x=Date.now()-m,y=n-x;if(y<=0){l.push(`# ${h.label}
|
|
547
547
|
|
|
548
548
|
(skipped \u2014 batch timeout exceeded)
|
|
549
|
-
`),f=!0;continue}g=
|
|
549
|
+
`),f=!0;continue}g=y}let _=await r.execute({language:"shell",code:`${o}${h.command} 2>&1`,timeout:g});if(l.push(c$(h.label,_.stdout,i)),_.timedOut){f=!0;for(let x=p+1;x<t.length;x++)l.push(`# ${t[x].label}
|
|
550
550
|
|
|
551
551
|
(skipped \u2014 batch timeout exceeded)
|
|
552
|
-
`);break}}return{outputs:l,timedOut:f}}let a=t.map(l=>({run:async()=>{let m=await r.execute({language:"shell",code:`${o}${l.command} 2>&1`,timeout:n}),f=
|
|
552
|
+
`);break}}return{outputs:l,timedOut:f}}let a=t.map(l=>({run:async()=>{let m=await r.execute({language:"shell",code:`${o}${l.command} 2>&1`,timeout:n}),f=c$(l.label,m.stdout,i);return{output:m.timedOut?f.replace(/\n$/,"")+`
|
|
553
553
|
(timed out after ${n??"?"}ms)
|
|
554
|
-
`:f,timedOut:!!m.timedOut}}})),{settled:c}=await
|
|
554
|
+
`:f,timedOut:!!m.timedOut}}})),{settled:c}=await Zg(a,{concurrency:s}),u=new Array(t.length),d=!1;for(let l=0;l<c.length;l++){let m=c[l];if(m.status==="fulfilled")u[l]=m.value.output,m.value.timedOut&&(d=!0);else{let f=m.reason instanceof Error?m.reason.message:String(m.reason);u[l]=`# ${t[l].label}
|
|
555
555
|
|
|
556
556
|
(executor error: ${f})
|
|
557
|
-
`}}return{outputs:u,timedOut:d}}function
|
|
558
|
-
Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}function
|
|
559
|
-
`).length,o=Buffer.byteLength(t),i=
|
|
557
|
+
`}}return{outputs:u,timedOut:d}}function S$(t,e){let r=fs();hr(Buffer.byteLength(t));let n=r.index({content:t,source:e});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
|
|
558
|
+
Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}function ko(t,e,r,n=5){let s=t.split(`
|
|
559
|
+
`).length,o=Buffer.byteLength(t),i=fs(),a=i.indexPlainText(t,r),c=i.searchWithFallback(e,n,r),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let l=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`No sections matched intent "${e}" in ${s}-line output (${(o/1024).toFixed(1)}KB).`];return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to explore the indexed content."),l.join(`
|
|
560
560
|
`)}let d=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`${c.length} sections matched "${e}" (${s} lines, ${(o/1024).toFixed(1)}KB):`,""];for(let l of c){let m=l.content.split(`
|
|
561
561
|
`)[0].slice(0,120);d.push(` - ${l.title}: ${m}`)}return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to retrieve full content of any section."),d.join(`
|
|
562
|
-
`)}function
|
|
562
|
+
`)}function Ty(t){if(typeof t=="string")try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t}function ZF(t){let e=Ty(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}function BF(){return hy||(hy=m$(import.meta.url).resolve("turndown")),hy}function qF(){return gy||(gy=m$(import.meta.url).resolve("turndown-plugin-gfm")),gy}function k$(t,e){let r=JSON.stringify(BF()),n=JSON.stringify(qF()),s=JSON.stringify(e),o=el.toString(),i=process.env.CTX_FETCH_STRICT==="1";return`
|
|
563
563
|
const TurndownService = require(${r});
|
|
564
564
|
const { gfm } = require(${n});
|
|
565
565
|
const fs = require('fs');
|
|
566
|
-
const dns = require('
|
|
567
|
-
const dnsPromises = require('
|
|
566
|
+
const dns = require('no' + 'de:dns');
|
|
567
|
+
const dnsPromises = require('no' + 'de:dns/promises');
|
|
568
568
|
const url = ${JSON.stringify(t)};
|
|
569
569
|
const outputPath = ${s};
|
|
570
570
|
|
|
@@ -784,20 +784,20 @@ async function main() {
|
|
|
784
784
|
emit('text', text);
|
|
785
785
|
}
|
|
786
786
|
main();
|
|
787
|
-
`}async function
|
|
787
|
+
`}async function WF(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 r=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:n}=await import("node:dns/promises"),s=await n(e.hostname,{all:!0,verbatim:!0});for(let o of s){let i=el(o.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${o.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&r)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${o.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(n){return{kind:"fetch_error",url:t,error:`DNS lookup failed for "${e.hostname}": ${n instanceof Error?n.message:String(n)}`,reason:"exit"}}return null}function el(t){let e=t.indexOf("%"),r=e===-1?t:t.slice(0,e),n=r.toLowerCase();if(n.includes(":")){let a=n.match(/^::ffff:([\d.]+)$/);return a?el(a[1]):n==="::"||n.startsWith("fe8")||n.startsWith("fe9")||n.startsWith("fea")||n.startsWith("feb")||n.startsWith("ff")?"block":n==="::1"||n.startsWith("fc")||n.startsWith("fd")?"private":"public"}if(!r.includes("."))return"block";let s=r.split(".").map(a=>parseInt(a,10));if(s.length!==4||s.some(a=>isNaN(a)||a<0||a>255))return"block";let[o,i]=s;return o===169&&i===254||o===0||o>=224?"block":o===127||o===10||o===172&&i>=16&&i<=31||o===192&&i===168?"private":"public"}async function GF(t,e,r){let n=await WF(t);if(n)return n;if(!r){let o=fs(),i=Yg(e,t),a=o.getSourceMeta(i);if(a){let c=new Date(a.indexedAt+"Z"),u=Date.now()-c.getTime();if(u<VF){let d=Math.floor(u/36e5),l=Math.floor(u/(60*1e3)),m=d>0?`${d}h ago`:l>0?`${l}m ago`:"just now",f=a.chunkCount*1600;return{kind:"cached",label:a.label,chunkCount:a.chunkCount,estimatedBytes:f,ageStr:m}}}}let s=Ce(ky(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let o=k$(t,s),i=await ra.execute({language:"javascript",code:o,timeout:3e4});if(i.exitCode!==0)return{kind:"fetch_error",url:t,error:i.stderr||i.stdout||"unknown error",reason:"exit"};let a=(i.stdout||"").trim(),c;try{c=by(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return c.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:c,header:a}}catch(o){return{kind:"fetch_error",url:t,error:o instanceof Error?o.message:String(o),reason:"throw"}}finally{try{Ku(s)}catch{}}}function KF(t){let e=fs(),r=Yg(t.source,t.url),n;t.header==="__CM_CT__:json"?n=e.indexJSON(t.markdown,r):t.header==="__CM_CT__:text"?n=e.indexPlainText(t.markdown,r):n=e.index({content:t.markdown,source:r}),hr(Buffer.byteLength(t.markdown));let s=t.markdown.length>d$?t.markdown.slice(0,d$)+`
|
|
788
788
|
|
|
789
|
-
\u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:n.label,totalChunks:n.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function
|
|
790
|
-
${ma(
|
|
791
|
-
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash"))}var
|
|
789
|
+
\u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:n.label,totalChunks:n.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function p$(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function w$(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 vy(t,e=process.platform,r=f$){let n=w$(t,e),s=[];for(let{cmd:o,args:i}of n)try{let a=r(o,i,{stdio:"ignore",timeout:Yi});if(!a.error&&a.status===0)return{ok:!0,method:o};let c=a.error?.message??`status=${a.status===null?"signaled":a.status}`;s.push(`${o}: ${c}`)}catch(a){s.push(`${o}: ${a instanceof Error?a.message:String(a)}`)}return{ok:!1,method:"none",reason:s.join("; ")}}function Py(t,e=process.platform,r=f$){let n={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return n.errors.push(`invalid port: ${t}`),n;try{if(e==="win32"){let s=r("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Yi});if(s.error)return n.errors.push(`netstat: ${s.error.message}`),n;if(s.status!==0||typeof s.stdout!="string")return n;let o=`:${t}`,i=new Set;for(let a of s.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let d=u[0],l=u[1],m=u[2],f=u[u.length-1];d==="TCP"&&l.endsWith(o)&&(m!=="0.0.0.0:0"&&m!=="[::]:0"||/^\d+$/.test(f)&&i.add(f))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:Yi});c.error||c.status!==0?n.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):n.killedPids.push(a)}catch(c){n.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let s=r("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Yi});if(s.error)return n.errors.push(`lsof: ${s.error.message}`),n;if(s.status!==0||typeof s.stdout!="string")return n;let o=s.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of o){n.attemptedPids.push(i);try{let a=r("kill",[i],{stdio:"ignore",timeout:Yi});a.error||a.status!==0?n.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):n.killedPids.push(i)}catch(a){n.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(s){n.errors.push(s instanceof Error?s.message:String(s))}return n}async function JF(){let t=Kg();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?ky():"/tmp",r=Ce(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{ra.cleanupBackgrounded(),fr&&fr.close();try{Xi(wy)}catch{}try{Xi(r)}catch{}if(Ur&&Ur.pid&&!Ur.killed)try{Ur.kill("SIGTERM")}catch{}},s=async()=>{try{xy=0,Ju()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),bE({onShutdown:()=>s()});let o=new $u;await rt.connect(o);try{Sy(r,String(process.pid))}catch{}try{let{detectPlatform:i,getAdapter:a}=await Promise.resolve().then(()=>(No(),xd)),c=rt.server.getClientVersion(),u=i(c??void 0);Sn=await a(u.platform),c&&console.error(`MCP client: ${c.name} v${c.version} \u2192 ${u.platform}`)}catch{}try{let i=ME(ea());if(i){for(let[a,c]of Object.entries(i.calls))se.calls[a]=c;for(let[a,c]of Object.entries(i.bytesReturned))se.bytesReturned[a]=c;i.sessionStart>0&&(se.sessionStart=i.sessionStart)}}catch{}i$().then(i=>{i!=="unknown"&&(Zr=i)}),setInterval(()=>{i$().then(i=>{i!=="unknown"&&(Zr=i)})},3600*1e3).unref(),setInterval(()=>Ju(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${Hr} running on stdio`),console.error(`Detected runtimes:
|
|
790
|
+
${ma(ta)}`),vs()||(console.error(`
|
|
791
|
+
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var Dt,Hr,ta,Gu,rt,ra,wy,fr,Sn,Ur,se,Zr,Vu,o$,EF,$F,a$,IF,AF,NF,DF,xy,Wu,MF,jF,zF,LF,Yu,Xu,ms,fy,HF,u$,l$,hy,gy,VF,d$,Yi,$$=v(()=>{"use strict";Lw();Zw();Lg();Hg();Qw();mE();fE();xE();ha();vE();SE();Gi();RE();AE();jE();ZE();Jr();No();Bl();kl();Kr();qE();xo();r$();Qn();Dt=er(xF(import.meta.url)),Hr=(()=>{for(let t of["../package.json","./package.json"]){let e=ut(Dt,t);if(ze(e))try{return JSON.parse(by(e,"utf8")).version}catch{}}return"unknown"})();process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
|
|
792
792
|
`)});process.on("uncaughtException",t=>{process.stderr.write(`[context-mode] uncaughtException: ${t?.message??t}
|
|
793
|
-
`)});
|
|
794
|
-
`);
|
|
793
|
+
`)});ta=xs(),Gu=fa(ta),rt=new wu({name:"context-mode",version:Hr});rt.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});rt.server.setRequestHandler(Ws,async()=>({prompts:[]}));rt.server.setRequestHandler(qs,async()=>({resources:[]}));rt.server.setRequestHandler(Vs,async()=>({resourceTemplates:[]}));ra=new fo({runtimes:ta,projectRoot:()=>gr()}),wy=Ce(ky(),`cm-fs-preload-${process.pid}.js`);Sy(wy,`(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){}})();
|
|
794
|
+
`);fr=null;Sn=null,Ur=null;se={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheBytesSaved:0,sessionStart:Date.now()},Zr=null,Vu=0,o$=0,EF=3,$F=3600*1e3;a$=!1;IF=500,AF=2,NF=3e4,DF=256,xy=0;MF=Gu.join(", "),jF=vs()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",zF="",LF="";rt.registerTool("ctx_execute",{title:"Execute Code",description:`MANDATORY: Use for any command where output exceeds 20 lines. Execute code in a sandboxed subprocess. Only stdout enters context \u2014 raw data stays in the subprocess.${jF} Available: ${MF}.
|
|
795
795
|
|
|
796
796
|
PREFER THIS OVER BASH for: API calls (gh, curl, aws), test runners (npm test, pytest), git queries (git log, git diff), data processing, and ANY CLI command that may produce large output. Bash should only be used for file mutations, git writes, and navigation.
|
|
797
797
|
|
|
798
798
|
THINK IN CODE: When you need to analyze, count, filter, compare, or process data \u2014 write code that does the work and console.log() only the answer. Do NOT read raw data into context to process mentally. Program the analysis, don't compute it in your reasoning. Write robust, pure JavaScript (no npm dependencies). Use only Node.js built-ins (fs, path, child_process). Always wrap in try/catch. Handle null/undefined. Works on both Node.js and Bun.`,inputSchema:U.object({language:U.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir"]).describe("Runtime language"),code:U.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), or IO.puts (Elixir) to output a summary to context."),timeout:U.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:U.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."),intent:U.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'.
|
|
799
799
|
|
|
800
|
-
TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,intent:s})=>{if(t==="shell"){let o=
|
|
800
|
+
TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,intent:s})=>{if(t==="shell"){let o=Ey(e,"execute");if(o)return o}else{let o=g$(e,t,"execute");if(o)return o}try{let o=e;(t==="javascript"||t==="typescript")&&(o=`
|
|
801
801
|
// FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
|
|
802
802
|
let __cm_fs=0;
|
|
803
803
|
process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
|
|
@@ -856,18 +856,18 @@ ${e}
|
|
|
856
856
|
}
|
|
857
857
|
__cm_main().catch(e=>{console.error(e);process.exitCode=1});${n?`
|
|
858
858
|
setInterval(()=>{},2147483647);`:""}
|
|
859
|
-
})(typeof require!=='undefined'?require:null);`);let i=await
|
|
859
|
+
})(typeof require!=='undefined'?require:null);`);let i=await ra.execute({language:t,code:o,timeout:r,background:n}),a=i.stderr?.match(/__CM_NET__:(\d+)/);a&&(se.bytesSandboxed+=parseInt(a[1]),i.stderr=i.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let c=i.stderr?.match(/__CM_FS__:(\d+)/);if(c&&(se.bytesSandboxed+=parseInt(c[1]),i.stderr=i.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),i.timedOut){let d=i.stdout?.trim();return i.backgrounded&&d?K("ctx_execute",{content:[{type:"text",text:`${d}
|
|
860
860
|
|
|
861
861
|
_(process backgrounded after ${r}ms \u2014 still running)_`}]}):d?K("ctx_execute",{content:[{type:"text",text:`${d}
|
|
862
862
|
|
|
863
863
|
_(timed out after ${r}ms \u2014 partial output shown above)_`}]}):K("ctx_execute",{content:[{type:"text",text:`Execution timed out after ${r}ms
|
|
864
864
|
|
|
865
865
|
stderr:
|
|
866
|
-
${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:d,output:l}=
|
|
866
|
+
${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:d,output:l}=ny({language:t,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return s&&s.trim().length>0&&Buffer.byteLength(l)>Yu?(hr(Buffer.byteLength(l)),K("ctx_execute",{content:[{type:"text",text:ko(l,s,d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):Buffer.byteLength(l)>Xu?(hr(Buffer.byteLength(l)),K("ctx_execute",{content:[{type:"text",text:ko(l,"errors failures exceptions",d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):K("ctx_execute",{content:[{type:"text",text:l}],isError:d})}let u=i.stdout||"(no output)";return s&&s.trim().length>0&&Buffer.byteLength(u)>Yu?(hr(Buffer.byteLength(u)),K("ctx_execute",{content:[{type:"text",text:ko(u,s,`execute:${t}`)}]})):Buffer.byteLength(u)>Xu?K("ctx_execute",S$(u,`execute:${t}`)):K("ctx_execute",{content:[{type:"text",text:u}]})}catch(o){let i=o instanceof Error?o.message:String(o);return K("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});Yu=5e3,Xu=102400;rt.registerTool("ctx_execute_file",{title:"Execute File Processing",description:`Read a file and process it without loading contents into context. The file is read into a FILE_CONTENT variable inside the sandbox. Only your printed summary enters context.
|
|
867
867
|
|
|
868
868
|
PREFER THIS OVER Read/cat for: log files, data files (CSV, JSON, XML), large source files for analysis, and any file where you need to extract specific information rather than read the entire content.
|
|
869
869
|
|
|
870
|
-
THINK IN CODE: Write code that processes FILE_CONTENT and console.log() only the answer. Don't read files into context to analyze mentally. Write robust, pure JavaScript \u2014 no npm deps, try/catch, null-safe. Node.js + Bun compatible.`,inputSchema:U.object({path:U.string().describe("Absolute file path or relative to project root"),language:U.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir"]).describe("Runtime language"),code:U.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts."),timeout:U.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:U.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:r,timeout:n,intent:s})=>{let o=
|
|
870
|
+
THINK IN CODE: Write code that processes FILE_CONTENT and console.log() only the answer. Don't read files into context to analyze mentally. Write robust, pure JavaScript \u2014 no npm deps, try/catch, null-safe. Node.js + Bun compatible.`,inputSchema:U.object({path:U.string().describe("Absolute file path or relative to project root"),language:U.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir"]).describe("Runtime language"),code:U.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts."),timeout:U.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:U.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:r,timeout:n,intent:s})=>{let o=y$(t,"ctx_execute_file");if(o)return o;if(e==="shell"){let i=Ey(r,"execute_file");if(i)return i}else{let i=g$(r,e,"execute_file");if(i)return i}try{let i=await ra.executeFile({path:t,language:e,code:r,timeout:n});if(i.timedOut)return K("ctx_execute_file",{content:[{type:"text",text:`Timed out processing ${t} after ${n}ms`}],isError:!0});if(i.exitCode!==0){let{isError:c,output:u}=ny({language:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return s&&s.trim().length>0&&Buffer.byteLength(u)>Yu?(hr(Buffer.byteLength(u)),K("ctx_execute_file",{content:[{type:"text",text:ko(u,s,c?`file:${t}:error`:`file:${t}`)}],isError:c})):Buffer.byteLength(u)>Xu?(hr(Buffer.byteLength(u)),K("ctx_execute_file",{content:[{type:"text",text:ko(u,"errors failures exceptions",c?`file:${t}:error`:`file:${t}`)}],isError:c})):K("ctx_execute_file",{content:[{type:"text",text:u}],isError:c})}let a=i.stdout||"(no output)";return s&&s.trim().length>0&&Buffer.byteLength(a)>Yu?(hr(Buffer.byteLength(a)),K("ctx_execute_file",{content:[{type:"text",text:ko(a,s,`file:${t}`)}]})):Buffer.byteLength(a)>Xu?K("ctx_execute_file",S$(a,`file:${t}`)):K("ctx_execute_file",{content:[{type:"text",text:a}]})}catch(i){let a=i instanceof Error?i.message:String(i);return K("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});rt.registerTool("ctx_index",{title:"Index Content",description:`Index documentation or knowledge content into a searchable BM25 knowledge base. Chunks markdown by headings (keeping code blocks intact) and stores in ephemeral FTS5 database. The full content does NOT stay in context \u2014 only a brief summary is returned.
|
|
871
871
|
|
|
872
872
|
WHEN TO USE:
|
|
873
873
|
- Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
|
|
@@ -879,22 +879,22 @@ WHEN TO USE:
|
|
|
879
879
|
|
|
880
880
|
After indexing, use 'ctx_search' to retrieve specific sections on-demand.
|
|
881
881
|
When \`path\` is provided, a content hash is stored for automatic stale detection in search results.
|
|
882
|
-
Do NOT use for: log files, test output, CSV, build output \u2014 use 'ctx_execute_file' for those.`,inputSchema:U.object({content:U.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:U.string().optional().describe("File path to read and index (content never enters context). Provide this OR content."),source:U.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')")})},async({content:t,path:e,source:r})=>{if(!t&&!e)return K("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let n=
|
|
883
|
-
Use ctx_search(queries: ["..."]) to query this content. Use source: "${o.label}" to scope results.`}]})}catch(n){let s=n instanceof Error?n.message:String(n);return K("ctx_index",{content:[{type:"text",text:`Index error: ${s}`}],isError:!0})}});
|
|
882
|
+
Do NOT use for: log files, test output, CSV, build output \u2014 use 'ctx_execute_file' for those.`,inputSchema:U.object({content:U.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:U.string().optional().describe("File path to read and index (content never enters context). Provide this OR content."),source:U.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')")})},async({content:t,path:e,source:r})=>{if(!t&&!e)return K("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let n=y$(e,"ctx_index");if(n)return n}try{let n=e?wF(e):void 0;if(t)hr(Buffer.byteLength(t));else if(n)try{let i=await import("fs");hr(i.readFileSync(n).byteLength)}catch{}let o=fs().index({content:t,path:n,source:r??n});return K("ctx_index",{content:[{type:"text",text:`Indexed ${o.totalChunks} sections (${o.codeChunks} with code) from: ${o.label}
|
|
883
|
+
Use ctx_search(queries: ["..."]) to query this content. Use source: "${o.label}" to scope results.`}]})}catch(n){let s=n instanceof Error?n.message:String(n);return K("ctx_index",{content:[{type:"text",text:`Index error: ${s}`}],isError:!0})}});ms=0,fy=Date.now(),HF=6e4,u$=3,l$=8;rt.registerTool("ctx_search",{title:"Search Indexed Content",description:`Search indexed content. Requires prior indexing via ctx_batch_execute, ctx_index, or ctx_fetch_and_index. Pass ALL search questions as queries array in ONE call. File-backed sources are auto-refreshed when the source file changes.
|
|
884
884
|
|
|
885
885
|
TIPS: 2-4 specific terms per query. Use 'source' to scope results.
|
|
886
886
|
|
|
887
|
-
SESSION STATE: If skills, roles, or decisions were set earlier in this conversation, they are still active. Do not discard or contradict them.`,inputSchema:U.object({queries:U.preprocess(
|
|
887
|
+
SESSION STATE: If skills, roles, or decisions were set earlier in this conversation, they are still active. Do not discard or contradict them.`,inputSchema:U.object({queries:U.preprocess(Ty,U.array(U.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:U.number().optional().default(3).describe("Results per query (default: 3)"),source:U.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:U.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:U.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.")})},async t=>{try{let e=fs(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return K("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
|
|
888
888
|
|
|
889
889
|
ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
|
|
890
890
|
\u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
|
|
891
891
|
\u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
|
|
892
892
|
\u2022 ctx_index(content, source) \u2014 manually index text content
|
|
893
893
|
|
|
894
|
-
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,s=[];if(Array.isArray(n.queries)&&n.queries.length>0?s.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&s.push(n.query),s.length===0)return K("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:o=3,source:i,contentType:a}=t,c=Date.now();if(c-
|
|
894
|
+
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,s=[];if(Array.isArray(n.queries)&&n.queries.length>0?s.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&s.push(n.query),s.length===0)return K("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:o=3,source:i,contentType:a}=t,c=Date.now();if(c-fy>HF&&(ms=0,fy=c),ms++,ms>l$)return K("ctx_search",{content:[{type:"text",text:`BLOCKED: ${ms} search calls in ${Math.round((c-fy)/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 u=ms>u$?1:Math.min(o,2),d=40*1024,l=0,m=[],f=null;if(r==="timeline")try{let g=ct(),_=gr(),x=ju({projectDir:_,sessionsDir:g});ze(x)&&(f=new Fr({dbPath:x}))}catch{}let p=Sn?.getConfigDir()??yy();try{for(let g of s){if(l>d){m.push(`## ${g}
|
|
895
895
|
(output cap reached)
|
|
896
|
-
`);continue}let
|
|
897
|
-
No results found.`);continue}let x=
|
|
896
|
+
`);continue}let _;if(r==="timeline"?_=HE({query:g,limit:u,store:e,sort:r,source:i,contentType:a,sessionDB:f,projectDir:gr(),configDir:p,adapter:Sn??void 0}):_=e.searchWithFallback(g,u,i,a),_.length===0){m.push(`## ${g}
|
|
897
|
+
No results found.`);continue}let x=_.map((y,b)=>{let w=y.origin||"current-session",O=y.timestamp?y.timestamp.slice(0,16).replace("T"," "):"",C=`--- [${w}${O?" | "+O:""} | ${y.source}] ---`,T=`### ${y.title}`,z=$y(y.content,g,1500,y.highlighted);return`${C}
|
|
898
898
|
${T}
|
|
899
899
|
|
|
900
900
|
${z}`}).join(`
|
|
@@ -907,10 +907,10 @@ ${x}`),l+=x.length}}finally{try{f?.close()}catch{}}let h=m.join(`
|
|
|
907
907
|
|
|
908
908
|
`);if(e.lastRefreshCount>0&&(h=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
|
|
909
909
|
|
|
910
|
-
`+h),
|
|
910
|
+
`+h),ms>=u$&&(h+=`
|
|
911
911
|
|
|
912
|
-
\u26A0 search call #${
|
|
913
|
-
Indexed sources: ${g.map(x=>`"${x.label}" (${x.chunkCount} sections)`).join(", ")}`:"";return K("ctx_search",{content:[{type:"text",text:`No results found.${
|
|
912
|
+
\u26A0 search call #${ms}/${l$} in this window. Results limited to ${u}/query. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`),h.trim().length===0){let g=e.listSources(),_=g.length>0?`
|
|
913
|
+
Indexed sources: ${g.map(x=>`"${x.label}" (${x.chunkCount} sections)`).join(", ")}`:"";return K("ctx_search",{content:[{type:"text",text:`No results found.${_}`}]})}return K("ctx_search",{content:[{type:"text",text:h}]})}catch(e){let r=e instanceof Error?e.message:String(e);return K("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});hy=null,gy=null;VF=1440*60*1e3,d$=3072;rt.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",description:`Fetches URL content, converts HTML to markdown, indexes into searchable knowledge base, and returns a ~3KB preview. Full content stays in sandbox \u2014 use ctx_search() for deeper lookups.
|
|
914
914
|
|
|
915
915
|
Better than WebFetch: preview is immediate, full content is searchable, raw HTML never enters context.
|
|
916
916
|
|
|
@@ -920,15 +920,15 @@ PARALLELIZE I/O: For multi-URL research (library evaluation, migration scans, do
|
|
|
920
920
|
\u2705 Use concurrency: 4-8 for: library docs sweep, multi-changelog scan, competitive pricing pages, multi-region docs, GitHub raw file pulls.
|
|
921
921
|
\u274C Single URL \u2192 use the legacy {url, source} shape (concurrency irrelevant).
|
|
922
922
|
Example: requests: [{url: 'https://react.dev/...', source: 'react'}, {url: 'https://vuejs.org/...', source: 'vue'}], concurrency: 5.
|
|
923
|
-
Fetches parallelize up to your concurrency setting; FTS5 indexing serializes the writes after (SQLite single-writer rule).`,inputSchema:U.object({url:U.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:U.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:U.array(U.object({url:U.string().describe("URL to fetch"),source:U.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:U.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:U.boolean().optional().describe("Skip cache and re-fetch even if content was recently indexed")})},async({url:t,source:e,requests:r,concurrency:n,force:s})=>{let o=r||(t?[{url:t,source:e}]:[]);if(o.length===0)return K("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let i=!r&&o.length===1,a=n??1,c=o.map(P=>({run:()=>
|
|
923
|
+
Fetches parallelize up to your concurrency setting; FTS5 indexing serializes the writes after (SQLite single-writer rule).`,inputSchema:U.object({url:U.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:U.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:U.array(U.object({url:U.string().describe("URL to fetch"),source:U.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:U.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:U.boolean().optional().describe("Skip cache and re-fetch even if content was recently indexed")})},async({url:t,source:e,requests:r,concurrency:n,force:s})=>{let o=r||(t?[{url:t,source:e}]:[]);if(o.length===0)return K("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let i=!r&&o.length===1,a=n??1,c=o.map(P=>({run:()=>GF(P.url,P.source,s)})),{settled:u,effectiveConcurrency:d,capped:l}=await Zg(c,{concurrency:a,capByCpuCount:!i&&a>1}),m=[];for(let P=0;P<u.length;P++){let I=u[P];if(I.status==="rejected"){let oe=I.reason instanceof Error?I.reason.message:String(I.reason);m.push({kind:"job_error",url:o[P].url,error:oe});continue}let V=I.value;if(V.kind==="cached"){se.cacheHits++,se.cacheBytesSaved+=V.estimatedBytes;let oe=V.estimatedBytes,he=V.label;setImmediate(()=>IE({sessionDbPath:ea(),source:he,bytesAvoided:oe})),m.push({kind:"cached",label:V.label,chunkCount:V.chunkCount,ageStr:V.ageStr})}else V.kind==="fetch_error"?m.push({kind:"fetch_error",url:V.url,error:V.error,reason:V.reason}):m.push({kind:"fetched",indexed:KF(V)})}if(i){let P=m[0];if(P.kind==="cached")return K("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${P.label}** \u2014 ${P.chunkCount} sections, indexed ${P.ageStr} (fresh, TTL: 24h).
|
|
924
924
|
To refresh: call ctx_fetch_and_index again with \`force: true\`.
|
|
925
925
|
|
|
926
926
|
You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
|
|
927
|
-
Use: ctx_search(queries: [...], source: "${P.label}")`}]});if(P.kind==="fetched"){let
|
|
928
|
-
`);return K("ctx_fetch_and_index",{content:[{type:"text",text:V}]})}if(P.kind==="fetch_error"){let
|
|
927
|
+
Use: ctx_search(queries: [...], source: "${P.label}")`}]});if(P.kind==="fetched"){let I=(P.indexed.totalBytes/1024).toFixed(1),V=[`Fetched and indexed **${P.indexed.totalChunks} sections** (${I}KB) from: ${P.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${P.indexed.label}") for specific lookups.`,"","---","",P.indexed.preview].join(`
|
|
928
|
+
`);return K("ctx_fetch_and_index",{content:[{type:"text",text:V}]})}if(P.kind==="fetch_error"){let I=P.reason==="empty"?`Fetched ${P.url} but got empty content`:P.reason==="read"?`Fetched ${P.url} but could not read subprocess output`:P.reason==="exit"?`Failed to fetch ${P.url}: ${P.error}`:`Fetch error: ${P.error}`;return K("ctx_fetch_and_index",{content:[{type:"text",text:I}],isError:!0})}return K("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${P.error}`}],isError:!0})}let f=384,p=[],h=0,g=0,_=0,x=0,y=0,b=[];for(let P of m)if(P.kind==="cached")_++,p.push(`- [cache] ${P.label} \u2014 ${P.chunkCount} sections (${P.ageStr})`);else if(P.kind==="fetched"){x++,h+=P.indexed.totalChunks,g+=P.indexed.totalBytes;let I=(P.indexed.totalBytes/1024).toFixed(1);p.push(`- [new] ${P.indexed.label} \u2014 ${P.indexed.totalChunks} sections (${I}KB)`);let V=P.indexed.preview.length>f?P.indexed.preview.slice(0,f).trimEnd()+"\u2026":P.indexed.preview;b.push(`### ${P.indexed.label}
|
|
929
929
|
|
|
930
|
-
${V}`)}else
|
|
931
|
-
`);return K("ctx_fetch_and_index",{content:[{type:"text",text:z}],isError:
|
|
930
|
+
${V}`)}else y++,p.push(`- [err] ${P.url}: ${P.error}`);let w=(g/1024).toFixed(1),O=l?` cap=${d}/${vF().length}cpu`:"",C=(P,I,V)=>`${P} ${P===1?I:V}`,z=[`fetched ${o.length} c=${d}${O}. ok=${x} cache=${_} err=${y}. ${C(h,"section","sections")} ${w}KB.`,"",...p,"",'ctx_search(queries: [...], source: "<label>") for full content.',...b.length>0?["","---","",...b]:[]].join(`
|
|
931
|
+
`);return K("ctx_fetch_and_index",{content:[{type:"text",text:z}],isError:y===o.length})});rt.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",description:`Execute multiple commands in ONE call, auto-index all output, and search with multiple queries. Returns search results directly \u2014 no follow-up calls needed.
|
|
932
932
|
|
|
933
933
|
THIS IS THE PRIMARY TOOL. Use this instead of multiple ctx_execute() calls.
|
|
934
934
|
|
|
@@ -941,60 +941,69 @@ PARALLELIZE I/O: For I/O-bound batches (network calls, slow API queries, multi-U
|
|
|
941
941
|
Example: [gh issue view 1, gh issue view 2, gh issue view 3] \u2192 concurrency: 3.
|
|
942
942
|
Speedup depends on workload \u2014 applies to I/O wait, not CPU work.
|
|
943
943
|
|
|
944
|
-
THINK IN CODE \u2014 NON-NEGOTIABLE: When commands produce data you need to analyze, count, filter, compare, or transform \u2014 add a processing command that runs JavaScript and console.log() ONLY the answer. NEVER pull raw output into context to reason over. Concurrency parallelizes the FETCH; THINK IN CODE owns the PROCESSING. One programmed analysis replaces ten read-and-reason rounds. Pure JavaScript, Node.js built-ins (fs, path, child_process), try/catch, null-safe.`,inputSchema:U.object({commands:U.preprocess(
|
|
944
|
+
THINK IN CODE \u2014 NON-NEGOTIABLE: When commands produce data you need to analyze, count, filter, compare, or transform \u2014 add a processing command that runs JavaScript and console.log() ONLY the answer. NEVER pull raw output into context to reason over. Concurrency parallelizes the FETCH; THINK IN CODE owns the PROCESSING. One programmed analysis replaces ten read-and-reason rounds. Pure JavaScript, Node.js built-ins (fs, path, child_process), try/catch, null-safe.`,inputSchema:U.object({commands:U.preprocess(ZF,U.array(U.object({label:U.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:U.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:U.preprocess(Ty,U.array(U.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:U.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:U.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.")})},async({commands:t,queries:e,timeout:r,concurrency:n})=>{for(let s of t){let o=Ey(s.command,"batch_execute");if(o)return o}try{let s=v$(ta.shell,wy),{outputs:o,timedOut:i}=await b$(t,{timeout:r,concurrency:n,nodeOptsPrefix:s,onFsBytes:y=>{se.bytesSandboxed+=y}},ra),a=o.join(`
|
|
945
945
|
`),c=Buffer.byteLength(a),u=a.split(`
|
|
946
|
-
`).length;if(i&&o.length===0)return K("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});
|
|
947
|
-
Searchable terms for follow-up: ${
|
|
948
|
-
`);return K("ctx_batch_execute",{content:[{type:"text",text:x}]})}catch(s){let o=s instanceof Error?s.message:String(s);return K("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${o}`}],isError:!0})}});rt.registerTool("ctx_stats",{title:"Session Statistics",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:U.object({})},async()=>{let t;try{let e=
|
|
949
|
-
`)}]})});rt.registerTool("ctx_upgrade",{title:"Upgrade Plugin",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:U.object({})},async()=>{let t=ze(ut(
|
|
950
|
-
`),a=ut(t,".ctx-upgrade-inline.mjs"),{writeFileSync:c}=await import("node:fs");c(a,i),n=
|
|
951
|
-
`);return K("ctx_upgrade",{content:[{type:"text",text:s}]})});rt.registerTool("ctx_purge",{title:"Purge Knowledge Base",description:"Permanently deletes ALL session data for this project: FTS5 knowledge base (indexed content), session events DB (analytics, metadata, resume snapshots), and session events markdown. Resets in-memory stats. This is irreversible.",inputSchema:U.object({confirm:U.boolean().describe("Must be true to confirm the destructive operation.")})},async({confirm:t})=>{if(!t)return K("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let e;try{e=
|
|
946
|
+
`).length;if(i&&o.length===0)return K("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});hr(c);let d=fs(),l=`batch:${t.map(y=>y.label).join(",").slice(0,80)}`,m=d.index({content:a,source:l}),f=d.getChunksBySource(m.sourceId),p=["## Indexed Sections",""],h=[];for(let y of f){let b=Buffer.byteLength(y.content);p.push(`- ${y.title} (${(b/1024).toFixed(1)}KB)`),h.push(y.title)}let g=x$(d,e,l),_=d.getDistinctiveTerms?d.getDistinctiveTerms(m.sourceId):[],x=[`Executed ${t.length} commands (${u} lines, ${(c/1024).toFixed(1)}KB). Indexed ${m.totalChunks} sections. Searched ${e.length} queries.`,"",...p,"",...g,_.length>0?`
|
|
947
|
+
Searchable terms for follow-up: ${_.join(", ")}`:""].join(`
|
|
948
|
+
`);return K("ctx_batch_execute",{content:[{type:"text",text:x}]})}catch(s){let o=s instanceof Error?s.message:String(s);return K("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${o}`}],isError:!0})}});rt.registerTool("ctx_stats",{title:"Session Statistics",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:U.object({})},async()=>{let t;try{let e=gr(),r=ds(e),n=ju({projectDir:e,sessionsDir:ct()});if(ze(n)){let s=Qt(),o=new s(n,{readonly:!0});try{let i=new So(o),a=i.queryAll(se),c=i.getMcpToolUsage(),u=Ji({sessionsDir:ct()}),d;try{d=Zu()}catch{}let l,m;try{let f=process.env.CLAUDE_SESSION_ID;if(f||(f=o.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),f){l=e$({sessionId:f,sessionsDir:ct(),worktreeHash:r});let p=my({sessionId:f,sessionsDir:ct(),worktreeHash:r}),h=my({sessionsDir:ct()});m={conversation:p,lifetime:h}}}catch{}t=qu(a,Hr,Zr,{lifetime:u,mcpUsage:c,multiAdapter:d,conversation:l,realBytes:m,cwd:e})}finally{o.close()}}else{let o=new So(p$()).queryAll(se),i=Ji({sessionsDir:ct()}),a;try{a=Zu()}catch{}t=qu(o,Hr,Zr,{lifetime:i,multiAdapter:a})}}catch{let r=new So(p$()).queryAll(se),n;try{n=Ji({sessionsDir:ct()})}catch{}let s;try{s=Zu()}catch{}t=qu(r,Hr,Zr,n||s?{lifetime:n,multiAdapter:s}:void 0)}return K("ctx_stats",{content:[{type:"text",text:t}]})});rt.registerTool("ctx_doctor",{title:"Run Diagnostics",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:U.object({})},async()=>{let t=["context-mode doctor",""],e=ze(ut(Dt,"package.json"))?Dt:er(Dt),r=11,n=(Gu.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${Gu.length}/${r} (${n}%) \u2014 ${Gu.join(", ")}`),vs()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");{let o=new fo({runtimes:ta});try{let i=await o.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(i.exitCode===0&&i.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let a=i.stderr?.trim()?` (${i.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${i.exitCode}${a}`)}}catch(i){t.push(`[FAIL] Server test: FAIL \u2014 ${i instanceof Error?i.message:i}`)}finally{o.cleanupBackgrounded()}}{let o;try{let i=Qt();o=new i(":memory:"),o.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),o.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let a=o.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();a&&a.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(i){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${i instanceof Error?i.message:i}`)}finally{try{o?.close()}catch{}}}let s=await kF();if(s){for(let i of s.validateHooks(e)){let a=i.status==="pass"?"[OK]":i.status==="warn"?"[WARN]":"[FAIL]",c=i.fix?` \u2014 fix: ${i.fix}`:"";t.push(`${a} ${i.check}: ${i.message}${c}`)}let o=ga(s,e);o.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let i of o){let a=ut(e,i);ze(a)?t.push(`[OK] Hook script: PASS \u2014 ${a}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${a}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${Hr}`),K("ctx_doctor",{content:[{type:"text",text:t.join(`
|
|
949
|
+
`)}]})});rt.registerTool("ctx_upgrade",{title:"Upgrade Plugin",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:U.object({})},async()=>{let t=ze(ut(Dt,"package.json"))?Dt:er(Dt),e=ut(t,"cli.bundle.mjs"),r=ut(t,"build","cli.js");try{let o=ct(),i=Ce(er(o),"insight-cache");ze(i)&&(Py(4747),Ku(i,{recursive:!0,force:!0}))}catch{}let n;if(ze(e))n=`${Ue(e)} upgrade`;else if(ze(r))n=`${Ue(r)} upgrade`;else{let i=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync}from"node:fs";','import{join}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(t)};`,'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"];',"for(const item of items){const from=join(T,item);const to=join(P,item);if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true});}}",'writeFileSync(join(P,".mcp.json"),JSON.stringify({mcpServers:{"context-mode":{command:"node",args:["${CLAUDE_PLUGIN_ROOT}/start.mjs"]}}},null,2)+"\\n");','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(`
|
|
950
|
+
`),a=ut(t,".ctx-upgrade-inline.mjs"),{writeFileSync:c}=await import("node:fs");c(a,i),n=Ue(a)}let s=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",n,"```","","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(`
|
|
951
|
+
`);return K("ctx_upgrade",{content:[{type:"text",text:s}]})});rt.registerTool("ctx_purge",{title:"Purge Knowledge Base",description:"Permanently deletes ALL session data for this project: FTS5 knowledge base (indexed content), session events DB (analytics, metadata, resume snapshots), and session events markdown. Resets in-memory stats. This is irreversible.",inputSchema:U.object({confirm:U.boolean().describe("Must be true to confirm the destructive operation.")})},async({confirm:t})=>{if(!t)return K("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let e;try{e=_y()}catch{}if(fr){try{fr.cleanup()}catch{}fr=null}let r=e?er(e):void 0,{deleted:n}=PE({projectDir:gr(),sessionsDir:ct(),storePath:e,contentDir:r,legacyContentDir:Ce(Qu(),".context-mode","content"),contentHash:ls(gr())});se.calls={},se.bytesReturned={},se.bytesIndexed=0,se.bytesSandboxed=0,se.cacheHits=0,se.cacheBytesSaved=0,se.sessionStart=Date.now(),n.push("session stats");try{let s=h$();ze(s)&&Xi(s)}catch{}return K("ctx_purge",{content:[{type:"text",text:`Purged: ${n.join(", ")}. All session data for this project has been permanently deleted.`}]})});Yi=5e3;rt.registerTool("ctx_insight",{title:"Open Insight Dashboard",description:"Opens the context-mode Insight dashboard in the browser. Shows personal analytics: session activity, tool usage, error rate, parallel work patterns, project focus, and actionable insights. First run installs dependencies (~30s). Subsequent runs open instantly.",inputSchema:U.object({port:U.coerce.number().int().min(1).max(65535).optional().describe("Port to serve on (default: 4747)"),sessionDir:U.string().optional().describe("Override INSIGHT_SESSION_DIR: directory containing context-mode session .db files"),contentDir:U.string().optional().describe("Override INSIGHT_CONTENT_DIR: directory containing context-mode content/index .db files"),insightSessionDir:U.string().optional().describe("Alias for sessionDir / INSIGHT_SESSION_DIR"),insightContentDir:U.string().optional().describe("Alias for contentDir / INSIGHT_CONTENT_DIR")})},async({port:t,sessionDir:e,contentDir:r,insightSessionDir:n,insightContentDir:s})=>{let o=t||4747,i=e||n,a=r||s,c=ze(ut(Dt,"package.json"))?Dt:er(Dt),u=ut(c,"insight"),d=i?ut(i):ct(),l=a?ut(a):Ce(er(d),"content"),m=Ce(er(d),"insight-cache");if(!ze(Ce(u,"server.mjs")))return K("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let f=[],p=!1;Qi(m,{recursive:!0});let h=n$(Ce(u,"server.mjs")).mtimeMs,g=ze(Ce(m,"server.mjs"))?n$(Ce(m,"server.mjs")).mtimeMs:0;if(h>g&&(f.push("Copying source files..."),fF(u,m,{recursive:!0,force:!0}),f.push("Source files copied."),p=!0),!ze(Ce(m,"node_modules"))||p){f.push("Installing dependencies (first run, ~30s)...");try{s$(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:m,stdio:"pipe",timeout:3e5})}catch{try{Ku(Ce(m,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!ze(Ce(m,"node_modules","vite"))||!ze(Ce(m,"node_modules","better-sqlite3")))throw Ku(Ce(m,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");f.push("Dependencies installed.")}f.push("Building dashboard..."),s$("npx vite build",{cwd:m,stdio:"pipe",timeout:6e4}),f.push("Build complete.");let x=!1;try{let{request:T}=await import("node:http");await new Promise((z,P)=>{let I=T(`http://127.0.0.1:${o}/api/overview`,{timeout:2e3},V=>{V.resume(),z()});I.on("error",()=>P()),I.on("timeout",()=>{I.destroy(),P()}),I.end()}),x=!0}catch{}if(x&&p){f.push("Killing stale dashboard server (source updated)...");let T=Py(o);if(T.attemptedPids.length>0&&T.killedPids.length===0)return K("ctx_insight",{content:[{type:"text",text:`Could not free port ${o} (kill failed for ${T.attemptedPids.join(", ")}: ${T.errors.join("; ")}). Try ctx_insight({ port: ${o+1} }) or stop the process manually.`}]});if(T.errors.length>0&&T.attemptedPids.length===0)return K("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${o}: ${T.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(z=>setTimeout(z,500)),f.push(`Stale server killed (${T.killedPids.length} pid${T.killedPids.length===1?"":"s"}).`)}else if(x){f.push("Dashboard already running.");let T=`http://localhost:${o}`,z=vy(T),P=z.ok?"":` (auto-open failed: ${z.reason}; navigate manually)`;return K("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${T}${P}`}]})}if(Ur&&Ur.pid&&!Ur.killed)try{Ur.kill("SIGTERM")}catch{}let{spawn:y}=await import("node:child_process"),b=y("node",[Ce(m,"server.mjs")],{cwd:m,env:{...process.env,PORT:String(o),INSIGHT_SESSION_DIR:d,INSIGHT_CONTENT_DIR:l,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});b.on("error",()=>{}),b.unref(),Ur=b,await new Promise(T=>setTimeout(T,1500));try{let{request:T}=await import("node:http");await new Promise((z,P)=>{let I=T(`http://127.0.0.1:${o}/api/overview`,{timeout:3e3},V=>{z(),V.resume()});I.on("error",P),I.on("timeout",()=>{I.destroy(),P(new Error("timeout"))}),I.end()})}catch{return K("ctx_insight",{content:[{type:"text",text:`Port ${o} appears to be in use. Either a previous dashboard is still running, or another service is using this port.
|
|
952
952
|
|
|
953
953
|
To fix:
|
|
954
954
|
- Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${o}`:`lsof -ti:${o} | xargs kill`}
|
|
955
|
-
- Or use a different port: ctx_insight({ port: ${o+1} })`}]})}let w=`http://localhost:${o}`,
|
|
955
|
+
- Or use a different port: ctx_insight({ port: ${o+1} })`}]})}let w=`http://localhost:${o}`,O=vy(w),C=O.ok?"":` (auto-open failed: ${O.reason}; navigate manually)`;return f.push(`Dashboard running at ${w}${C}`),K("ctx_insight",{content:[{type:"text",text:f.map(T=>`- ${T}`).join(`
|
|
956
956
|
`)+`
|
|
957
957
|
|
|
958
958
|
Open: ${w}
|
|
959
|
-
PID: ${b.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${b.pid} /F`:`kill ${b.pid}`}`}]})}catch(f){let p=f instanceof Error?f.message:String(f);return K("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${p}`}]})}});
|
|
960
|
-
`),d=!1;for(let l=0;l<u.length;l++){let m=u[l];if(n+=m,!d)d=m>="\uD800"&&m<="\uDBFF";else continue;if(m===ca||m===
|
|
961
|
-
`){o&&(n+=
|
|
962
|
-
`&&(s&&
|
|
963
|
-
`)}var
|
|
959
|
+
PID: ${b.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${b.pid} /F`:`kill ${b.pid}`}`}]})}catch(f){let p=f instanceof Error?f.message:String(f);return K("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${p}`}]})}});JF().catch(t=>{console.error("Fatal:",t),process.exit(1)})});import{stdout as eT,stdin as tT}from"node:process";import*as Wr from"node:readline";var Ay=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,Ny=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Dy=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 al=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,oa=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ia=/\t{1,1000}/y,cl=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"),aa=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Z$=new RegExp("\\p{M}+","gu"),B$={limit:1/0,ellipsis:""},My=(t,e={},r={})=>{let n=e.limit??1/0,s=e.ellipsis??"",o=e?.ellipsisWidth??(s?My(s,B$,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,d=r.emojiWidth??2,l=r.fullWidthWidth??2,m=r.regularWidth??1,f=r.wideWidth??2,p=0,h=0,g=t.length,_=0,x=!1,y=g,b=Math.max(0,n-o),w=0,O=0,C=0,T=0;e:for(;;){if(O>w||h>=g&&h>p){let z=t.slice(w,O)||t.slice(p,h);_=0;for(let P of z.replaceAll(Z$,"")){let I=P.codePointAt(0)||0;if(Ny(I)?T=l:Dy(I)?T=f:u!==m&&Ay(I)?T=u:T=m,C+T>b&&(y=Math.min(y,Math.max(w,p)+_)),C+T>n){x=!0;break e}_+=P.length,C+=T}w=O=0}if(h>=g)break;if(aa.lastIndex=h,aa.test(t)){if(_=aa.lastIndex-h,T=_*m,C+T>b&&(y=Math.min(y,h+Math.floor((b-C)/m))),C+T>n){x=!0;break}C+=T,w=p,O=h,h=p=aa.lastIndex;continue}if(al.lastIndex=h,al.test(t)){if(C+i>b&&(y=Math.min(y,h)),C+i>n){x=!0;break}C+=i,w=p,O=h,h=p=al.lastIndex;continue}if(oa.lastIndex=h,oa.test(t)){if(_=oa.lastIndex-h,T=_*a,C+T>b&&(y=Math.min(y,h+Math.floor((b-C)/a))),C+T>n){x=!0;break}C+=T,w=p,O=h,h=p=oa.lastIndex;continue}if(ia.lastIndex=h,ia.test(t)){if(_=ia.lastIndex-h,T=_*c,C+T>b&&(y=Math.min(y,h+Math.floor((b-C)/c))),C+T>n){x=!0;break}C+=T,w=p,O=h,h=p=ia.lastIndex;continue}if(cl.lastIndex=h,cl.test(t)){if(C+d>b&&(y=Math.min(y,h)),C+d>n){x=!0;break}C+=d,w=p,O=h,h=p=cl.lastIndex;continue}h+=1}return{width:x?b:C,index:x?y:g,truncated:x,ellipsed:x&&n>=o}},jy=My;var q$={limit:1/0,ellipsis:"",ellipsisWidth:0},V$=(t,e={})=>jy(t,q$,e).width,lt=V$;var ca="\x1B",Hy="\x9B",W$=39,ll="\x07",Zy="[",G$="]",By="m",dl=`${G$}8;;`,zy=new RegExp(`(?:\\${Zy}(?<code>\\d+)m|\\${dl}(?<uri>.*)${ll})`,"y"),Ly=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},Fy=t=>`${ca}${Zy}${t}${By}`,Uy=t=>`${ca}${dl}${t}${ll}`,ul=(t,e,r)=>{let n=e[Symbol.iterator](),s=!1,o=!1,i=t.at(-1),a=i===void 0?0:lt(i),c=n.next(),u=n.next(),d=0;for(;!c.done;){let l=c.value,m=lt(l);a+m<=r?t[t.length-1]+=l:(t.push(l),a=0),(l===ca||l===Hy)&&(s=!0,o=e.startsWith(dl,d+1)),s?o?l===ll&&(s=!1,o=!1):l===By&&(s=!1):(a+=m,a===r&&!u.done&&(t.push(""),a=0)),c=u,u=n.next(),d+=l.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},K$=t=>{let e=t.split(" "),r=e.length;for(;r&&!lt(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},J$=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",s,o,i=t.split(" "),a=[""],c=0;for(let l=0;l<i.length;l++){let m=i[l];if(r.trim!==!1){let p=a.at(-1)??"",h=p.trimStart();p.length!==h.length&&(a[a.length-1]=h,c=lt(h))}l!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let f=lt(m);if(r.hard&&f>e){let p=e-c,h=1+Math.floor((f-p-1)/e);Math.floor((f-1)/e)<h&&a.push(""),ul(a,m,e),c=lt(a.at(-1)??"");continue}if(c+f>e&&c&&f){if(r.wordWrap===!1&&c<e){ul(a,m,e),c=lt(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>e&&r.wordWrap===!1){ul(a,m,e),c=lt(a.at(-1)??"");continue}a[a.length-1]+=m,c+=f}r.trim!==!1&&(a=a.map(l=>K$(l)));let u=a.join(`
|
|
960
|
+
`),d=!1;for(let l=0;l<u.length;l++){let m=u[l];if(n+=m,!d)d=m>="\uD800"&&m<="\uDBFF";else continue;if(m===ca||m===Hy){zy.lastIndex=l+1;let p=zy.exec(u)?.groups;if(p?.code!==void 0){let h=Number.parseFloat(p.code);s=h===W$?void 0:h}else p?.uri!==void 0&&(o=p.uri.length===0?void 0:p.uri)}if(u[l+1]===`
|
|
961
|
+
`){o&&(n+=Uy(""));let f=s?Ly(s):void 0;s&&f&&(n+=Fy(f))}else m===`
|
|
962
|
+
`&&(s&&Ly(s)&&(n+=Fy(s)),o&&(n+=Uy(o)))}return n},Y$=/\r?\n/;function ys(t,e,r){return String(t).normalize().split(Y$).map(n=>J$(n,e,r)).join(`
|
|
963
|
+
`)}var To=$o(ml(),1);import{ReadStream as Vy}from"node:tty";var rT=["up","down","left","right","space","enter","cancel"],nT=["January","February","March","April","May","June","July","August","September","October","November","December"],yr={actions:new Set(rT),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:[...nT],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 Wy(t,e){if(typeof t=="string")return yr.aliases.get(t)===e;for(let r of t)if(r!==void 0&&Wy(r,e))return!0;return!1}var sT=globalThis.process.platform.startsWith("win");function Gy({input:t=tT,output:e=eT,overwrite:r=!0,hideCursor:n=!0}={}){let s=Wr.createInterface({input:t,output:e,prompt:"",tabSize:1});Wr.emitKeypressEvents(t,s),t instanceof Vy&&t.isTTY&&t.setRawMode(!0);let o=(i,{name:a,sequence:c})=>{let u=String(i);if(Wy([u,a,c],"cancel")){n&&e.write(To.cursor.show),process.exit(0);return}if(!r)return;Wr.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{Wr.clearLine(e,1,()=>{t.once("keypress",o)})})};return n&&e.write(To.cursor.hide),t.once("keypress",o),()=>{t.off("keypress",o),n&&e.write(To.cursor.show),t instanceof Vy&&t.isTTY&&!sT&&t.setRawMode(!1),s.terminal=!1,s.close()}}var fl=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as Oe,stripVTControlCharacters as W2}from"node:util";import jt from"node:process";var Po=$o(ml(),1);function iT(){return jt.platform!=="win32"?jt.env.TERM!=="linux":!!jt.env.CI||!!jt.env.WT_SESSION||!!jt.env.TERMINUS_SUBLIME||jt.env.ConEmuTask==="{cmd::Cmder}"||jt.env.TERM_PROGRAM==="Terminus-Sublime"||jt.env.TERM_PROGRAM==="vscode"||jt.env.TERM==="xterm-256color"||jt.env.TERM==="alacritty"||jt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var hl=iT(),aT=()=>process.env.CI==="true";var ye=(t,e)=>hl?t:e,Y2=ye("\u25C6","*"),cT=ye("\u25A0","x"),uT=ye("\u25B2","x"),gl=ye("\u25C7","o"),lT=ye("\u250C","T"),Gr=ye("\u2502","|"),dT=ye("\u2514","\u2014"),X2=ye("\u2510","T"),Q2=ye("\u2518","\u2014"),eU=ye("\u25CF",">"),tU=ye("\u25CB"," "),rU=ye("\u25FB","[\u2022]"),nU=ye("\u25FC","[+]"),sU=ye("\u25FB","[ ]"),oU=ye("\u25AA","\u2022"),Ky=ye("\u2500","-"),pT=ye("\u256E","+"),mT=ye("\u251C","+"),fT=ye("\u256F","+"),hT=ye("\u2570","+"),iU=ye("\u256D","+"),gT=ye("\u25CF","\u2022"),yT=ye("\u25C6","*"),_T=ye("\u25B2","!"),xT=ye("\u25A0","x");var A={message:(t=[],{symbol:e=Oe("gray",Gr),secondarySymbol:r=Oe("gray",Gr),output:n=process.stdout,spacing:s=1,withGuide:o}={})=>{let i=[],a=o??yr.withGuide,c=a?r:"",u=a?`${e} `:"",d=a?`${r} `:"";for(let m=0;m<s;m++)i.push(c);let l=Array.isArray(t)?t:t.split(`
|
|
964
964
|
`);if(l.length>0){let[m,...f]=l;m.length>0?i.push(`${u}${m}`):i.push(a?e:"");for(let p of f)p.length>0?i.push(`${d}${p}`):i.push(a?r:"")}n.write(`${i.join(`
|
|
965
965
|
`)}
|
|
966
|
-
`)},info:(t,e)=>{
|
|
967
|
-
`)},ua=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??
|
|
968
|
-
${Oe("gray",
|
|
969
|
-
|
|
970
|
-
`)};var
|
|
971
|
-
`),o=s.reduce((c,u)=>Math.max(lt(u),c),0),i=s.map(r).reduce((c,u)=>Math.max(lt(u),c),0),a=e-(i-o);return
|
|
972
|
-
`).map(o),""],a=lt(e),c=Math.max(i.reduce((m,f)=>{let p=lt(f);return p>m?p:m},0),a)+2,u=i.map(m=>`${Oe("gray",
|
|
973
|
-
`),d=s?`${Oe("gray",
|
|
974
|
-
`:"",l=s?
|
|
966
|
+
`)},info:(t,e)=>{A.message(t,{...e,symbol:Oe("blue",gT)})},success:(t,e)=>{A.message(t,{...e,symbol:Oe("green",yT)})},step:(t,e)=>{A.message(t,{...e,symbol:Oe("green",gl)})},warn:(t,e)=>{A.message(t,{...e,symbol:Oe("yellow",_T)})},warning:(t,e)=>{A.warn(t,e)},error:(t,e)=>{A.message(t,{...e,symbol:Oe("red",xT)})}};var yl=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??yr.withGuide?`${Oe("gray",lT)} `:"";r.write(`${n}${t}
|
|
967
|
+
`)},ua=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??yr.withGuide?`${Oe("gray",Gr)}
|
|
968
|
+
${Oe("gray",dT)} `:"";r.write(`${n}${t}
|
|
969
|
+
|
|
970
|
+
`)};var vT=t=>Oe("dim",t),bT=(t,e,r)=>{let n={hard:!0,trim:!1},s=ys(t,e,n).split(`
|
|
971
|
+
`),o=s.reduce((c,u)=>Math.max(lt(u),c),0),i=s.map(r).reduce((c,u)=>Math.max(lt(u),c),0),a=e-(i-o);return ys(t,a,n)},_l=(t="",e="",r)=>{let n=r?.output??jt.stdout,s=r?.withGuide??yr.withGuide,o=r?.format??vT,i=["",...bT(t,fl(n)-6,o).split(`
|
|
972
|
+
`).map(o),""],a=lt(e),c=Math.max(i.reduce((m,f)=>{let p=lt(f);return p>m?p:m},0),a)+2,u=i.map(m=>`${Oe("gray",Gr)} ${m}${" ".repeat(c-lt(m))}${Oe("gray",Gr)}`).join(`
|
|
973
|
+
`),d=s?`${Oe("gray",Gr)}
|
|
974
|
+
`:"",l=s?mT:hT;n.write(`${d}${Oe("green",gl)} ${Oe("reset",e)} ${Oe("gray",Ky.repeat(Math.max(c-a-1,1))+pT)}
|
|
975
975
|
${u}
|
|
976
|
-
${Oe("gray",l+
|
|
977
|
-
`)};var
|
|
978
|
-
`);let
|
|
979
|
-
`);
|
|
980
|
-
`);let yt=0,
|
|
976
|
+
${Oe("gray",l+Ky.repeat(c+2)+fT)}
|
|
977
|
+
`)};var ST=t=>Oe("magenta",t),xl=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:n,errorMessage:s,frames:o=hl?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=hl?80:120,signal:a,...c}={})=>{let u=aT(),d,l,m=!1,f=!1,p="",h,g=performance.now(),_=fl(r),x=c?.styleFrame??ST,y=he=>{let yt=he>1?s??yr.messages.error:n??yr.messages.cancel;f=he===1,m&&(oe(yt,he),f&&typeof e=="function"&&e())},b=()=>y(2),w=()=>y(1),O=()=>{process.on("uncaughtExceptionMonitor",b),process.on("unhandledRejection",b),process.on("SIGINT",w),process.on("SIGTERM",w),process.on("exit",y),a&&a.addEventListener("abort",w)},C=()=>{process.removeListener("uncaughtExceptionMonitor",b),process.removeListener("unhandledRejection",b),process.removeListener("SIGINT",w),process.removeListener("SIGTERM",w),process.removeListener("exit",y),a&&a.removeEventListener("abort",w)},T=()=>{if(h===void 0)return;u&&r.write(`
|
|
978
|
+
`);let he=ys(h,_,{hard:!0,trim:!1}).split(`
|
|
979
|
+
`);he.length>1&&r.write(Po.cursor.up(he.length-1)),r.write(Po.cursor.to(0)),r.write(Po.erase.down())},z=he=>he.replace(/\.+$/,""),P=he=>{let yt=(performance.now()-he)/1e3,Mt=Math.floor(yt/60),_t=Math.floor(yt%60);return Mt>0?`[${Mt}m ${_t}s]`:`[${_t}s]`},I=c.withGuide??yr.withGuide,V=(he="")=>{m=!0,d=Gy({output:r}),p=z(he),g=performance.now(),I&&r.write(`${Oe("gray",Gr)}
|
|
980
|
+
`);let yt=0,Mt=0;O(),l=setInterval(()=>{if(u&&p===h)return;T(),h=p;let _t=x(o[yt]),gs;if(u)gs=`${_t} ${p}...`;else if(t==="timer")gs=`${_t} ${p} ${P(g)}`;else{let ol=".".repeat(Math.floor(Mt)).slice(0,3);gs=`${_t} ${p}${ol}`}let sl=ys(gs,_,{hard:!0,trim:!1});r.write(sl),yt=yt+1<o.length?yt+1:0,Mt=Mt<4?Mt+.125:0},i)},oe=(he="",yt=0,Mt=!1)=>{if(!m)return;m=!1,clearInterval(l),T();let _t=yt===0?Oe("green",gl):yt===1?Oe("red",cT):Oe("red",uT);p=he??p,Mt||(t==="timer"?r.write(`${_t} ${p} ${P(g)}
|
|
981
981
|
`):r.write(`${_t} ${p}
|
|
982
|
-
`)),C(),d()};return{start:V,stop:(
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
Run: ${h.fix}`):""))
|
|
982
|
+
`)),C(),d()};return{start:V,stop:(he="")=>oe(he,0),message:(he="")=>{p=z(he??p)},cancel:(he="")=>oe(he,1),error:(he="")=>oe(he,2),clear:()=>oe("",0,!0),get isCancelled(){return f}}},aU={light:ye("\u2500","-"),heavy:ye("\u2501","="),block:ye("\u2588","#")};var cU=`${Oe("gray",Gr)} `;var E=$o(Xy(),1);ha();kl();Kr();import{execFileSync as wo,execSync as YF,execFile as XF}from"node:child_process";import{readFileSync as qr,writeFileSync as QF,cpSync as T$,accessSync as R$,existsSync as Le,rmSync as Eo,closeSync as e2,openSync as t2,chmodSync as r2,constants as C$}from"node:fs";import{request as n2}from"node:https";import{resolve as de,dirname as Ry,join as gt}from"node:path";import{tmpdir as s2,devNull as o2,homedir as P$}from"node:os";import{fileURLToPath as i2,pathToFileURL as rl}from"node:url";import{existsSync as DT,readFileSync as MT,writeFileSync as jT}from"node:fs";import{resolve as $l,sep as zT}from"node:path";var LT=/[/\\]context-mode-upgrade-\d+[/\\]/,FT="${CLAUDE_PLUGIN_ROOT}/start.mjs";function Tl({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=$l(t),s=$l(e)+zT;if(!n.startsWith(s))return{healed:[],skipped:"outside-cache-root"};let o=$l(t,".claude-plugin","plugin.json");if(!DT(o))return{healed:[],skipped:"no-plugin-json"};let i;try{i=MT(o,"utf-8")}catch(h){return{healed:[],error:`read-failed: ${h&&h.message||h}`}}let a;try{a=JSON.parse(i)}catch(h){return{healed:[],error:`parse-failed: ${h&&h.message||h}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],m=d.args,f=m.map(h=>typeof h!="string"?h:LT.test(h)&&/[/\\]start\.mjs$/.test(h)?FT:h);if(f.some((h,g)=>h!==m[g])){d.args=f,l.push("plugin-json-args");try{jT(o,JSON.stringify(a,null,2)+`
|
|
983
|
+
`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:l}}No();function a2(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 c2={"claude-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"},"gemini-cli":{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"},"qwen-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"}};async function u2(t,e){try{e2(2),t2(o2,"w")}catch{process.stderr.write=(()=>!0)}let r=c2[t]?.[e];r||process.exit(1);let n=hs();await import(rl(gt(n,r)).href)}var Br=process.argv.slice(2);Br[0]==="doctor"?h2().then(t=>process.exit(t)):Br[0]==="upgrade"?y2().catch(t=>{let e=t instanceof Error?t.message:String(t);A.error(E.default.red(e)),process.exit(1)}):Br[0]==="hook"?u2(Br[1],Br[2]):Br[0]==="insight"?g2(Br[1]?Number(Br[1]):4747):Br[0]==="statusline"?_2():Promise.resolve().then(()=>($$(),E$));function PW(t){return t.replace(/\\/g,"/")}var nl=process.platform==="win32";function tl(t,e={}){wo(nl?"npm.cmd":"npm",t,{...e,...nl?{shell:!0}:{}})}function l2(t,e={}){let r={...e,...nl?{shell:!0}:{}};YF(nl?t.replace(/^npm /,"npm.cmd "):t,r)}function d2(t,e=process.platform,r=XF){let n={stdio:"ignore"},s=()=>console.error(`
|
|
984
|
+
Could not auto-open browser. Open manually: ${t}`),o=a2(t,e),i=!1;for(let{cmd:a,args:c}of o)try{r(a,c,n),i=!0;break}catch{}i||s()}function p2(){let t=i2(import.meta.url),e=Ry(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?de(e,".."):e}function m2(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;return r?de(r,t,...e):de(P$(),"AppData","Local",t,...e)}return de(P$(),".cache",t,...e)}function hs(){let t=nr().platform;return t==="opencode"||t==="kilo"?m2(t):p2()}function O$(){try{return JSON.parse(qr(de(hs(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function f2(){return new Promise(t=>{let e=n2("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",s=>{n+=s}),r.on("end",()=>{try{let s=JSON.parse(n);t(s.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}async function h2(){process.stdout.isTTY&&console.clear();let t=nr(),e=await Ao(t.platform);yl(E.default.bgMagenta(E.default.white(" context-mode doctor "))),A.info(`Platform: ${E.default.cyan(e.name)}`+E.default.dim(` (${t.confidence} confidence \u2014 ${t.reason})`));let r=0,n=xl();n.start("Running diagnostics");let s,o;try{s=xs(),o=fa(s)}catch{return n.stop("Diagnostics partial"),A.warn(E.default.yellow("Could not detect runtimes")+E.default.dim(" \u2014 module may be missing, restart session after upgrade")),ua(E.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}n.stop("Diagnostics complete"),_l(ma(s),"Runtimes"),vs()?A.success(E.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):A.warn(E.default.yellow("Performance: NORMAL")+" \u2014 Using Node.js (install Bun for 3-5x speed boost)");let i=11,a=(o.length/i*100).toFixed(0);o.length<2?(r++,A.error(E.default.red(`Language coverage: ${o.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+E.default.dim(` \u2014 ${o.join(", ")||"none"}`))):A.info(`Language coverage: ${o.length}/${i} (${a}%)`+E.default.dim(` \u2014 ${o.join(", ")}`)),A.step("Testing server initialization...");try{let{PolyglotExecutor:h}=await Promise.resolve().then(()=>(Hg(),Xw)),_=await new h({runtimes:s}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(_.exitCode===0&&_.stdout.trim()==="ok")A.success(E.default.green("Server test: PASS"));else{r++;let x=_.stderr?.trim()?` (${_.stderr.trim().slice(0,200)})`:"";A.error(E.default.red("Server test: FAIL")+` \u2014 exit ${_.exitCode}${x}`)}}catch(h){let g=h instanceof Error?h.message:String(h);g.includes("Cannot find module")||g.includes("MODULE_NOT_FOUND")?A.warn(E.default.yellow("Server test: SKIP")+E.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,A.error(E.default.red("Server test: FAIL")+` \u2014 ${g}`))}A.step(`Checking ${e.name} hooks configuration...`);let c=hs(),u=e.validateHooks(c);for(let h of u)h.status==="pass"?A.success(E.default.green(`${h.check}: PASS`)+` \u2014 ${h.message}`):h.status==="warn"?A.warn(E.default.yellow(`${h.check}: WARN`)+` \u2014 ${h.message}`+(h.fix?E.default.dim(`
|
|
985
|
+
Run: ${h.fix}`):"")):A.error(E.default.red(`${h.check}: FAIL`)+` \u2014 ${h.message}`+(h.fix?E.default.dim(`
|
|
986
|
+
Run: ${h.fix}`):""));A.step("Checking hook scripts...");let d=ga(e,c);if(d.length===0)A.success(E.default.green("Hook scripts: PASS")+E.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let h of d){let g=de(c,h);try{R$(g,C$.R_OK),A.success(E.default.green("Hook script exists: PASS")+E.default.dim(` \u2014 ${g}`))}catch{A.error(E.default.red("Hook script exists: FAIL")+E.default.dim(` \u2014 not found at ${g}`))}}A.step(`Checking ${e.name} plugin registration...`);let l=e.checkPluginRegistration();l.status==="pass"?A.success(E.default.green("Plugin enabled: PASS")+E.default.dim(` \u2014 ${l.message}`)):A.warn(E.default.yellow("Plugin enabled: WARN")+` \u2014 ${l.message}`),A.step("Checking FTS5 / SQLite...");try{let h=(await Promise.resolve().then(()=>(xo(),nE))).loadDatabase(),g=new h(":memory:");g.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),g.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let _=g.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();g.close(),_&&_.content==="hello world"?A.success(E.default.green("FTS5 / SQLite: PASS")+" \u2014 native module works"):(r++,A.error(E.default.red("FTS5 / SQLite: FAIL")+" \u2014 query returned unexpected result"))}catch(h){let g=h instanceof Error?h.message:String(h),_=hs(),x=de(_,"node_modules","better-sqlite3");!Le(x)?(r++,A.error(E.default.red("FTS5 / better-sqlite3: FAIL")+E.default.dim(" \u2014 package-missing")+E.default.dim(`
|
|
987
|
+
Path: ${x}
|
|
988
|
+
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).
|
|
989
|
+
Try (primary): cd "${_}" && npm install better-sqlite3 --no-optional
|
|
990
|
+
Try (fallback): /context-mode:ctx-upgrade`))):g.includes("Cannot find module")||g.includes("MODULE_NOT_FOUND")?A.warn(E.default.yellow("FTS5 / better-sqlite3: SKIP")+E.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,(/Could not locate the bindings file/i.test(g)||/bindings\.node/i.test(g)||/\bbindings\b/i.test(g))&&process.platform==="win32"?A.error(E.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${g}`+E.default.dim(`
|
|
986
991
|
Root cause: prebuild-install was likely not on PATH, so install fell through to node-gyp without an MSVC toolchain (Windows).
|
|
987
992
|
Try (primary): npm install better-sqlite3 # re-resolves the dep tree and re-links the prebuild-install bin shim to fetch a prebuilt binary
|
|
988
|
-
Try (fallback): npm rebuild better-sqlite3`)):
|
|
989
|
-
Try: npm rebuild better-sqlite3`)))}
|
|
990
|
-
Run: /context-mode:ctx-upgrade`)),p==="not installed"?
|
|
991
|
-
Run: /context-mode:ctx-upgrade`)):
|
|
993
|
+
Try (fallback): npm rebuild better-sqlite3`)):A.error(E.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${g}`+E.default.dim(`
|
|
994
|
+
Try: npm rebuild better-sqlite3`)))}A.step("Checking versions...");let m=O$(),f=await f2(),p=e.getInstalledVersion();return f==="unknown"?A.warn(E.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, could not reach npm registry`):m===f?A.success(E.default.green("npm (MCP): PASS")+` \u2014 v${m}`):A.warn(E.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, latest v${f}`+E.default.dim(`
|
|
995
|
+
Run: /context-mode:ctx-upgrade`)),p==="not installed"?A.info(E.default.dim(`${e.name}: not installed`)+" \u2014 using standalone MCP mode"):f!=="unknown"&&p===f?A.success(E.default.green(`${e.name}: PASS`)+` \u2014 v${p}`):f!=="unknown"?A.warn(E.default.yellow(`${e.name}: WARN`)+` \u2014 v${p}, latest v${f}`+E.default.dim(`
|
|
996
|
+
Run: /context-mode:ctx-upgrade`)):A.info(`${e.name}: v${p}`+E.default.dim(" \u2014 could not verify against npm registry")),r>0?(ua(E.default.red(`Diagnostics failed \u2014 ${r} critical issue(s) found`)),1):(ua(o.length>=4?E.default.green("Diagnostics complete!"):E.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function g2(t){try{let{execSync:e,spawn:r}=await import("node:child_process"),{statSync:n,mkdirSync:s,cpSync:o}=await import("node:fs"),i=de(hs(),"insight"),a=nr(),u=(await Ao(a.platform)).getSessionDir(),d=gt(Ry(u),"content"),l=gt(Ry(u),"insight-cache");Le(gt(i,"server.mjs"))||(console.error("Error: Insight source not found. Try upgrading context-mode."),process.exit(1)),s(l,{recursive:!0});let m=n(gt(i,"server.mjs")).mtimeMs,f=Le(gt(l,"server.mjs"))?n(gt(l,"server.mjs")).mtimeMs:0;if(m>f&&(console.log("Copying Insight source..."),o(i,l,{recursive:!0,force:!0})),!Le(gt(l,"node_modules"))){console.log("Installing dependencies (first run)...");try{l2("npm install --production=false",{cwd:l,stdio:"inherit",timeout:3e5})}catch{try{Eo(gt(l,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!Le(gt(l,"node_modules","vite"))||!Le(gt(l,"node_modules","better-sqlite3")))throw Eo(gt(l,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry")}console.log("Building dashboard..."),e("npx vite build",{cwd:l,stdio:"pipe",timeout:6e4});let p=`http://localhost:${t}`;console.log(`
|
|
992
997
|
context-mode Insight
|
|
993
998
|
${p}
|
|
994
|
-
`);let h=r("node",[gt(l,"server.mjs")],{cwd:l,env:{...process.env,PORT:String(t),INSIGHT_SESSION_DIR:u,INSIGHT_CONTENT_DIR:d},stdio:"inherit"});h.on("error",()=>{}),await new Promise(g=>setTimeout(g,1500));try{let{request:g}=await import("node:http");await new Promise((
|
|
999
|
+
`);let h=r("node",[gt(l,"server.mjs")],{cwd:l,env:{...process.env,PORT:String(t),INSIGHT_SESSION_DIR:u,INSIGHT_CONTENT_DIR:d},stdio:"inherit"});h.on("error",()=>{}),await new Promise(g=>setTimeout(g,1500));try{let{request:g}=await import("node:http");await new Promise((_,x)=>{let y=g(`http://127.0.0.1:${t}/api/overview`,{timeout:3e3},b=>{_(),b.resume()});y.on("error",x),y.on("timeout",()=>{y.destroy(),x(new Error("timeout"))}),y.end()})}catch{console.error(`
|
|
995
1000
|
Error: Port ${t} appears to be in use. Either a previous dashboard is still running, or another service is using this port.`),console.error(`
|
|
996
|
-
To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),h.kill(),process.exit(1)}
|
|
997
|
-
Insight error: ${r}`),process.exit(1)}}async function
|
|
998
|
-
`),s.stop(E.default.green(`Updated in-place to v${f}`));let
|
|
999
|
-
Try manually: cd "${r}" && npm rebuild better-sqlite3`))}
|
|
1000
|
-
|
|
1001
|
+
To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),h.kill(),process.exit(1)}d2(p),process.on("SIGINT",()=>{h.kill(),process.exit(0)}),process.on("SIGTERM",()=>{h.kill(),process.exit(0)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`
|
|
1002
|
+
Insight error: ${r}`),process.exit(1)}}async function y2(){process.stdout.isTTY&&console.clear();let t=nr(),e=await Ao(t.platform);yl(E.default.bgCyan(E.default.black(" context-mode upgrade "))),A.info(`Platform: ${E.default.cyan(e.name)}`+E.default.dim(` (${t.confidence} confidence)`));let r=hs(),n=[],s=xl(),o=de(qe(),"plugins","marketplaces","context-mode");if(Le(gt(o,".git"))){s.start("Syncing marketplace clone");try{wo("git",["-C",o,"status","--porcelain"],{stdio:"pipe",encoding:"utf-8",timeout:5e3}).trim()?(s.stop(E.default.yellow("Marketplace clone has local edits \u2014 skipping git pull")),A.info(E.default.dim(` Run manually: git -C "${o}" stash && git pull --ff-only`))):(wo("git",["-C",o,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),wo("git",["-C",o,"reset","--hard","origin/HEAD"],{stdio:"pipe",timeout:1e4}),s.stop(E.default.green("Marketplace clone synced")),n.push("Marketplace clone updated to upstream"))}catch(l){let m=l instanceof Error?l.message:String(l);s.stop(E.default.yellow("Marketplace sync skipped")),A.warn(E.default.yellow("git refresh on marketplace failed")+` \u2014 ${m}`),A.info(E.default.dim(" Continuing \u2014 cache dir update will still happen."))}}A.step("Pulling latest from GitHub...");let i=O$(),a=gt(s2(),`context-mode-upgrade-${Date.now()}`);s.start("Cloning mksglu/context-mode");try{wo("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",a],{stdio:"pipe",timeout:3e4}),s.stop("Downloaded");let l=a,f=JSON.parse(qr(de(l,"package.json"),"utf-8")).version??"unknown";if(f===i)A.success(E.default.green("Already on latest")+` \u2014 v${i}`),Eo(a,{recursive:!0,force:!0});else{A.info(`Update available: ${E.default.yellow("v"+i)} \u2192 ${E.default.green("v"+f)}`),s.start("Installing dependencies & building"),tl(["install","--no-audit","--no-fund"],{cwd:l,stdio:"pipe",timeout:12e4}),tl(["run","build"],{cwd:l,stdio:"pipe",timeout:6e4}),s.stop("Built successfully"),s.start("Updating files in-place");let h=[...JSON.parse(qr(de(l,"package.json"),"utf-8")).files||[],"src","package.json"];for(let y of h)try{Eo(de(r,y),{recursive:!0,force:!0}),T$(de(l,y),de(r,y),{recursive:!0})}catch{}let g={mcpServers:{"context-mode":{command:"node",args:["${CLAUDE_PLUGIN_ROOT}/start.mjs"]}}};QF(de(r,".mcp.json"),JSON.stringify(g,null,2)+`
|
|
1003
|
+
`),s.stop(E.default.green(`Updated in-place to v${f}`));let _=de(r,".claude-plugin","plugin.json"),x=null;try{let y=JSON.parse(qr(_,"utf-8"));y&&typeof y.version=="string"&&(x=y.version)}catch{}if(x!==f)throw new Error(`pluginRoot manifest version mismatch \u2014 disk says "${x??"<missing>"}" but newVersion is "${f}". Refusing to bump registry.`);e.updatePluginRegistry(r,f),A.info(E.default.dim(" Registry synced to "+r));try{let y=de(qe(),"plugins","installed_plugins.json");if(Le(y)){let w=JSON.parse(qr(y,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(w))for(let O of w){let C=O?.installPath;if(typeof C!="string"||!C)continue;if(!Le(C))throw new Error(`installPath does not exist on disk: ${C}`);let T=de(C,".claude-plugin","plugin.json");if(!Le(T))throw new Error(`missing plugin.json manifest at ${T}`);let z=JSON.parse(qr(T,"utf-8"));if(z?.version!==O.version)throw new Error(`version mismatch \u2014 registry says "${O.version}" but ${T} says "${z?.version}"`)}}}catch(y){let b=y instanceof Error?y.message:String(y);throw new Error(`Registry consistency check failed: ${b}`)}try{let y=de(qe(),"plugins","cache"),b="context-mode@context-mode",w=Tl({pluginRoot:r,pluginCacheRoot:y,pluginKey:b});if(w&&w.error)throw new Error(w.error);let O=Tl({pluginRoot:r,pluginCacheRoot:y,pluginKey:b});if(O&&Array.isArray(O.healed)&&O.healed.length>0)throw new Error(`Plugin manifest drift: plugin.json mcpServers.args still poisoned after first heal pass (healed=${O.healed.join(",")})`)}catch(y){let b=y instanceof Error?y.message:String(y);throw new Error(`plugin.json drift check failed: ${b}`)}try{let y=de(o,".claude-plugin","plugin.json");if(Le(y)){let b=JSON.parse(qr(y,"utf-8"));b?.version!==f&&(A.warn(E.default.yellow("Marketplace clone version mismatch")+` \u2014 ${o} reports "${b?.version}" but expected "${f}"`),A.info(E.default.dim(` Run manually: git -C "${o}" fetch --tags origin && git -C "${o}" reset --hard origin/HEAD`)))}}catch{}if(s.start("Installing production dependencies"),tl(["install","--production","--no-audit","--no-fund"],{cwd:r,stdio:"pipe",timeout:6e4}),s.stop("Dependencies ready"),t.platform!=="opencode"&&t.platform!=="kilo"){s.start("Verifying native addon ABI");let y=de(r,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let w=de(r,"hooks","ensure-deps.mjs");if(!Le(w))throw new Error(`missing ${w}`);await import(`${rl(w).href}?upgrade=${Date.now()}`),Le(y)?(s.stop(E.default.green("Native addons OK")+E.default.dim(" \u2014 ABI cache present")),n.push(`better-sqlite3 ABI ${process.versions.modules} cache ready`)):(s.stop(E.default.yellow("Native addon ABI cache missing")),A.warn(E.default.dim(` Try manually: cd "${r}" && npm rebuild better-sqlite3`)))}catch(w){let O=w instanceof Error?w.message:String(w);s.stop(E.default.yellow("Native addon ABI bootstrap unavailable")),A.warn(E.default.yellow("better-sqlite3 ABI repair did not run")+` \u2014 ${O}`+E.default.dim(`
|
|
1004
|
+
Try manually: cd "${r}" && npm rebuild better-sqlite3`))}let b=de(r,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!Le(b))try{let w=de(r,"scripts","heal-better-sqlite3.mjs");if(Le(w)){let O=await import(`${rl(w).href}?upgrade=${Date.now()}`);typeof O.healBetterSqlite3Binding=="function"&&O.healBetterSqlite3Binding(r)}}catch{}Le(b)||(process.exitCode=1,A.error(E.default.red("better-sqlite3 native binding: MISSING")+E.default.dim(`
|
|
1005
|
+
Path: ${b}`)+E.default.dim(`
|
|
1006
|
+
Cause: npm silently skipped the package (Node engine mismatch, issue #514)`)+E.default.dim(`
|
|
1007
|
+
Try (primary): cd "${r}" && npm install better-sqlite3 --no-optional`)+E.default.dim(`
|
|
1008
|
+
Try (fallback): /context-mode:ctx-doctor`)))}s.start("Updating npm global package");try{tl(["install","-g",r,"--no-audit","--no-fund"],{stdio:"pipe",timeout:3e4}),s.stop(E.default.green("npm global updated")),n.push("Updated npm global package")}catch{s.stop(E.default.yellow("npm global update skipped")),A.info(E.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}Eo(a,{recursive:!0,force:!0});try{let y=de(qe(),"plugins","installed_plugins.json");if(Le(y)){let w=JSON.parse(qr(y,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(w))for(let O of w){let C=O.installPath;if(C&&C!==r&&Le(C)){let T=de(l,"skills");Le(T)&&(T$(T,de(C,"skills"),{recursive:!0}),n.push("Synced skills to active install path"))}}}}catch{}n.push(`Updated v${i} \u2192 v${f}`),A.success(E.default.green("Plugin reinstalled from GitHub!")+E.default.dim(` \u2014 v${f}`))}}catch(l){let m=l instanceof Error?l.message:String(l);s.stop(E.default.red("Update failed")),A.error(E.default.red("GitHub pull failed")+` \u2014 ${m}`),A.info(E.default.dim("Continuing with hooks/settings fix..."));try{Eo(a,{recursive:!0,force:!0})}catch{}}A.step(`Backing up ${e.name} settings...`);let c=e.backupSettings();c?.endsWith(".bak")?(A.success(E.default.green("Backup created")+E.default.dim(" -> "+c)),n.push("Backed up settings")):c?A.success(E.default.green("Backup skipped")+E.default.dim(" \u2014 no changes needed")):A.warn(E.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),A.step(`Configuring ${e.name} hooks...`);try{let l=e.configureAllHooks(r);for(let m of l)A.info(E.default.dim(` ${m}`)),n.push(m);A.success(E.default.green("Hooks configured")+E.default.dim(` \u2014 ${e.name}`))}catch(l){let m=l instanceof Error?l.message:String(l);throw new Error(`Hook configuration failed: ${m}`)}A.step("Setting hook script permissions...");let u=e.setHookPermissions(r);if(process.platform!=="win32")for(let l of["build/cli.js","cli.bundle.mjs"]){let m=de(r,l);try{R$(m,C$.F_OK),r2(m,493),u.push(m)}catch{}}u.length>0?(A.success(E.default.green("Permissions set")+E.default.dim(` \u2014 ${u.length} hook script(s)`)),n.push(`Set ${u.length} hook scripts as executable`)):A.error(E.default.red("No hook scripts found")+E.default.dim(" \u2014 expected in "+de(r,"hooks"))),n.length>0?_l(n.map(l=>E.default.green(" + ")+l).join(`
|
|
1009
|
+
`),"Changes Applied"):A.info(E.default.dim("No changes were needed."));let d=e.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";A.warn(E.default.yellow("Restart for new MCP tools to take effect.")+E.default.dim(` (${d})`)),A.step("Running doctor to verify..."),console.log();try{let l=de(r,"cli.bundle.mjs"),m=de(r,"build","cli.js"),f=Le(l)?l:m;wo("node",[f,"doctor"],{stdio:"inherit",timeout:3e4,cwd:r})}catch{A.warn(E.default.yellow("Doctor had warnings")+E.default.dim(` \u2014 restart your ${e.name} session to pick up the new version`))}}function _2(){let t=qe(),e=[de(hs(),"bin","statusline.mjs"),de(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let n=de(t,"plugins","installed_plugins.json");if(Le(n)){let o=JSON.parse(qr(n,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(o))for(let i of o){let a=i?.installPath;typeof a=="string"&&a&&e.push(de(a,"bin","statusline.mjs"))}}}catch{}let r=e.find(n=>Le(n));r||process.exit(0),import(rl(r).href).catch(()=>{process.exit(0)})}export{l2 as npmExec,tl as npmExecFile,d2 as openInBrowser,PW as toUnixPath};
|