context-mode 1.0.162 → 1.0.163
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.openclaw-plugin/openclaw.plugin.json +1 -1
- package/.openclaw-plugin/package.json +1 -1
- package/README.md +142 -28
- package/bin/statusline.mjs +24 -4
- package/build/adapters/antigravity/index.d.ts +1 -1
- package/build/adapters/antigravity-cli/index.d.ts +51 -0
- package/build/adapters/antigravity-cli/index.js +341 -0
- package/build/adapters/claude-code/hooks.d.ts +1 -0
- package/build/adapters/claude-code/hooks.js +3 -0
- package/build/adapters/claude-code/index.js +24 -5
- package/build/adapters/client-map.js +5 -0
- package/build/adapters/codex/hooks.d.ts +5 -1
- package/build/adapters/codex/hooks.js +5 -1
- package/build/adapters/codex/index.d.ts +9 -1
- package/build/adapters/codex/index.js +87 -5
- package/build/adapters/copilot-cli/hooks.d.ts +33 -0
- package/build/adapters/copilot-cli/hooks.js +64 -0
- package/build/adapters/copilot-cli/index.d.ts +48 -0
- package/build/adapters/copilot-cli/index.js +341 -0
- package/build/adapters/detect.d.ts +1 -1
- package/build/adapters/detect.js +71 -3
- package/build/adapters/openclaw/mcp-tools.js +1 -1
- package/build/adapters/opencode/index.js +31 -17
- package/build/adapters/opencode/zod3tov4.js +27 -6
- package/build/adapters/pi/extension.d.ts +2 -12
- package/build/adapters/pi/extension.js +114 -96
- package/build/adapters/types.d.ts +5 -4
- package/build/adapters/types.js +4 -3
- package/build/cache-heal.d.ts +48 -0
- package/build/cache-heal.js +150 -0
- package/build/cli.js +37 -97
- package/build/executor.d.ts +25 -0
- package/build/executor.js +143 -22
- package/build/opencode-plugin.js +5 -2
- package/build/routing-block.d.ts +8 -0
- package/build/routing-block.js +86 -0
- package/build/runtime.d.ts +0 -36
- package/build/runtime.js +107 -27
- package/build/search/flood-guard.d.ts +57 -0
- package/build/search/flood-guard.js +80 -0
- package/build/security.d.ts +8 -3
- package/build/security.js +155 -29
- package/build/server.d.ts +14 -0
- package/build/server.js +368 -350
- package/build/session/analytics.d.ts +1 -1
- package/build/session/analytics.js +5 -1
- package/build/session/db.js +23 -3
- package/build/session/extract.js +8 -0
- package/build/store.d.ts +1 -1
- package/build/store.js +139 -25
- package/build/tool-naming.d.ts +4 -0
- package/build/tool-naming.js +24 -0
- package/build/util/jsonc.d.ts +14 -0
- package/build/util/jsonc.js +104 -0
- package/cli.bundle.mjs +254 -252
- package/configs/antigravity/GEMINI.md +2 -2
- package/configs/antigravity-cli/hooks/hooks.json +37 -0
- package/configs/antigravity-cli/hooks.json +37 -0
- package/configs/antigravity-cli/mcp_config.json +10 -0
- package/configs/antigravity-cli/plugin.json +14 -0
- package/configs/antigravity-cli/rules/context-mode.md +77 -0
- package/configs/antigravity-cli/skills/context-mode/SKILL.md +77 -0
- package/configs/claude-code/CLAUDE.md +2 -2
- package/configs/codex/AGENTS.md +2 -2
- package/configs/copilot-cli/.github/plugin/plugin.json +23 -0
- package/configs/copilot-cli/.mcp.json +12 -0
- package/configs/copilot-cli/README.md +47 -0
- package/configs/copilot-cli/hooks.json +41 -0
- package/configs/copilot-cli/skills/context-mode/SKILL.md +38 -0
- package/configs/gemini-cli/GEMINI.md +2 -2
- package/configs/jetbrains-copilot/copilot-instructions.md +2 -2
- package/configs/kilo/AGENTS.md +2 -2
- package/configs/kiro/KIRO.md +2 -2
- package/configs/omp/SYSTEM.md +2 -2
- package/configs/openclaw/AGENTS.md +2 -2
- package/configs/opencode/AGENTS.md +2 -2
- package/configs/qwen-code/QWEN.md +2 -2
- package/configs/vscode-copilot/copilot-instructions.md +2 -2
- package/configs/zed/AGENTS.md +2 -2
- package/hooks/antigravity-cli/payload.mjs +98 -0
- package/hooks/antigravity-cli/posttooluse.mjs +138 -0
- package/hooks/antigravity-cli/pretooluse.mjs +78 -0
- package/hooks/antigravity-cli/stop.mjs +58 -0
- package/hooks/codex/pretooluse.mjs +14 -4
- package/hooks/codex/stop.mjs +12 -4
- package/hooks/copilot-cli/posttooluse.mjs +79 -0
- package/hooks/copilot-cli/precompact.mjs +66 -0
- package/hooks/copilot-cli/pretooluse.mjs +41 -0
- package/hooks/copilot-cli/sessionstart.mjs +121 -0
- package/hooks/copilot-cli/stop.mjs +59 -0
- package/hooks/copilot-cli/userpromptsubmit.mjs +77 -0
- package/hooks/core/codex-caps.mjs +112 -0
- package/hooks/core/formatters.mjs +158 -7
- package/hooks/core/mcp-ready.mjs +37 -8
- package/hooks/core/routing.mjs +94 -8
- package/hooks/core/tool-naming.mjs +3 -0
- package/hooks/hooks.json +12 -1
- package/hooks/pretooluse.mjs +6 -2
- package/hooks/routing-block.mjs +2 -2
- package/hooks/security.bundle.mjs +2 -1
- package/hooks/session-db.bundle.mjs +5 -5
- package/hooks/session-directive.mjs +88 -20
- package/hooks/session-extract.bundle.mjs +1 -1
- package/hooks/session-helpers.mjs +21 -0
- package/hooks/sessionstart.mjs +37 -5
- package/hooks/stop.mjs +49 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +4 -10
- package/scripts/install-antigravity-cli-plugin.mjs +141 -0
- package/server.bundle.mjs +208 -203
- package/skills/ctx-insight/SKILL.md +12 -17
- package/build/util/db-lock.d.ts +0 -65
- package/build/util/db-lock.js +0 -166
- package/insight/index.html +0 -13
- package/insight/package.json +0 -55
- package/insight/server.mjs +0 -1265
- package/insight/src/components/analytics.tsx +0 -112
- package/insight/src/components/ui/badge.tsx +0 -52
- package/insight/src/components/ui/button.tsx +0 -58
- package/insight/src/components/ui/card.tsx +0 -103
- package/insight/src/components/ui/chart.tsx +0 -371
- package/insight/src/components/ui/collapsible.tsx +0 -19
- package/insight/src/components/ui/input.tsx +0 -20
- package/insight/src/components/ui/progress.tsx +0 -83
- package/insight/src/components/ui/scroll-area.tsx +0 -55
- package/insight/src/components/ui/separator.tsx +0 -23
- package/insight/src/components/ui/table.tsx +0 -114
- package/insight/src/components/ui/tabs.tsx +0 -82
- package/insight/src/components/ui/tooltip.tsx +0 -64
- package/insight/src/lib/api.ts +0 -144
- package/insight/src/lib/utils.ts +0 -6
- package/insight/src/main.tsx +0 -22
- package/insight/src/routeTree.gen.ts +0 -189
- package/insight/src/router.tsx +0 -19
- package/insight/src/routes/__root.tsx +0 -55
- package/insight/src/routes/enterprise.tsx +0 -316
- package/insight/src/routes/index.tsx +0 -1482
- package/insight/src/routes/knowledge.tsx +0 -221
- package/insight/src/routes/knowledge_.$dbHash.$sourceId.tsx +0 -137
- package/insight/src/routes/search.tsx +0 -97
- package/insight/src/routes/sessions.tsx +0 -179
- package/insight/src/routes/sessions_.$dbHash.$sessionId.tsx +0 -181
- package/insight/src/styles.css +0 -104
- package/insight/tsconfig.json +0 -29
- package/insight/vite.config.ts +0 -19
package/server.bundle.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Uw=Object.create;var Mu=Object.defineProperty;var Fw=Object.getOwnPropertyDescriptor;var Zw=Object.getOwnPropertyNames;var qw=Object.getPrototypeOf,Bw=Object.prototype.hasOwnProperty;var ne=(t,e)=>()=>(t&&(e=t(t=0)),e);var N=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),He=(t,e)=>{for(var r in e)Mu(t,r,{get:e[r],enumerable:!0})},Vw=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Zw(e))!Bw.call(t,o)&&o!==r&&Mu(t,o,{get:()=>e[o],enumerable:!(n=Fw(e,o))||n.enumerable});return t};var pg=(t,e,r)=>(r=t!=null?Uw(qw(t)):{},Vw(e||!t||!t.__esModule?Mu(r,"default",{value:t,enumerable:!0}):r,t));var Gs=N(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.regexpCode=de.getEsmExportName=de.getProperty=de.safeStringify=de.stringify=de.strConcat=de.addCodeArg=de.str=de._=de.nil=de._Code=de.Name=de.IDENTIFIER=de._CodeOrName=void 0;var Ws=class{};de._CodeOrName=Ws;de.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Hn=class extends Ws{constructor(e){if(super(),!de.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}}};de.Name=Hn;var Dt=class extends Ws{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 Hn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};de._Code=Dt;de.nil=new Dt("");function cx(t,...e){let r=[t[0]],n=0;for(;n<e.length;)_p(r,e[n]),r.push(t[++n]);return new Dt(r)}de._=cx;var yp=new Dt("+");function ux(t,...e){let r=[Ks(t[0])],n=0;for(;n<e.length;)r.push(yp),_p(r,e[n]),r.push(yp,Ks(t[++n]));return Z$(r),new Dt(r)}de.str=ux;function _p(t,e){e instanceof Dt?t.push(...e._items):e instanceof Hn?t.push(e):t.push(V$(e))}de.addCodeArg=_p;function Z$(t){let e=1;for(;e<t.length-1;){if(t[e]===yp){let r=q$(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function q$(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Hn||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 Hn))return`"${t}${e.slice(1)}`}function B$(t,e){return e.emptyStr()?t:t.emptyStr()?e:ux`${t}${e}`}de.strConcat=B$;function V$(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ks(Array.isArray(t)?t.join(","):t)}function W$(t){return new Dt(Ks(t))}de.stringify=W$;function Ks(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}de.safeStringify=Ks;function K$(t){return typeof t=="string"&&de.IDENTIFIER.test(t)?new Dt(`.${t}`):cx`[${t}]`}de.getProperty=K$;function G$(t){if(typeof t=="string"&&de.IDENTIFIER.test(t))return new Dt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}de.getEsmExportName=G$;function J$(t){return new Dt(t.toString())}de.regexpCode=J$});var vp=N(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.ValueScope=yt.ValueScopeName=yt.Scope=yt.varKinds=yt.UsedValueState=void 0;var gt=Gs(),xp=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Wa;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Wa||(yt.UsedValueState=Wa={}));yt.varKinds={const:new gt.Name("const"),let:new gt.Name("let"),var:new gt.Name("var")};var Ka=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof gt.Name?e:this.name(e)}name(e){return new gt.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}}};yt.Scope=Ka;var Ga=class extends gt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,gt._)`.${new gt.Name(r)}[${n}]`}};yt.ValueScopeName=Ga;var X$=(0,gt._)`\n`,Sp=class extends Ka{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?X$:gt.nil}}get(){return this._scope}name(e){return new Ga(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,gt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=gt.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,Wa.Started);let l=r(u);if(l){let d=this.opts.es5?yt.varKinds.var:yt.varKinds.const;s=(0,gt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,gt._)`${s}${l}${this.opts._n}`;else throw new xp(u);c.set(u,Wa.Completed)})}return s}};yt.ValueScope=Sp});var Q=N(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.or=ee.and=ee.not=ee.CodeGen=ee.operators=ee.varKinds=ee.ValueScopeName=ee.ValueScope=ee.Scope=ee.Name=ee.regexpCode=ee.stringify=ee.getProperty=ee.nil=ee.strConcat=ee.str=ee._=void 0;var ce=Gs(),Yt=vp(),en=Gs();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return en._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return en.str}});Object.defineProperty(ee,"strConcat",{enumerable:!0,get:function(){return en.strConcat}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return en.nil}});Object.defineProperty(ee,"getProperty",{enumerable:!0,get:function(){return en.getProperty}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return en.stringify}});Object.defineProperty(ee,"regexpCode",{enumerable:!0,get:function(){return en.regexpCode}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return en.Name}});var Qa=vp();Object.defineProperty(ee,"Scope",{enumerable:!0,get:function(){return Qa.Scope}});Object.defineProperty(ee,"ValueScope",{enumerable:!0,get:function(){return Qa.ValueScope}});Object.defineProperty(ee,"ValueScopeName",{enumerable:!0,get:function(){return Qa.ValueScopeName}});Object.defineProperty(ee,"varKinds",{enumerable:!0,get:function(){return Qa.varKinds}});ee.operators={GT:new ce._Code(">"),GTE:new ce._Code(">="),LT:new ce._Code("<"),LTE:new ce._Code("<="),EQ:new ce._Code("==="),NEQ:new ce._Code("!=="),NOT:new ce._Code("!"),OR:new ce._Code("||"),AND:new ce._Code("&&"),ADD:new ce._Code("+")};var $r=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},bp=class extends $r{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Yt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=No(this.rhs,e,r)),this}get names(){return this.rhs instanceof ce._CodeOrName?this.rhs.names:{}}},Ja=class extends $r{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 ce.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=No(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ce.Name?{}:{...this.lhs.names};return Ya(e,this.rhs)}},kp=class extends Ja{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ep=class extends $r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},wp=class extends $r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Tp=class extends $r{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Pp=class extends $r{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=No(this.code,e,r),this}get names(){return this.code instanceof ce._CodeOrName?this.code.names:{}}},Js=class extends $r{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(Y$(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Zn(e,r.names),{})}},Cr=class extends Js{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Rp=class extends Js{},Ao=class extends Cr{};Ao.kind="else";var Un=class t extends Cr{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 Ao(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(lx(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=No(this.condition,e,r),this}get names(){let e=super.names;return Ya(e,this.condition),this.else&&Zn(e,this.else.names),e}};Un.kind="if";var Fn=class extends Cr{};Fn.kind="for";var $p=class extends Fn{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=No(this.iteration,e,r),this}get names(){return Zn(super.names,this.iteration.names)}},Cp=class extends Fn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Yt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ya(super.names,this.from);return Ya(e,this.to)}},Xa=class extends Fn{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=No(this.iterable,e,r),this}get names(){return Zn(super.names,this.iterable.names)}},Xs=class extends Cr{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)}};Xs.kind="func";var Ys=class extends Js{render(e){return"return "+super.render(e)}};Ys.kind="return";var Op=class extends Cr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Zn(e,this.catch.names),this.finally&&Zn(e,this.finally.names),e}},Qs=class extends Cr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Qs.kind="catch";var ei=class extends Cr{render(e){return"finally"+super.render(e)}};ei.kind="finally";var Ip=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
3
|
-
`:""},this._extScope=e,this._scope=new Yt.Scope({parent:e}),this._nodes=[new Rp]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new bp(e,s,n)),s}const(e,r,n){return this._def(Yt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Yt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Yt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Ja(e,r,n))}add(e,r){return this._leafNode(new kp(e,ee.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ce.nil&&this._leafNode(new Pp(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,ce.addCodeArg)(r,o));return r.push("}"),new ce._Code(r)}if(e,r,n){if(this._blockNode(new Un(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 Un(e))}else(){return this._elseNode(new Ao)}endIf(){return this._endBlockNode(Un,Ao)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new $p(e),r)}forRange(e,r,n,o,s=this.opts.es5?Yt.varKinds.var:Yt.varKinds.let){let i=this._scope.toName(e);return this._for(new Cp(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Yt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ce.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ce._)`${i}.length`,a=>{this.var(s,(0,ce._)`${i}[${a}]`),n(s)})}return this._for(new Xa("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Yt.varKinds.var:Yt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ce._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Xa("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Fn)}label(e){return this._leafNode(new Ep(e))}break(e){return this._leafNode(new wp(e))}return(e){let r=new Ys;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Ys)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Op;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Qs(s),r(s)}return n&&(this._currNode=o.finally=new ei,this.code(n)),this._endBlockNode(Qs,ei)}throw(e){return this._leafNode(new Tp(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=ce.nil,n,o){return this._blockNode(new Xs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Xs)}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 Un))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}};ee.CodeGen=Ip;function Zn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ya(t,e){return e instanceof ce._CodeOrName?Zn(t,e.names):t}function No(t,e,r){if(t instanceof ce.Name)return n(t);if(!o(t))return t;return new ce._Code(t._items.reduce((s,i)=>(i instanceof ce.Name&&(i=n(i)),i instanceof ce._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ce._Code&&s._items.some(i=>i instanceof ce.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Y$(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function lx(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ce._)`!${Ap(t)}`}ee.not=lx;var Q$=dx(ee.operators.AND);function eC(...t){return t.reduce(Q$)}ee.and=eC;var tC=dx(ee.operators.OR);function rC(...t){return t.reduce(tC)}ee.or=rC;function dx(t){return(e,r)=>e===ce.nil?r:r===ce.nil?e:(0,ce._)`${Ap(e)} ${t} ${Ap(r)}`}function Ap(t){return t instanceof ce.Name?t:(0,ce._)`(${t})`}});var ue=N(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.checkStrictMode=re.getErrorPath=re.Type=re.useFunc=re.setEvaluated=re.evaluatedPropsToName=re.mergeEvaluated=re.eachItem=re.unescapeJsonPointer=re.escapeJsonPointer=re.escapeFragment=re.unescapeFragment=re.schemaRefOrVal=re.schemaHasRulesButRef=re.schemaHasRules=re.checkUnknownRules=re.alwaysValidSchema=re.toHash=void 0;var xe=Q(),nC=Gs();function oC(t){let e={};for(let r of t)e[r]=!0;return e}re.toHash=oC;function sC(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(mx(t,e),!hx(e,t.self.RULES.all))}re.alwaysValidSchema=sC;function mx(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||_x(t,`unknown keyword: "${s}"`)}re.checkUnknownRules=mx;function hx(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}re.schemaHasRules=hx;function iC(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}re.schemaHasRulesButRef=iC;function aC({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,xe._)`${r}`}return(0,xe._)`${t}${e}${(0,xe.getProperty)(n)}`}re.schemaRefOrVal=aC;function cC(t){return gx(decodeURIComponent(t))}re.unescapeFragment=cC;function uC(t){return encodeURIComponent(Dp(t))}re.escapeFragment=uC;function Dp(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=Dp;function gx(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=gx;function lC(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}re.eachItem=lC;function px({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof xe.Name?(s instanceof xe.Name?t(o,s,i):e(o,s,i),i):s instanceof xe.Name?(e(o,i,s),s):r(s,i);return a===xe.Name&&!(c instanceof xe.Name)?n(o,c):c}}re.mergeEvaluated={props:px({mergeNames:(t,e,r)=>t.if((0,xe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,xe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,xe._)`${r} || {}`).code((0,xe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,xe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,xe._)`${r} || {}`),Mp(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:yx}),items:px({mergeNames:(t,e,r)=>t.if((0,xe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,xe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,xe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,xe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function yx(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,xe._)`{}`);return e!==void 0&&Mp(t,r,e),r}re.evaluatedPropsToName=yx;function Mp(t,e,r){Object.keys(r).forEach(n=>t.assign((0,xe._)`${e}${(0,xe.getProperty)(n)}`,!0))}re.setEvaluated=Mp;var fx={};function dC(t,e){return t.scopeValue("func",{ref:e,code:fx[e.code]||(fx[e.code]=new nC._Code(e.code))})}re.useFunc=dC;var Np;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Np||(re.Type=Np={}));function pC(t,e,r){if(t instanceof xe.Name){let n=e===Np.Num;return r?n?(0,xe._)`"[" + ${t} + "]"`:(0,xe._)`"['" + ${t} + "']"`:n?(0,xe._)`"/" + ${t}`:(0,xe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,xe.getProperty)(t).toString():"/"+Dp(t)}re.getErrorPath=pC;function _x(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}re.checkStrictMode=_x});var Or=N(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var rt=Q(),fC={data:new rt.Name("data"),valCxt:new rt.Name("valCxt"),instancePath:new rt.Name("instancePath"),parentData:new rt.Name("parentData"),parentDataProperty:new rt.Name("parentDataProperty"),rootData:new rt.Name("rootData"),dynamicAnchors:new rt.Name("dynamicAnchors"),vErrors:new rt.Name("vErrors"),errors:new rt.Name("errors"),this:new rt.Name("this"),self:new rt.Name("self"),scope:new rt.Name("scope"),json:new rt.Name("json"),jsonPos:new rt.Name("jsonPos"),jsonLen:new rt.Name("jsonLen"),jsonPart:new rt.Name("jsonPart")};jp.default=fC});var ti=N(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.extendErrors=nt.resetErrorsCount=nt.reportExtraError=nt.reportError=nt.keyword$DataError=nt.keywordError=void 0;var le=Q(),ec=ue(),ct=Or();nt.keywordError={message:({keyword:t})=>(0,le.str)`must pass "${t}" keyword validation`};nt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,le.str)`"${t}" keyword must be ${e} ($data)`:(0,le.str)`"${t}" keyword is invalid ($data)`};function mC(t,e=nt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=vx(t,e,r);n??(i||a)?xx(s,c):Sx(o,(0,le._)`[${c}]`)}nt.reportError=mC;function hC(t,e=nt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=vx(t,e,r);xx(o,a),s||i||Sx(n,ct.default.vErrors)}nt.reportExtraError=hC;function gC(t,e){t.assign(ct.default.errors,e),t.if((0,le._)`${ct.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,le._)`${ct.default.vErrors}.length`,e),()=>t.assign(ct.default.vErrors,null)))}nt.resetErrorsCount=gC;function yC({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,ct.default.errors,a=>{t.const(i,(0,le._)`${ct.default.vErrors}[${a}]`),t.if((0,le._)`${i}.instancePath === undefined`,()=>t.assign((0,le._)`${i}.instancePath`,(0,le.strConcat)(ct.default.instancePath,s.errorPath))),t.assign((0,le._)`${i}.schemaPath`,(0,le.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,le._)`${i}.schema`,r),t.assign((0,le._)`${i}.data`,n))})}nt.extendErrors=yC;function xx(t,e){let r=t.const("err",e);t.if((0,le._)`${ct.default.vErrors} === null`,()=>t.assign(ct.default.vErrors,(0,le._)`[${r}]`),(0,le._)`${ct.default.vErrors}.push(${r})`),t.code((0,le._)`${ct.default.errors}++`)}function Sx(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,le._)`new ${t.ValidationError}(${e})`):(r.assign((0,le._)`${n}.errors`,e),r.return(!1))}var qn={keyword:new le.Name("keyword"),schemaPath:new le.Name("schemaPath"),params:new le.Name("params"),propertyName:new le.Name("propertyName"),message:new le.Name("message"),schema:new le.Name("schema"),parentSchema:new le.Name("parentSchema")};function vx(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,le._)`{}`:_C(t,e,r)}function _C(t,e,r={}){let{gen:n,it:o}=t,s=[xC(o,r),SC(t,r)];return vC(t,e,s),n.object(...s)}function xC({errorPath:t},{instancePath:e}){let r=e?(0,le.str)`${t}${(0,ec.getErrorPath)(e,ec.Type.Str)}`:t;return[ct.default.instancePath,(0,le.strConcat)(ct.default.instancePath,r)]}function SC({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,le.str)`${e}/${t}`;return r&&(o=(0,le.str)`${o}${(0,ec.getErrorPath)(r,ec.Type.Str)}`),[qn.schemaPath,o]}function vC(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([qn.keyword,o],[qn.params,typeof e=="function"?e(t):e||(0,le._)`{}`]),c.messages&&n.push([qn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([qn.schema,i],[qn.parentSchema,(0,le._)`${l}${d}`],[ct.default.data,s]),u&&n.push([qn.propertyName,u])}});var kx=N(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.boolOrEmptySchema=Do.topBoolOrEmptySchema=void 0;var bC=ti(),kC=Q(),EC=Or(),wC={message:"boolean schema is false"};function TC(t){let{gen:e,schema:r,validateName:n}=t;r===!1?bx(t,!1):typeof r=="object"&&r.$async===!0?e.return(EC.default.data):(e.assign((0,kC._)`${n}.errors`,null),e.return(!0))}Do.topBoolOrEmptySchema=TC;function PC(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),bx(t)):r.var(e,!0)}Do.boolOrEmptySchema=PC;function bx(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,bC.reportError)(o,wC,void 0,e)}});var zp=N(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.getRules=Mo.isJSONType=void 0;var RC=["string","number","integer","boolean","null","object","array"],$C=new Set(RC);function CC(t){return typeof t=="string"&&$C.has(t)}Mo.isJSONType=CC;function OC(){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:{}}}Mo.getRules=OC});var Lp=N(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.shouldUseRule=tn.shouldUseGroup=tn.schemaHasRulesForType=void 0;function IC({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Ex(t,n)}tn.schemaHasRulesForType=IC;function Ex(t,e){return e.rules.some(r=>wx(t,r))}tn.shouldUseGroup=Ex;function wx(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))}tn.shouldUseRule=wx});var ri=N(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.reportTypeError=ot.checkDataTypes=ot.checkDataType=ot.coerceAndCheckDataType=ot.getJSONTypes=ot.getSchemaTypes=ot.DataType=void 0;var AC=zp(),NC=Lp(),DC=ti(),X=Q(),Tx=ue(),jo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(jo||(ot.DataType=jo={}));function MC(t){let e=Px(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}ot.getSchemaTypes=MC;function Px(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(AC.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ot.getJSONTypes=Px;function jC(t,e){let{gen:r,data:n,opts:o}=t,s=zC(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,NC.schemaHasRulesForType)(t,e[0]));if(i){let a=Up(e,n,o.strictNumbers,jo.Wrong);r.if(a,()=>{s.length?LC(t,e,s):Fp(t)})}return i}ot.coerceAndCheckDataType=jC;var Rx=new Set(["string","number","integer","boolean","null"]);function zC(t,e){return e?t.filter(r=>Rx.has(r)||e==="array"&&r==="array"):[]}function LC(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,X._)`typeof ${o}`),a=n.let("coerced",(0,X._)`undefined`);s.coerceTypes==="array"&&n.if((0,X._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,X._)`${o}[0]`).assign(i,(0,X._)`typeof ${o}`).if(Up(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,X._)`${a} !== undefined`);for(let u of r)(Rx.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Fp(t),n.endIf(),n.if((0,X._)`${a} !== undefined`,()=>{n.assign(o,a),HC(t,a)});function c(u){switch(u){case"string":n.elseIf((0,X._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,X._)`"" + ${o}`).elseIf((0,X._)`${o} === null`).assign(a,(0,X._)`""`);return;case"number":n.elseIf((0,X._)`${i} == "boolean" || ${o} === null
|
|
4
|
-
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,
|
|
5
|
-
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,
|
|
6
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,X._)`[${o}]`)}}}function HC({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,X._)`${e} !== undefined`,()=>t.assign((0,X._)`${e}[${r}]`,n))}function Hp(t,e,r,n=jo.Correct){let o=n===jo.Correct?X.operators.EQ:X.operators.NEQ,s;switch(t){case"null":return(0,X._)`${e} ${o} null`;case"array":s=(0,X._)`Array.isArray(${e})`;break;case"object":s=(0,X._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,X._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,X._)`typeof ${e} ${o} ${t}`}return n===jo.Correct?s:(0,X.not)(s);function i(a=X.nil){return(0,X.and)((0,X._)`typeof ${e} == "number"`,a,r?(0,X._)`isFinite(${e})`:X.nil)}}ot.checkDataType=Hp;function Up(t,e,r,n){if(t.length===1)return Hp(t[0],e,r,n);let o,s=(0,Tx.toHash)(t);if(s.array&&s.object){let i=(0,X._)`typeof ${e} != "object"`;o=s.null?i:(0,X._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=X.nil;s.number&&delete s.integer;for(let i in s)o=(0,X.and)(o,Hp(i,e,r,n));return o}ot.checkDataTypes=Up;var UC={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,X._)`{type: ${t}}`:(0,X._)`{type: ${e}}`};function Fp(t){let e=FC(t);(0,DC.reportError)(e,UC)}ot.reportTypeError=Fp;function FC(t){let{gen:e,data:r,schema:n}=t,o=(0,Tx.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Cx=N(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.assignDefaults=void 0;var zo=Q(),ZC=ue();function qC(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)$x(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>$x(t,s,o.default))}tc.assignDefaults=qC;function $x(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,zo._)`${s}${(0,zo.getProperty)(e)}`;if(o){(0,ZC.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,zo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,zo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,zo._)`${a} = ${(0,zo.stringify)(r)}`)}});var Mt=N(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.validateUnion=he.validateArray=he.usePattern=he.callValidateCode=he.schemaProperties=he.allSchemaProperties=he.noPropertyInData=he.propertyInData=he.isOwnProperty=he.hasPropFunc=he.reportMissingProp=he.checkMissingProp=he.checkReportMissingProp=void 0;var we=Q(),Zp=ue(),rn=Or(),BC=ue();function VC(t,e){let{gen:r,data:n,it:o}=t;r.if(Bp(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,we._)`${e}`},!0),t.error()})}he.checkReportMissingProp=VC;function WC({gen:t,data:e,it:{opts:r}},n,o){return(0,we.or)(...n.map(s=>(0,we.and)(Bp(t,e,s,r.ownProperties),(0,we._)`${o} = ${s}`)))}he.checkMissingProp=WC;function KC(t,e){t.setParams({missingProperty:e},!0),t.error()}he.reportMissingProp=KC;function Ox(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,we._)`Object.prototype.hasOwnProperty`})}he.hasPropFunc=Ox;function qp(t,e,r){return(0,we._)`${Ox(t)}.call(${e}, ${r})`}he.isOwnProperty=qp;function GC(t,e,r,n){let o=(0,we._)`${e}${(0,we.getProperty)(r)} !== undefined`;return n?(0,we._)`${o} && ${qp(t,e,r)}`:o}he.propertyInData=GC;function Bp(t,e,r,n){let o=(0,we._)`${e}${(0,we.getProperty)(r)} === undefined`;return n?(0,we.or)(o,(0,we.not)(qp(t,e,r))):o}he.noPropertyInData=Bp;function Ix(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}he.allSchemaProperties=Ix;function JC(t,e){return Ix(e).filter(r=>!(0,Zp.alwaysValidSchema)(t,e[r]))}he.schemaProperties=JC;function XC({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,we._)`${t}, ${e}, ${n}${o}`:e,d=[[rn.default.instancePath,(0,we.strConcat)(rn.default.instancePath,s)],[rn.default.parentData,i.parentData],[rn.default.parentDataProperty,i.parentDataProperty],[rn.default.rootData,rn.default.rootData]];i.opts.dynamicRef&&d.push([rn.default.dynamicAnchors,rn.default.dynamicAnchors]);let f=(0,we._)`${l}, ${r.object(...d)}`;return c!==we.nil?(0,we._)`${a}.call(${c}, ${f})`:(0,we._)`${a}(${f})`}he.callValidateCode=XC;var YC=(0,we._)`new RegExp`;function QC({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,we._)`${o.code==="new RegExp"?YC:(0,BC.useFunc)(t,o)}(${r}, ${n})`})}he.usePattern=QC;function eO(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,we._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Zp.Type.Num},s),e.if((0,we.not)(s),a)})}}he.validateArray=eO;function tO(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Zp.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,we._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,we.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}he.validateUnion=tO});var Dx=N(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.validateKeywordUsage=fr.validSchemaType=fr.funcKeywordCode=fr.macroKeywordCode=void 0;var ut=Q(),Bn=Or(),rO=Mt(),nO=ti();function oO(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Nx(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:ut.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}fr.macroKeywordCode=oO;function sO(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;aO(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Nx(n,o,u),d=n.let("valid");t.block$data(d,f),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function f(){if(e.errors===!1)m(),e.modifying&&Ax(t),g(()=>t.error());else{let y=e.async?h():p();e.modifying&&Ax(t),g(()=>iO(t,y))}}function h(){let y=n.let("ruleErrs",null);return n.try(()=>m((0,ut._)`await `),_=>n.assign(d,!1).if((0,ut._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,ut._)`${_}.errors`),()=>n.throw(_))),y}function p(){let y=(0,ut._)`${l}.errors`;return n.assign(y,null),m(ut.nil),y}function m(y=e.async?(0,ut._)`await `:ut.nil){let _=c.opts.passContext?Bn.default.this:Bn.default.self,x=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ut._)`${y}${(0,rO.callValidateCode)(t,l,_,x)}`,e.modifying)}function g(y){var _;n.if((0,ut.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}fr.funcKeywordCode=sO;function Ax(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ut._)`${n.parentData}[${n.parentDataProperty}]`))}function iO(t,e){let{gen:r}=t;r.if((0,ut._)`Array.isArray(${e})`,()=>{r.assign(Bn.default.vErrors,(0,ut._)`${Bn.default.vErrors} === null ? ${e} : ${Bn.default.vErrors}.concat(${e})`).assign(Bn.default.errors,(0,ut._)`${Bn.default.vErrors}.length`),(0,nO.extendErrors)(t)},()=>t.error())}function aO({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Nx(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,ut.stringify)(r)})}function cO(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")}fr.validSchemaType=cO;function uO({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}fr.validateKeywordUsage=uO});var jx=N(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.extendSubschemaMode=nn.extendSubschemaData=nn.getSubschema=void 0;var mr=Q(),Mx=ue();function lO(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,mr._)`${t.schemaPath}${(0,mr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,mr._)`${t.schemaPath}${(0,mr.getProperty)(e)}${(0,mr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Mx.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}nn.getSubschema=lO;function dO(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,f=a.let("data",(0,mr._)`${e.data}${(0,mr.getProperty)(r)}`,!0);c(f),t.errorPath=(0,mr.str)`${u}${(0,Mx.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,mr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof mr.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}nn.extendSubschemaData=dO;function pO(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}nn.extendSubschemaMode=pO});var Vp=N((oB,zx)=>{"use strict";zx.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Hx=N((sB,Lx)=>{"use strict";var on=Lx.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};rc(e,n,o,t,"",t)};on.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};on.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};on.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};on.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 rc(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in on.arrayKeywords)for(var f=0;f<d.length;f++)rc(t,e,r,d[f],o+"/"+l+"/"+f,s,o,l,n,f)}else if(l in on.propsKeywords){if(d&&typeof d=="object")for(var h in d)rc(t,e,r,d[h],o+"/"+l+"/"+fO(h),s,o,l,n,h)}else(l in on.keywords||t.allKeys&&!(l in on.skipKeywords))&&rc(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function fO(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ni=N(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.getSchemaRefs=_t.resolveUrl=_t.normalizeId=_t._getFullPath=_t.getFullPath=_t.inlineRef=void 0;var mO=ue(),hO=Vp(),gO=Hx(),yO=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function _O(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Wp(t):e?Ux(t)<=e:!1}_t.inlineRef=_O;var xO=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Wp(t){for(let e in t){if(xO.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Wp)||typeof r=="object"&&Wp(r))return!0}return!1}function Ux(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!yO.has(r)&&(typeof t[r]=="object"&&(0,mO.eachItem)(t[r],n=>e+=Ux(n)),e===1/0))return 1/0}return e}function Fx(t,e="",r){r!==!1&&(e=Lo(e));let n=t.parse(e);return Zx(t,n)}_t.getFullPath=Fx;function Zx(t,e){return t.serialize(e).split("#")[0]+"#"}_t._getFullPath=Zx;var SO=/#\/?$/;function Lo(t){return t?t.replace(SO,""):""}_t.normalizeId=Lo;function vO(t,e,r){return r=Lo(r),t.resolve(e,r)}_t.resolveUrl=vO;var bO=/^[a-z_][-a-z0-9._]*$/i;function kO(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Lo(t[r]||e),s={"":o},i=Fx(n,o,!1),a={},c=new Set;return gO(t,{allKeys:!0},(d,f,h,p)=>{if(p===void 0)return;let m=i+f,g=s[p];typeof d[r]=="string"&&(g=y.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[f]=g;function y(x){let S=this.opts.uriResolver.resolve;if(x=Lo(g?S(g,x):x),c.has(x))throw l(x);c.add(x);let k=this.refs[x];return typeof k=="string"&&(k=this.refs[k]),typeof k=="object"?u(d,k.schema,x):x!==Lo(m)&&(x[0]==="#"?(u(d,a[x],x),a[x]=d):this.refs[x]=m),x}function _(x){if(typeof x=="string"){if(!bO.test(x))throw new Error(`invalid anchor "${x}"`);y.call(this,`#${x}`)}}}),a;function u(d,f,h){if(f!==void 0&&!hO(d,f))throw l(h)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}_t.getSchemaRefs=kO});var ii=N(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.getData=sn.KeywordCxt=sn.validateFunctionCode=void 0;var Kx=kx(),qx=ri(),Gp=Lp(),nc=ri(),EO=Cx(),si=Dx(),Kp=jx(),F=Q(),G=Or(),wO=ni(),Ir=ue(),oi=ti();function TO(t){if(Xx(t)&&(Yx(t),Jx(t))){$O(t);return}Gx(t,()=>(0,Kx.topBoolOrEmptySchema)(t))}sn.validateFunctionCode=TO;function Gx({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,F._)`${G.default.data}, ${G.default.valCxt}`,n.$async,()=>{t.code((0,F._)`"use strict"; ${Bx(r,o)}`),RO(t,o),t.code(s)}):t.func(e,(0,F._)`${G.default.data}, ${PO(o)}`,n.$async,()=>t.code(Bx(r,o)).code(s))}function PO(t){return(0,F._)`{${G.default.instancePath}="", ${G.default.parentData}, ${G.default.parentDataProperty}, ${G.default.rootData}=${G.default.data}${t.dynamicRef?(0,F._)`, ${G.default.dynamicAnchors}={}`:F.nil}}={}`}function RO(t,e){t.if(G.default.valCxt,()=>{t.var(G.default.instancePath,(0,F._)`${G.default.valCxt}.${G.default.instancePath}`),t.var(G.default.parentData,(0,F._)`${G.default.valCxt}.${G.default.parentData}`),t.var(G.default.parentDataProperty,(0,F._)`${G.default.valCxt}.${G.default.parentDataProperty}`),t.var(G.default.rootData,(0,F._)`${G.default.valCxt}.${G.default.rootData}`),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,F._)`${G.default.valCxt}.${G.default.dynamicAnchors}`)},()=>{t.var(G.default.instancePath,(0,F._)`""`),t.var(G.default.parentData,(0,F._)`undefined`),t.var(G.default.parentDataProperty,(0,F._)`undefined`),t.var(G.default.rootData,G.default.data),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,F._)`{}`)})}function $O(t){let{schema:e,opts:r,gen:n}=t;Gx(t,()=>{r.$comment&&e.$comment&&eS(t),NO(t),n.let(G.default.vErrors,null),n.let(G.default.errors,0),r.unevaluated&&CO(t),Qx(t),jO(t)})}function CO(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,F._)`${r}.evaluated`),e.if((0,F._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,F._)`${t.evaluated}.props`,(0,F._)`undefined`)),e.if((0,F._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,F._)`${t.evaluated}.items`,(0,F._)`undefined`))}function Bx(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,F._)`/*# sourceURL=${r} */`:F.nil}function OO(t,e){if(Xx(t)&&(Yx(t),Jx(t))){IO(t,e);return}(0,Kx.boolOrEmptySchema)(t,e)}function Jx({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 Xx(t){return typeof t.schema!="boolean"}function IO(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&eS(t),DO(t),MO(t);let s=n.const("_errs",G.default.errors);Qx(t,s),n.var(e,(0,F._)`${s} === ${G.default.errors}`)}function Yx(t){(0,Ir.checkUnknownRules)(t),AO(t)}function Qx(t,e){if(t.opts.jtd)return Vx(t,[],!1,e);let r=(0,qx.getSchemaTypes)(t.schema),n=(0,qx.coerceAndCheckDataType)(t,r);Vx(t,r,!n,e)}function AO(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Ir.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function NO(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Ir.checkStrictMode)(t,"default is ignored in the schema root")}function DO(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,wO.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function MO(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function eS({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,F._)`${G.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,F.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,F._)`${G.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function jO(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,F._)`${G.default.errors} === 0`,()=>e.return(G.default.data),()=>e.throw((0,F._)`new ${o}(${G.default.vErrors})`)):(e.assign((0,F._)`${n}.errors`,G.default.vErrors),s.unevaluated&&zO(t),e.return((0,F._)`${G.default.errors} === 0`))}function zO({gen:t,evaluated:e,props:r,items:n}){r instanceof F.Name&&t.assign((0,F._)`${e}.props`,r),n instanceof F.Name&&t.assign((0,F._)`${e}.items`,n)}function Vx(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Ir.schemaHasRulesButRef)(s,l))){o.block(()=>rS(t,"$ref",l.all.$ref.definition));return}c.jtd||LO(t,e),o.block(()=>{for(let f of l.rules)d(f);d(l.post)});function d(f){(0,Gp.shouldUseGroup)(s,f)&&(f.type?(o.if((0,nc.checkDataType)(f.type,i,c.strictNumbers)),Wx(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,nc.reportTypeError)(t)),o.endIf()):Wx(t,f),a||o.if((0,F._)`${G.default.errors} === ${n||0}`))}}function Wx(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,EO.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Gp.shouldUseRule)(n,s)&&rS(t,s.keyword,s.definition,e.type)})}function LO(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(HO(t,e),t.opts.allowUnionTypes||UO(t,e),FO(t,t.dataTypes))}function HO(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{tS(t.dataTypes,r)||Jp(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),qO(t,e)}}function UO(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Jp(t,"use allowUnionTypes to allow union type keyword")}function FO(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Gp.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>ZO(e,i))&&Jp(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function ZO(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function tS(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function qO(t,e){let r=[];for(let n of t.dataTypes)tS(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Jp(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Ir.checkStrictMode)(t,e,t.opts.strictTypes)}var oc=class{constructor(e,r,n){if((0,si.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,Ir.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",nS(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,si.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",G.default.errors))}result(e,r,n){this.failResult((0,F.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,F.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,F._)`${r} !== undefined && (${(0,F.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?oi.reportExtraError:oi.reportError)(this,this.def.error,r)}$dataError(){(0,oi.reportError)(this,this.def.$dataError||oi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,oi.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=F.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=F.nil,r=F.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,F.or)((0,F._)`${o} === undefined`,r)),e!==F.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==F.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,F.or)(i(),a());function i(){if(n.length){if(!(r instanceof F.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,F._)`${(0,nc.checkDataTypes)(c,r,s.opts.strictNumbers,nc.DataType.Wrong)}`}return F.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,F._)`!${c}(${r})`}return F.nil}}subschema(e,r){let n=(0,Kp.getSubschema)(this.it,e);(0,Kp.extendSubschemaData)(n,this.it,e),(0,Kp.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return OO(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Ir.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Ir.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,F.Name)),!0}};sn.KeywordCxt=oc;function rS(t,e,r,n){let o=new oc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,si.funcKeywordCode)(o,r):"macro"in r?(0,si.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,si.funcKeywordCode)(o,r)}var BO=/^\/(?:[^~]|~0|~1)*$/,VO=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function nS(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return G.default.rootData;if(t[0]==="/"){if(!BO.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=G.default.rootData}else{let u=VO.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,F._)`${s}${(0,F.getProperty)((0,Ir.unescapeJsonPointer)(u))}`,i=(0,F._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}sn.getData=nS});var sc=N(Yp=>{"use strict";Object.defineProperty(Yp,"__esModule",{value:!0});var Xp=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Yp.default=Xp});var ai=N(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var Qp=ni(),ef=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Qp.resolveUrl)(e,r,n),this.missingSchema=(0,Qp.normalizeId)((0,Qp.getFullPath)(e,this.missingRef))}};tf.default=ef});var ac=N(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.resolveSchema=jt.getCompilingSchema=jt.resolveRef=jt.compileSchema=jt.SchemaEnv=void 0;var Qt=Q(),WO=sc(),Vn=Or(),er=ni(),oS=ue(),KO=ii(),Ho=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,er.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=Ho;function nf(t){let e=sS.call(this,t);if(e)return e;let r=(0,er.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Qt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:WO.default,code:(0,Qt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Vn.default.data,parentData:Vn.default.parentData,parentDataProperty:Vn.default.parentDataProperty,dataNames:[Vn.default.data],dataPathArr:[Qt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Qt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Qt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Qt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,KO.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Vn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let h=new Function(`${Vn.default.self}`,`${Vn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:m}=u;h.evaluated={props:p instanceof Qt.Name?void 0:p,items:m instanceof Qt.Name?void 0:m,dynamicProps:p instanceof Qt.Name,dynamicItems:m instanceof Qt.Name},h.source&&(h.source.evaluated=(0,Qt.stringify)(h.evaluated))}return t.validate=h,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}jt.compileSchema=nf;function GO(t,e,r){var n;r=(0,er.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=YO.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Ho({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=JO.call(this,s)}jt.resolveRef=GO;function JO(t){return(0,er.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:nf.call(this,t)}function sS(t){for(let e of this._compilations)if(XO(e,t))return e}jt.getCompilingSchema=sS;function XO(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function YO(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ic.call(this,t,e)}function ic(t,e){let r=this.opts.uriResolver.parse(e),n=(0,er._getFullPath)(this.opts.uriResolver,r),o=(0,er.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return rf.call(this,r,t);let s=(0,er.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ic.call(this,t,i);return typeof a?.schema!="object"?void 0:rf.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||nf.call(this,i),s===(0,er.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,er.resolveUrl)(this.opts.uriResolver,o,u)),new Ho({schema:a,schemaId:c,root:t,baseId:o})}return rf.call(this,r,i)}}jt.resolveSchema=ic;var QO=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function rf(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,oS.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!QO.has(a)&&u&&(e=(0,er.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,oS.schemaHasRulesButRef)(r,this.RULES)){let a=(0,er.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ic.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Ho({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var iS=N((dB,eI)=>{eI.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 sf=N((pB,lS)=>{"use strict";var tI=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),cS=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 of(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 rI=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function aS(t){return t.length=0,!0}function nI(t,e,r){if(t.length){let n=of(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function oI(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=nI;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=aS}else{o.push(u);continue}}return o.length&&(a===aS?r.zone=o.join(""):i?n.push(o.join("")):n.push(of(o))),r.address=n.join(""),r}function uS(t){if(sI(t,":")<2)return{host:t,isIPV6:!1};let e=oI(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 sI(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function iI(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function aI(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 cI(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!cS(r)){let n=uS(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}lS.exports={nonSimpleDomain:rI,recomposeAuthority:cI,normalizeComponentEncoding:aI,removeDotSegments:iI,isIPv4:cS,isUUID:tI,normalizeIPv6:uS,stringArrayToHexStripped:of}});var hS=N((fB,mS)=>{"use strict";var{isUUID:uI}=sf(),lI=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,dI=["http","https","ws","wss","urn","urn:uuid"];function pI(t){return dI.indexOf(t)!==-1}function af(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 dS(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function pS(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 fI(t){return t.secure=af(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function mI(t){if((t.port===(af(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 hI(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(lI);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=cf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function gI(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=cf(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function yI(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!uI(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function _I(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var fS={scheme:"http",domainHost:!0,parse:dS,serialize:pS},xI={scheme:"https",domainHost:fS.domainHost,parse:dS,serialize:pS},cc={scheme:"ws",domainHost:!0,parse:fI,serialize:mI},SI={scheme:"wss",domainHost:cc.domainHost,parse:cc.parse,serialize:cc.serialize},vI={scheme:"urn",parse:hI,serialize:gI,skipNormalize:!0},bI={scheme:"urn:uuid",parse:yI,serialize:_I,skipNormalize:!0},uc={http:fS,https:xI,ws:cc,wss:SI,urn:vI,"urn:uuid":bI};Object.setPrototypeOf(uc,null);function cf(t){return t&&(uc[t]||uc[t.toLowerCase()])||void 0}mS.exports={wsIsSecure:af,SCHEMES:uc,isValidSchemeName:pI,getSchemeHandler:cf}});var _S=N((mB,dc)=>{"use strict";var{normalizeIPv6:kI,removeDotSegments:ci,recomposeAuthority:EI,normalizeComponentEncoding:lc,isIPv4:wI,nonSimpleDomain:TI}=sf(),{SCHEMES:PI,getSchemeHandler:gS}=hS();function RI(t,e){return typeof t=="string"?t=hr(Ar(t,e),e):typeof t=="object"&&(t=Ar(hr(t,e),e)),t}function $I(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=yS(Ar(t,n),Ar(e,n),n,!0);return n.skipEscape=!0,hr(o,n)}function yS(t,e,r,n){let o={};return n||(t=Ar(hr(t,r),r),e=Ar(hr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ci(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ci(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ci(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=ci(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function CI(t,e,r){return typeof t=="string"?(t=unescape(t),t=hr(lc(Ar(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=hr(lc(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=hr(lc(Ar(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=hr(lc(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function hr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=gS(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=EI(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=ci(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var OI=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Ar(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(OI);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(wI(n.host)===!1){let c=kI(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=gS(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&TI(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 uf={SCHEMES:PI,normalize:RI,resolve:$I,resolveComponent:yS,equal:CI,serialize:hr,parse:Ar};dc.exports=uf;dc.exports.default=uf;dc.exports.fastUri=uf});var SS=N(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var xS=_S();xS.code='require("ajv/dist/runtime/uri").default';lf.default=xS});var RS=N(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.CodeGen=Je.Name=Je.nil=Je.stringify=Je.str=Je._=Je.KeywordCxt=void 0;var II=ii();Object.defineProperty(Je,"KeywordCxt",{enumerable:!0,get:function(){return II.KeywordCxt}});var Uo=Q();Object.defineProperty(Je,"_",{enumerable:!0,get:function(){return Uo._}});Object.defineProperty(Je,"str",{enumerable:!0,get:function(){return Uo.str}});Object.defineProperty(Je,"stringify",{enumerable:!0,get:function(){return Uo.stringify}});Object.defineProperty(Je,"nil",{enumerable:!0,get:function(){return Uo.nil}});Object.defineProperty(Je,"Name",{enumerable:!0,get:function(){return Uo.Name}});Object.defineProperty(Je,"CodeGen",{enumerable:!0,get:function(){return Uo.CodeGen}});var AI=sc(),wS=ai(),NI=zp(),ui=ac(),DI=Q(),li=ni(),pc=ri(),pf=ue(),vS=iS(),MI=SS(),TS=(t,e)=>new RegExp(t,e);TS.code="new RegExp";var jI=["removeAdditional","useDefaults","coerceTypes"],zI=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),LI={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."},HI={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},bS=200;function UI(t){var e,r,n,o,s,i,a,c,u,l,d,f,h,p,m,g,y,_,x,S,k,R,$,C,A;let W=t.strict,T=(e=t.code)===null||e===void 0?void 0:e.optimize,E=T===!0||T===void 0?1:T||0,H=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:TS,pe=(o=t.uriResolver)!==null&&o!==void 0?o:MI.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:W)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:W)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:W)!==null&&l!==void 0?l:"log",strictTuples:(f=(d=t.strictTuples)!==null&&d!==void 0?d:W)!==null&&f!==void 0?f:"log",strictRequired:(p=(h=t.strictRequired)!==null&&h!==void 0?h:W)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:E,regExp:H}:{optimize:E,regExp:H},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:bS,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:bS,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(S=t.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(k=t.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(R=t.validateSchema)!==null&&R!==void 0?R:!0,validateFormats:($=t.validateFormats)!==null&&$!==void 0?$:!0,unicodeRegExp:(C=t.unicodeRegExp)!==null&&C!==void 0?C:!0,int32range:(A=t.int32range)!==null&&A!==void 0?A:!0,uriResolver:pe}}var di=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,...UI(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new DI.ValueScope({scope:{},prefixes:zI,es5:r,lines:n}),this.logger=WI(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,NI.getRules)(),kS.call(this,LI,e,"NOT SUPPORTED"),kS.call(this,HI,e,"DEPRECATED","warn"),this._metaOpts=BI.call(this),e.formats&&ZI.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&qI.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),FI.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=vS;n==="id"&&(o={...vS},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let f=this._addSchema(l,d);return f.validate||i.call(this,f)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof wS.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,li.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=ES.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ui.SchemaEnv({schema:{},schemaId:n});if(r=ui.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=ES.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,li.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(GI.call(this,n,r),!r)return(0,pf.eachItem)(n,s=>df.call(this,s)),this;XI.call(this,r);let o={...r,type:(0,pc.getJSONTypes)(r.type),schemaType:(0,pc.getJSONTypes)(r.schemaType)};return(0,pf.eachItem)(n,o.type.length===0?s=>df.call(this,s,o):s=>o.type.forEach(i=>df.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=PS(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,li.normalizeId)(i||n);let u=li.getSchemaRefs.call(this,e,n);return c=new ui.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):ui.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{ui.compileSchema.call(this,e)}finally{this.opts=r}}};di.ValidationError=AI.default;di.MissingRefError=wS.default;Je.default=di;function kS(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function ES(t){return t=(0,li.normalizeId)(t),this.schemas[t]||this.refs[t]}function FI(){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 ZI(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function qI(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 BI(){let t={...this.opts};for(let e of jI)delete t[e];return t}var VI={log(){},warn(){},error(){}};function WI(t){if(t===!1)return VI;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 KI=/^[a-z_$][a-z0-9_$:-]*$/i;function GI(t,e){let{RULES:r}=this;if((0,pf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!KI.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 df(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,pc.getJSONTypes)(e.type),schemaType:(0,pc.getJSONTypes)(e.schemaType)}};e.before?JI.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function JI(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function XI(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=PS(e)),t.validateSchema=this.compile(e,!0))}var YI={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function PS(t){return{anyOf:[t,YI]}}});var $S=N(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var QI={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ff.default=QI});var AS=N(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.callRef=Wn.getValidate=void 0;var eA=ai(),CS=Mt(),xt=Q(),Fo=Or(),OS=ac(),fc=ue(),tA={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=OS.resolveRef.call(c,u,o,r);if(l===void 0)throw new eA.default(n.opts.uriResolver,o,r);if(l instanceof OS.SchemaEnv)return f(l);return h(l);function d(){if(s===u)return mc(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return mc(t,(0,xt._)`${p}.validate`,u,u.$async)}function f(p){let m=IS(t,p);mc(t,m,p,p.$async)}function h(p){let m=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,xt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:xt.nil,topSchemaRef:m,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function IS(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,xt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Wn.getValidate=IS;function mc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Fo.default.this:xt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=o.let("valid");o.try(()=>{o.code((0,xt._)`await ${(0,CS.callValidateCode)(t,e,u)}`),h(e),i||o.assign(p,!0)},m=>{o.if((0,xt._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),f(m),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,CS.callValidateCode)(t,e,u),()=>h(e),()=>f(e))}function f(p){let m=(0,xt._)`${p}.errors`;o.assign(Fo.default.vErrors,(0,xt._)`${Fo.default.vErrors} === null ? ${m} : ${Fo.default.vErrors}.concat(${m})`),o.assign(Fo.default.errors,(0,xt._)`${Fo.default.vErrors}.length`)}function h(p){var m;if(!s.opts.unevaluated)return;let g=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=fc.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,xt._)`${p}.evaluated.props`);s.props=fc.mergeEvaluated.props(o,y,s.props,xt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=fc.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,xt._)`${p}.evaluated.items`);s.items=fc.mergeEvaluated.items(o,y,s.items,xt.Name)}}}Wn.callRef=mc;Wn.default=tA});var NS=N(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var rA=$S(),nA=AS(),oA=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",rA.default,nA.default];mf.default=oA});var DS=N(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var hc=Q(),an=hc.operators,gc={maximum:{okStr:"<=",ok:an.LTE,fail:an.GT},minimum:{okStr:">=",ok:an.GTE,fail:an.LT},exclusiveMaximum:{okStr:"<",ok:an.LT,fail:an.GTE},exclusiveMinimum:{okStr:">",ok:an.GT,fail:an.LTE}},sA={message:({keyword:t,schemaCode:e})=>(0,hc.str)`must be ${gc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,hc._)`{comparison: ${gc[t].okStr}, limit: ${e}}`},iA={keyword:Object.keys(gc),type:"number",schemaType:"number",$data:!0,error:sA,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,hc._)`${r} ${gc[e].fail} ${n} || isNaN(${r})`)}};hf.default=iA});var MS=N(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var pi=Q(),aA={message:({schemaCode:t})=>(0,pi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,pi._)`{multipleOf: ${t}}`},cA={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:aA,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,pi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,pi._)`${i} !== parseInt(${i})`;t.fail$data((0,pi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};gf.default=cA});var zS=N(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});function jS(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}yf.default=jS;jS.code='require("ajv/dist/runtime/ucs2length").default'});var LS=N(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var Kn=Q(),uA=ue(),lA=zS(),dA={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Kn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Kn._)`{limit: ${t}}`},pA={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:dA,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Kn.operators.GT:Kn.operators.LT,i=o.opts.unicode===!1?(0,Kn._)`${r}.length`:(0,Kn._)`${(0,uA.useFunc)(t.gen,lA.default)}(${r})`;t.fail$data((0,Kn._)`${i} ${s} ${n}`)}};_f.default=pA});var HS=N(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var fA=Mt(),mA=ue(),Zo=Q(),hA={message:({schemaCode:t})=>(0,Zo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Zo._)`{pattern: ${t}}`},gA={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:hA,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Zo._)`new RegExp`:(0,mA.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Zo._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Zo._)`!${l}`)}else{let c=(0,fA.usePattern)(t,o);t.fail$data((0,Zo._)`!${c}.test(${r})`)}}};xf.default=gA});var US=N(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var fi=Q(),yA={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,fi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,fi._)`{limit: ${t}}`},_A={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:yA,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?fi.operators.GT:fi.operators.LT;t.fail$data((0,fi._)`Object.keys(${r}).length ${o} ${n}`)}};Sf.default=_A});var FS=N(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var mi=Mt(),hi=Q(),xA=ue(),SA={message:({params:{missingProperty:t}})=>(0,hi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,hi._)`{missingProperty: ${t}}`},vA={keyword:"required",type:"object",schemaType:"array",$data:!0,error:SA,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let h=t.parentSchema.properties,{definedProperties:p}=t.it;for(let m of r)if(h?.[m]===void 0&&!p.has(m)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,xA.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(hi.nil,d);else for(let h of r)(0,mi.checkReportMissingProp)(t,h)}function l(){let h=e.let("missing");if(c||s){let p=e.let("valid",!0);t.block$data(p,()=>f(h,p)),t.ok(p)}else e.if((0,mi.checkMissingProp)(t,r,h)),(0,mi.reportMissingProp)(t,h),e.else()}function d(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,mi.noPropertyInData)(e,o,h,a.ownProperties),()=>t.error())})}function f(h,p){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(p,(0,mi.propertyInData)(e,o,h,a.ownProperties)),e.if((0,hi.not)(p),()=>{t.error(),e.break()})},hi.nil)}}};vf.default=vA});var ZS=N(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var gi=Q(),bA={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,gi.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,gi._)`{limit: ${t}}`},kA={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:bA,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?gi.operators.GT:gi.operators.LT;t.fail$data((0,gi._)`${r}.length ${o} ${n}`)}};bf.default=kA});var yc=N(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var qS=Vp();qS.code='require("ajv/dist/runtime/equal").default';kf.default=qS});var BS=N(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var Ef=ri(),Xe=Q(),EA=ue(),wA=yc(),TA={message:({params:{i:t,j:e}})=>(0,Xe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Xe._)`{i: ${t}, j: ${e}}`},PA={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:TA,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Ef.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Xe._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,Xe._)`${r}.length`),m=e.let("j");t.setParams({i:p,j:m}),e.assign(c,!0),e.if((0,Xe._)`${p} > 1`,()=>(d()?f:h)(p,m))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,m){let g=e.name("item"),y=(0,Ef.checkDataTypes)(u,g,a.opts.strictNumbers,Ef.DataType.Wrong),_=e.const("indices",(0,Xe._)`{}`);e.for((0,Xe._)`;${p}--;`,()=>{e.let(g,(0,Xe._)`${r}[${p}]`),e.if(y,(0,Xe._)`continue`),u.length>1&&e.if((0,Xe._)`typeof ${g} == "string"`,(0,Xe._)`${g} += "_"`),e.if((0,Xe._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(m,(0,Xe._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,Xe._)`${_}[${g}] = ${p}`)})}function h(p,m){let g=(0,EA.useFunc)(e,wA.default),y=e.name("outer");e.label(y).for((0,Xe._)`;${p}--;`,()=>e.for((0,Xe._)`${m} = ${p}; ${m}--;`,()=>e.if((0,Xe._)`${g}(${r}[${p}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};wf.default=PA});var VS=N(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var Tf=Q(),RA=ue(),$A=yc(),CA={message:"must be equal to constant",params:({schemaCode:t})=>(0,Tf._)`{allowedValue: ${t}}`},OA={keyword:"const",$data:!0,error:CA,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Tf._)`!${(0,RA.useFunc)(e,$A.default)}(${r}, ${o})`):t.fail((0,Tf._)`${s} !== ${r}`)}};Pf.default=OA});var WS=N(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var yi=Q(),IA=ue(),AA=yc(),NA={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,yi._)`{allowedValues: ${t}}`},DA={keyword:"enum",schemaType:"array",$data:!0,error:NA,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,IA.useFunc)(e,AA.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let h=e.const("vSchema",s);l=(0,yi.or)(...o.map((p,m)=>f(h,m)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,h=>e.if((0,yi._)`${u()}(${r}, ${h})`,()=>e.assign(l,!0).break()))}function f(h,p){let m=o[p];return typeof m=="object"&&m!==null?(0,yi._)`${u()}(${r}, ${h}[${p}])`:(0,yi._)`${r} === ${m}`}}};Rf.default=DA});var KS=N($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var MA=DS(),jA=MS(),zA=LS(),LA=HS(),HA=US(),UA=FS(),FA=ZS(),ZA=BS(),qA=VS(),BA=WS(),VA=[MA.default,jA.default,zA.default,LA.default,HA.default,UA.default,FA.default,ZA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},qA.default,BA.default];$f.default=VA});var Of=N(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.validateAdditionalItems=void 0;var Gn=Q(),Cf=ue(),WA={message:({params:{len:t}})=>(0,Gn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Gn._)`{limit: ${t}}`},KA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:WA,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Cf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}GS(t,n)}};function GS(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Gn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Gn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Cf.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Gn._)`${a} <= ${e.length}`);r.if((0,Gn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Cf.Type.Num},u),i.allErrors||r.if((0,Gn.not)(u),()=>r.break())})}}_i.validateAdditionalItems=GS;_i.default=KA});var If=N(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.validateTuple=void 0;var JS=Q(),_c=ue(),GA=Mt(),JA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return XS(t,"additionalItems",e);r.items=!0,!(0,_c.alwaysValidSchema)(r,e)&&t.ok((0,GA.validateArray)(t))}};function XS(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=_c.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,JS._)`${s}.length`);r.forEach((d,f)=>{(0,_c.alwaysValidSchema)(a,d)||(n.if((0,JS._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){let{opts:f,errSchemaPath:h}=a,p=r.length,m=p===d.minItems&&(p===d.maxItems||d[e]===!1);if(f.strictTuples&&!m){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,_c.checkStrictMode)(a,g,f.strictTuples)}}}xi.validateTuple=XS;xi.default=JA});var YS=N(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var XA=If(),YA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,XA.validateTuple)(t,"items")};Af.default=YA});var ev=N(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var QS=Q(),QA=ue(),eN=Mt(),tN=Of(),rN={message:({params:{len:t}})=>(0,QS.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,QS._)`{limit: ${t}}`},nN={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:rN,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,QA.alwaysValidSchema)(n,e)&&(o?(0,tN.validateAdditionalItems)(t,o):t.ok((0,eN.validateArray)(t)))}};Nf.default=nN});var tv=N(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var zt=Q(),xc=ue(),oN={message:({params:{min:t,max:e}})=>e===void 0?(0,zt.str)`must contain at least ${t} valid item(s)`:(0,zt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,zt._)`{minContains: ${t}}`:(0,zt._)`{minContains: ${t}, maxContains: ${e}}`},sN={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:oN,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,zt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,xc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,xc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,xc.alwaysValidSchema)(s,r)){let m=(0,zt._)`${l} >= ${i}`;a!==void 0&&(m=(0,zt._)`${m} && ${l} <= ${a}`),t.pass(m);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?h(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,zt._)`${o}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){let m=e.name("_valid"),g=e.let("count",0);h(m,()=>e.if(m,()=>p(g)))}function h(m,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:xc.Type.Num,compositeRule:!0},m),g()})}function p(m){e.code((0,zt._)`${m}++`),a===void 0?e.if((0,zt._)`${m} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,zt._)`${m} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,zt._)`${m} >= ${i}`,()=>e.assign(d,!0)))}}};Df.default=sN});var ov=N(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.validateSchemaDeps=gr.validatePropertyDeps=gr.error=void 0;var Mf=Q(),iN=ue(),Si=Mt();gr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Mf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Mf._)`{property: ${t},
|
|
7
|
-
missingProperty: ${
|
|
2
|
+
var NT=Object.create;var Yu=Object.defineProperty;var DT=Object.getOwnPropertyDescriptor;var MT=Object.getOwnPropertyNames;var jT=Object.getPrototypeOf,zT=Object.prototype.hasOwnProperty;var X=(t,e)=>()=>(t&&(e=t(t=0)),e);var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),De=(t,e)=>{for(var n in e)Yu(t,n,{get:e[n],enumerable:!0})},LT=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of MT(e))!zT.call(t,o)&&o!==n&&Yu(t,o,{get:()=>e[o],enumerable:!(r=DT(e,o))||r.enumerable});return t};var jg=(t,e,n)=>(n=t!=null?NT(jT(t)):{},LT(e||!t||!t.__esModule?Yu(n,"default",{value:t,enumerable:!0}):n,t));var Qs=I(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.regexpCode=de.getEsmExportName=de.getProperty=de.safeStringify=de.stringify=de.strConcat=de.addCodeArg=de.str=de._=de.nil=de._Code=de.Name=de.IDENTIFIER=de._CodeOrName=void 0;var Xs=class{};de._CodeOrName=Xs;de.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Fr=class extends Xs{constructor(e){if(super(),!de.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}}};de.Name=Fr;var jt=class extends Xs{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Fr&&(n[r.str]=(n[r.str]||0)+1),n),{})}};de._Code=jt;de.nil=new jt("");function AS(t,...e){let n=[t[0]],r=0;for(;r<e.length;)Np(n,e[r]),n.push(t[++r]);return new jt(n)}de._=AS;var Ap=new jt("+");function NS(t,...e){let n=[Ys(t[0])],r=0;for(;r<e.length;)n.push(Ap),Np(n,e[r]),n.push(Ap,Ys(t[++r]));return M$(n),new jt(n)}de.str=NS;function Np(t,e){e instanceof jt?t.push(...e._items):e instanceof Fr?t.push(e):t.push(L$(e))}de.addCodeArg=Np;function M$(t){let e=1;for(;e<t.length-1;){if(t[e]===Ap){let n=j$(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function j$(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Fr||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 Fr))return`"${t}${e.slice(1)}`}function z$(t,e){return e.emptyStr()?t:t.emptyStr()?e:NS`${t}${e}`}de.strConcat=z$;function L$(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ys(Array.isArray(t)?t.join(","):t)}function H$(t){return new jt(Ys(t))}de.stringify=H$;function Ys(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}de.safeStringify=Ys;function U$(t){return typeof t=="string"&&de.IDENTIFIER.test(t)?new jt(`.${t}`):AS`[${t}]`}de.getProperty=U$;function F$(t){if(typeof t=="string"&&de.IDENTIFIER.test(t))return new jt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}de.getEsmExportName=F$;function Z$(t){return new jt(t.toString())}de.regexpCode=Z$});var jp=I(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.ValueScope=St.ValueScopeName=St.Scope=St.varKinds=St.UsedValueState=void 0;var _t=Qs(),Dp=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Qa;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Qa||(St.UsedValueState=Qa={}));St.varKinds={const:new _t.Name("const"),let:new _t.Name("let"),var:new _t.Name("var")};var ec=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof _t.Name?e:this.name(e)}name(e){return new _t.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};St.Scope=ec;var tc=class extends _t.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,_t._)`.${new _t.Name(n)}[${r}]`}};St.ValueScopeName=tc;var B$=(0,_t._)`\n`,Mp=class extends ec{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?B$:_t.nil}}get(){return this._scope}name(e){return new tc(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(r=n.key)!==null&&r!==void 0?r:n.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=n.ref,o.setValue(n,{property:s,itemIndex:u}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,_t._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let s=_t.nil;for(let i in e){let a=e[i];if(!a)continue;let c=r[i]=r[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Qa.Started);let l=n(u);if(l){let d=this.opts.es5?St.varKinds.var:St.varKinds.const;s=(0,_t._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,_t._)`${s}${l}${this.opts._n}`;else throw new Dp(u);c.set(u,Qa.Completed)})}return s}};St.ValueScope=Mp});var ee=I(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.or=te.and=te.not=te.CodeGen=te.operators=te.varKinds=te.ValueScopeName=te.ValueScope=te.Scope=te.Name=te.regexpCode=te.stringify=te.getProperty=te.nil=te.strConcat=te.str=te._=void 0;var ce=Qs(),Qt=jp(),tr=Qs();Object.defineProperty(te,"_",{enumerable:!0,get:function(){return tr._}});Object.defineProperty(te,"str",{enumerable:!0,get:function(){return tr.str}});Object.defineProperty(te,"strConcat",{enumerable:!0,get:function(){return tr.strConcat}});Object.defineProperty(te,"nil",{enumerable:!0,get:function(){return tr.nil}});Object.defineProperty(te,"getProperty",{enumerable:!0,get:function(){return tr.getProperty}});Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return tr.stringify}});Object.defineProperty(te,"regexpCode",{enumerable:!0,get:function(){return tr.regexpCode}});Object.defineProperty(te,"Name",{enumerable:!0,get:function(){return tr.Name}});var sc=jp();Object.defineProperty(te,"Scope",{enumerable:!0,get:function(){return sc.Scope}});Object.defineProperty(te,"ValueScope",{enumerable:!0,get:function(){return sc.ValueScope}});Object.defineProperty(te,"ValueScopeName",{enumerable:!0,get:function(){return sc.ValueScopeName}});Object.defineProperty(te,"varKinds",{enumerable:!0,get:function(){return sc.varKinds}});te.operators={GT:new ce._Code(">"),GTE:new ce._Code(">="),LT:new ce._Code("<"),LTE:new ce._Code("<="),EQ:new ce._Code("==="),NEQ:new ce._Code("!=="),NOT:new ce._Code("!"),OR:new ce._Code("||"),AND:new ce._Code("&&"),ADD:new ce._Code("+")};var On=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},zp=class extends On{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?Qt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=Do(this.rhs,e,n)),this}get names(){return this.rhs instanceof ce._CodeOrName?this.rhs.names:{}}},nc=class extends On{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof ce.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Do(this.rhs,e,n),this}get names(){let e=this.lhs instanceof ce.Name?{}:{...this.lhs.names};return oc(e,this.rhs)}},Lp=class extends nc{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Hp=class extends On{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Up=class extends On{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Fp=class extends On{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Zp=class extends On{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=Do(this.code,e,n),this}get names(){return this.code instanceof ce._CodeOrName?this.code.names:{}}},ei=class extends On{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let s=r[o];s.optimizeNames(e,n)||(q$(e,s.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>qr(e,n.names),{})}},In=class extends ei{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Bp=class extends ei{},No=class extends In{};No.kind="else";var Zr=class t extends In{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new No(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(DS(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=Do(this.condition,e,n),this}get names(){let e=super.names;return oc(e,this.condition),this.else&&qr(e,this.else.names),e}};Zr.kind="if";var Br=class extends In{};Br.kind="for";var qp=class extends Br{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=Do(this.iteration,e,n),this}get names(){return qr(super.names,this.iteration.names)}},Vp=class extends Br{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?Qt.varKinds.var:this.varKind,{name:r,from:o,to:s}=this;return`for(${n} ${r}=${o}; ${r}<${s}; ${r}++)`+super.render(e)}get names(){let e=oc(super.names,this.from);return oc(e,this.to)}},rc=class extends Br{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=Do(this.iterable,e,n),this}get names(){return qr(super.names,this.iterable.names)}},ti=class extends In{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ti.kind="func";var ni=class extends ei{render(e){return"return "+super.render(e)}};ni.kind="return";var Wp=class extends In{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&qr(e,this.catch.names),this.finally&&qr(e,this.finally.names),e}},ri=class extends In{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ri.kind="catch";var oi=class extends In{render(e){return"finally"+super.render(e)}};oi.kind="finally";var Kp=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
3
|
+
`:""},this._extScope=e,this._scope=new Qt.Scope({parent:e}),this._nodes=[new Bp]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let s=this._scope.toName(n);return r!==void 0&&o&&(this._constants[s.str]=r),this._leafNode(new zp(e,s,r)),s}const(e,n,r){return this._def(Qt.varKinds.const,e,n,r)}let(e,n,r){return this._def(Qt.varKinds.let,e,n,r)}var(e,n,r){return this._def(Qt.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new nc(e,n,r))}add(e,n){return this._leafNode(new Lp(e,te.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==ce.nil&&this._leafNode(new Zp(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,ce.addCodeArg)(n,o));return n.push("}"),new ce._Code(n)}if(e,n,r){if(this._blockNode(new Zr(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Zr(e))}else(){return this._elseNode(new No)}endIf(){return this._endBlockNode(Zr,No)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new qp(e),n)}forRange(e,n,r,o,s=this.opts.es5?Qt.varKinds.var:Qt.varKinds.let){let i=this._scope.toName(e);return this._for(new Vp(s,i,n,r),()=>o(i))}forOf(e,n,r,o=Qt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=n instanceof ce.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,ce._)`${i}.length`,a=>{this.var(s,(0,ce._)`${i}[${a}]`),r(s)})}return this._for(new rc("of",o,s,n),()=>r(s))}forIn(e,n,r,o=this.opts.es5?Qt.varKinds.var:Qt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ce._)`Object.keys(${n})`,r);let s=this._scope.toName(e);return this._for(new rc("in",o,s,n),()=>r(s))}endFor(){return this._endBlockNode(Br)}label(e){return this._leafNode(new Hp(e))}break(e){return this._leafNode(new Up(e))}return(e){let n=new ni;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ni)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Wp;if(this._blockNode(o),this.code(e),n){let s=this.name("e");this._currNode=o.catch=new ri(s),n(s)}return r&&(this._currNode=o.finally=new oi,this.code(r)),this._endBlockNode(ri,oi)}throw(e){return this._leafNode(new Fp(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=ce.nil,r,o){return this._blockNode(new ti(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ti)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Zr))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};te.CodeGen=Kp;function qr(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function oc(t,e){return e instanceof ce._CodeOrName?qr(t,e.names):t}function Do(t,e,n){if(t instanceof ce.Name)return r(t);if(!o(t))return t;return new ce._Code(t._items.reduce((s,i)=>(i instanceof ce.Name&&(i=r(i)),i instanceof ce._Code?s.push(...i._items):s.push(i),s),[]));function r(s){let i=n[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ce._Code&&s._items.some(i=>i instanceof ce.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function q$(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function DS(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ce._)`!${Gp(t)}`}te.not=DS;var V$=MS(te.operators.AND);function W$(...t){return t.reduce(V$)}te.and=W$;var K$=MS(te.operators.OR);function G$(...t){return t.reduce(K$)}te.or=G$;function MS(t){return(e,n)=>e===ce.nil?n:n===ce.nil?e:(0,ce._)`${Gp(e)} ${t} ${Gp(n)}`}function Gp(t){return t instanceof ce.Name?t:(0,ce._)`(${t})`}});var ue=I(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.checkStrictMode=re.getErrorPath=re.Type=re.useFunc=re.setEvaluated=re.evaluatedPropsToName=re.mergeEvaluated=re.eachItem=re.unescapeJsonPointer=re.escapeJsonPointer=re.escapeFragment=re.unescapeFragment=re.schemaRefOrVal=re.schemaHasRulesButRef=re.schemaHasRules=re.checkUnknownRules=re.alwaysValidSchema=re.toHash=void 0;var _e=ee(),J$=Qs();function X$(t){let e={};for(let n of t)e[n]=!0;return e}re.toHash=X$;function Y$(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(LS(t,e),!HS(e,t.self.RULES.all))}re.alwaysValidSchema=Y$;function LS(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let s in e)o[s]||ZS(t,`unknown keyword: "${s}"`)}re.checkUnknownRules=LS;function HS(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}re.schemaHasRules=HS;function Q$(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}re.schemaHasRulesButRef=Q$;function eO({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,_e._)`${n}`}return(0,_e._)`${t}${e}${(0,_e.getProperty)(r)}`}re.schemaRefOrVal=eO;function tO(t){return US(decodeURIComponent(t))}re.unescapeFragment=tO;function nO(t){return encodeURIComponent(Xp(t))}re.escapeFragment=nO;function Xp(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=Xp;function US(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=US;function rO(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}re.eachItem=rO;function jS({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof _e.Name?(s instanceof _e.Name?t(o,s,i):e(o,s,i),i):s instanceof _e.Name?(e(o,i,s),s):n(s,i);return a===_e.Name&&!(c instanceof _e.Name)?r(o,c):c}}re.mergeEvaluated={props:jS({mergeNames:(t,e,n)=>t.if((0,_e._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,_e._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,_e._)`${n} || {}`).code((0,_e._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,_e._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,_e._)`${n} || {}`),Yp(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:FS}),items:jS({mergeNames:(t,e,n)=>t.if((0,_e._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,_e._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,_e._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,_e._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function FS(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,_e._)`{}`);return e!==void 0&&Yp(t,n,e),n}re.evaluatedPropsToName=FS;function Yp(t,e,n){Object.keys(n).forEach(r=>t.assign((0,_e._)`${e}${(0,_e.getProperty)(r)}`,!0))}re.setEvaluated=Yp;var zS={};function oO(t,e){return t.scopeValue("func",{ref:e,code:zS[e.code]||(zS[e.code]=new J$._Code(e.code))})}re.useFunc=oO;var Jp;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Jp||(re.Type=Jp={}));function sO(t,e,n){if(t instanceof _e.Name){let r=e===Jp.Num;return n?r?(0,_e._)`"[" + ${t} + "]"`:(0,_e._)`"['" + ${t} + "']"`:r?(0,_e._)`"/" + ${t}`:(0,_e._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,_e.getProperty)(t).toString():"/"+Xp(t)}re.getErrorPath=sO;function ZS(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}re.checkStrictMode=ZS});var An=I(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});var rt=ee(),iO={data:new rt.Name("data"),valCxt:new rt.Name("valCxt"),instancePath:new rt.Name("instancePath"),parentData:new rt.Name("parentData"),parentDataProperty:new rt.Name("parentDataProperty"),rootData:new rt.Name("rootData"),dynamicAnchors:new rt.Name("dynamicAnchors"),vErrors:new rt.Name("vErrors"),errors:new rt.Name("errors"),this:new rt.Name("this"),self:new rt.Name("self"),scope:new rt.Name("scope"),json:new rt.Name("json"),jsonPos:new rt.Name("jsonPos"),jsonLen:new rt.Name("jsonLen"),jsonPart:new rt.Name("jsonPart")};Qp.default=iO});var si=I(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.extendErrors=ot.resetErrorsCount=ot.reportExtraError=ot.reportError=ot.keyword$DataError=ot.keywordError=void 0;var le=ee(),ic=ue(),ut=An();ot.keywordError={message:({keyword:t})=>(0,le.str)`must pass "${t}" keyword validation`};ot.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,le.str)`"${t}" keyword must be ${e} ($data)`:(0,le.str)`"${t}" keyword is invalid ($data)`};function aO(t,e=ot.keywordError,n,r){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=VS(t,e,n);r??(i||a)?BS(s,c):qS(o,(0,le._)`[${c}]`)}ot.reportError=aO;function cO(t,e=ot.keywordError,n){let{it:r}=t,{gen:o,compositeRule:s,allErrors:i}=r,a=VS(t,e,n);BS(o,a),s||i||qS(r,ut.default.vErrors)}ot.reportExtraError=cO;function uO(t,e){t.assign(ut.default.errors,e),t.if((0,le._)`${ut.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,le._)`${ut.default.vErrors}.length`,e),()=>t.assign(ut.default.vErrors,null)))}ot.resetErrorsCount=uO;function lO({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,ut.default.errors,a=>{t.const(i,(0,le._)`${ut.default.vErrors}[${a}]`),t.if((0,le._)`${i}.instancePath === undefined`,()=>t.assign((0,le._)`${i}.instancePath`,(0,le.strConcat)(ut.default.instancePath,s.errorPath))),t.assign((0,le._)`${i}.schemaPath`,(0,le.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,le._)`${i}.schema`,n),t.assign((0,le._)`${i}.data`,r))})}ot.extendErrors=lO;function BS(t,e){let n=t.const("err",e);t.if((0,le._)`${ut.default.vErrors} === null`,()=>t.assign(ut.default.vErrors,(0,le._)`[${n}]`),(0,le._)`${ut.default.vErrors}.push(${n})`),t.code((0,le._)`${ut.default.errors}++`)}function qS(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,le._)`new ${t.ValidationError}(${e})`):(n.assign((0,le._)`${r}.errors`,e),n.return(!1))}var Vr={keyword:new le.Name("keyword"),schemaPath:new le.Name("schemaPath"),params:new le.Name("params"),propertyName:new le.Name("propertyName"),message:new le.Name("message"),schema:new le.Name("schema"),parentSchema:new le.Name("parentSchema")};function VS(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,le._)`{}`:dO(t,e,n)}function dO(t,e,n={}){let{gen:r,it:o}=t,s=[pO(o,n),fO(t,n)];return mO(t,e,s),r.object(...s)}function pO({errorPath:t},{instancePath:e}){let n=e?(0,le.str)`${t}${(0,ic.getErrorPath)(e,ic.Type.Str)}`:t;return[ut.default.instancePath,(0,le.strConcat)(ut.default.instancePath,n)]}function fO({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,le.str)`${e}/${t}`;return n&&(o=(0,le.str)`${o}${(0,ic.getErrorPath)(n,ic.Type.Str)}`),[Vr.schemaPath,o]}function mO(t,{params:e,message:n},r){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;r.push([Vr.keyword,o],[Vr.params,typeof e=="function"?e(t):e||(0,le._)`{}`]),c.messages&&r.push([Vr.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Vr.schema,i],[Vr.parentSchema,(0,le._)`${l}${d}`],[ut.default.data,s]),u&&r.push([Vr.propertyName,u])}});var KS=I(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.boolOrEmptySchema=Mo.topBoolOrEmptySchema=void 0;var hO=si(),gO=ee(),yO=An(),_O={message:"boolean schema is false"};function SO(t){let{gen:e,schema:n,validateName:r}=t;n===!1?WS(t,!1):typeof n=="object"&&n.$async===!0?e.return(yO.default.data):(e.assign((0,gO._)`${r}.errors`,null),e.return(!0))}Mo.topBoolOrEmptySchema=SO;function xO(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),WS(t)):n.var(e,!0)}Mo.boolOrEmptySchema=xO;function WS(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,hO.reportError)(o,_O,void 0,e)}});var ef=I(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.getRules=jo.isJSONType=void 0;var kO=["string","number","integer","boolean","null","object","array"],bO=new Set(kO);function vO(t){return typeof t=="string"&&bO.has(t)}jo.isJSONType=vO;function EO(){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:{}}}jo.getRules=EO});var tf=I(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.shouldUseRule=nr.shouldUseGroup=nr.schemaHasRulesForType=void 0;function wO({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&GS(t,r)}nr.schemaHasRulesForType=wO;function GS(t,e){return e.rules.some(n=>JS(t,n))}nr.shouldUseGroup=GS;function JS(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}nr.shouldUseRule=JS});var ii=I(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.reportTypeError=st.checkDataTypes=st.checkDataType=st.coerceAndCheckDataType=st.getJSONTypes=st.getSchemaTypes=st.DataType=void 0;var TO=ef(),PO=tf(),RO=si(),Y=ee(),XS=ue(),zo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(zo||(st.DataType=zo={}));function CO(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}st.getSchemaTypes=CO;function YS(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(TO.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}st.getJSONTypes=YS;function $O(t,e){let{gen:n,data:r,opts:o}=t,s=OO(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,PO.schemaHasRulesForType)(t,e[0]));if(i){let a=rf(e,r,o.strictNumbers,zo.Wrong);n.if(a,()=>{s.length?IO(t,e,s):of(t)})}return i}st.coerceAndCheckDataType=$O;var QS=new Set(["string","number","integer","boolean","null"]);function OO(t,e){return e?t.filter(n=>QS.has(n)||e==="array"&&n==="array"):[]}function IO(t,e,n){let{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,Y._)`typeof ${o}`),a=r.let("coerced",(0,Y._)`undefined`);s.coerceTypes==="array"&&r.if((0,Y._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,Y._)`${o}[0]`).assign(i,(0,Y._)`typeof ${o}`).if(rf(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,Y._)`${a} !== undefined`);for(let u of n)(QS.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),of(t),r.endIf(),r.if((0,Y._)`${a} !== undefined`,()=>{r.assign(o,a),AO(t,a)});function c(u){switch(u){case"string":r.elseIf((0,Y._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Y._)`"" + ${o}`).elseIf((0,Y._)`${o} === null`).assign(a,(0,Y._)`""`);return;case"number":r.elseIf((0,Y._)`${i} == "boolean" || ${o} === null
|
|
4
|
+
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,Y._)`+${o}`);return;case"integer":r.elseIf((0,Y._)`${i} === "boolean" || ${o} === null
|
|
5
|
+
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,Y._)`+${o}`);return;case"boolean":r.elseIf((0,Y._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,Y._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,Y._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,Y._)`${i} === "string" || ${i} === "number"
|
|
6
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,Y._)`[${o}]`)}}}function AO({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,Y._)`${e} !== undefined`,()=>t.assign((0,Y._)`${e}[${n}]`,r))}function nf(t,e,n,r=zo.Correct){let o=r===zo.Correct?Y.operators.EQ:Y.operators.NEQ,s;switch(t){case"null":return(0,Y._)`${e} ${o} null`;case"array":s=(0,Y._)`Array.isArray(${e})`;break;case"object":s=(0,Y._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,Y._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,Y._)`typeof ${e} ${o} ${t}`}return r===zo.Correct?s:(0,Y.not)(s);function i(a=Y.nil){return(0,Y.and)((0,Y._)`typeof ${e} == "number"`,a,n?(0,Y._)`isFinite(${e})`:Y.nil)}}st.checkDataType=nf;function rf(t,e,n,r){if(t.length===1)return nf(t[0],e,n,r);let o,s=(0,XS.toHash)(t);if(s.array&&s.object){let i=(0,Y._)`typeof ${e} != "object"`;o=s.null?i:(0,Y._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=Y.nil;s.number&&delete s.integer;for(let i in s)o=(0,Y.and)(o,nf(i,e,n,r));return o}st.checkDataTypes=rf;var NO={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Y._)`{type: ${t}}`:(0,Y._)`{type: ${e}}`};function of(t){let e=DO(t);(0,RO.reportError)(e,NO)}st.reportTypeError=of;function DO(t){let{gen:e,data:n,schema:r}=t,o=(0,XS.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var tx=I(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.assignDefaults=void 0;var Lo=ee(),MO=ue();function jO(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)ex(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>ex(t,s,o.default))}ac.assignDefaults=jO;function ex(t,e,n){let{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;let a=(0,Lo._)`${s}${(0,Lo.getProperty)(e)}`;if(o){(0,MO.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Lo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Lo._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Lo._)`${a} = ${(0,Lo.stringify)(n)}`)}});var zt=I(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.validateUnion=he.validateArray=he.usePattern=he.callValidateCode=he.schemaProperties=he.allSchemaProperties=he.noPropertyInData=he.propertyInData=he.isOwnProperty=he.hasPropFunc=he.reportMissingProp=he.checkMissingProp=he.checkReportMissingProp=void 0;var ve=ee(),sf=ue(),rr=An(),zO=ue();function LO(t,e){let{gen:n,data:r,it:o}=t;n.if(cf(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ve._)`${e}`},!0),t.error()})}he.checkReportMissingProp=LO;function HO({gen:t,data:e,it:{opts:n}},r,o){return(0,ve.or)(...r.map(s=>(0,ve.and)(cf(t,e,s,n.ownProperties),(0,ve._)`${o} = ${s}`)))}he.checkMissingProp=HO;function UO(t,e){t.setParams({missingProperty:e},!0),t.error()}he.reportMissingProp=UO;function nx(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ve._)`Object.prototype.hasOwnProperty`})}he.hasPropFunc=nx;function af(t,e,n){return(0,ve._)`${nx(t)}.call(${e}, ${n})`}he.isOwnProperty=af;function FO(t,e,n,r){let o=(0,ve._)`${e}${(0,ve.getProperty)(n)} !== undefined`;return r?(0,ve._)`${o} && ${af(t,e,n)}`:o}he.propertyInData=FO;function cf(t,e,n,r){let o=(0,ve._)`${e}${(0,ve.getProperty)(n)} === undefined`;return r?(0,ve.or)(o,(0,ve.not)(af(t,e,n))):o}he.noPropertyInData=cf;function rx(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}he.allSchemaProperties=rx;function ZO(t,e){return rx(e).filter(n=>!(0,sf.alwaysValidSchema)(t,e[n]))}he.schemaProperties=ZO;function BO({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ve._)`${t}, ${e}, ${r}${o}`:e,d=[[rr.default.instancePath,(0,ve.strConcat)(rr.default.instancePath,s)],[rr.default.parentData,i.parentData],[rr.default.parentDataProperty,i.parentDataProperty],[rr.default.rootData,rr.default.rootData]];i.opts.dynamicRef&&d.push([rr.default.dynamicAnchors,rr.default.dynamicAnchors]);let f=(0,ve._)`${l}, ${n.object(...d)}`;return c!==ve.nil?(0,ve._)`${a}.call(${c}, ${f})`:(0,ve._)`${a}(${f})`}he.callValidateCode=BO;var qO=(0,ve._)`new RegExp`;function VO({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ve._)`${o.code==="new RegExp"?qO:(0,zO.useFunc)(t,o)}(${n}, ${r})`})}he.usePattern=VO;function WO(t){let{gen:e,data:n,keyword:r,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ve._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:sf.Type.Num},s),e.if((0,ve.not)(s),a)})}}he.validateArray=WO;function KO(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,sf.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,u)=>{let l=t.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ve._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ve.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}he.validateUnion=KO});var ix=I(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.validateKeywordUsage=mn.validSchemaType=mn.funcKeywordCode=mn.macroKeywordCode=void 0;var lt=ee(),Wr=An(),GO=zt(),JO=si();function XO(t,e){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=sx(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:lt.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}mn.macroKeywordCode=XO;function YO(t,e){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;eI(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=sx(r,o,u),d=r.let("valid");t.block$data(d,f),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function f(){if(e.errors===!1)h(),e.modifying&&ox(t),g(()=>t.error());else{let y=e.async?m():p();e.modifying&&ox(t),g(()=>QO(t,y))}}function m(){let y=r.let("ruleErrs",null);return r.try(()=>h((0,lt._)`await `),_=>r.assign(d,!1).if((0,lt._)`${_} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,lt._)`${_}.errors`),()=>r.throw(_))),y}function p(){let y=(0,lt._)`${l}.errors`;return r.assign(y,null),h(lt.nil),y}function h(y=e.async?(0,lt._)`await `:lt.nil){let _=c.opts.passContext?Wr.default.this:Wr.default.self,S=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,lt._)`${y}${(0,GO.callValidateCode)(t,l,_,S)}`,e.modifying)}function g(y){var _;r.if((0,lt.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}mn.funcKeywordCode=YO;function ox(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,lt._)`${r.parentData}[${r.parentDataProperty}]`))}function QO(t,e){let{gen:n}=t;n.if((0,lt._)`Array.isArray(${e})`,()=>{n.assign(Wr.default.vErrors,(0,lt._)`${Wr.default.vErrors} === null ? ${e} : ${Wr.default.vErrors}.concat(${e})`).assign(Wr.default.errors,(0,lt._)`${Wr.default.vErrors}.length`),(0,JO.extendErrors)(t)},()=>t.error())}function eI({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function sx(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,lt.stringify)(n)})}function tI(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}mn.validSchemaType=tI;function nI({schema:t,opts:e,self:n,errSchemaPath:r},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}mn.validateKeywordUsage=nI});var cx=I(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.extendSubschemaMode=or.extendSubschemaData=or.getSubschema=void 0;var hn=ee(),ax=ue();function rI(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,hn._)`${t.schemaPath}${(0,hn.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,hn._)`${t.schemaPath}${(0,hn.getProperty)(e)}${(0,hn.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,ax.escapeFragment)(n)}`}}if(r!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}or.getSubschema=rI;function oI(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,f=a.let("data",(0,hn._)`${e.data}${(0,hn.getProperty)(n)}`,!0);c(f),t.errorPath=(0,hn.str)`${u}${(0,ax.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,hn._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof hn.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}or.extendSubschemaData=oI;function sI(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}or.extendSubschemaMode=sI});var uf=I((C2,ux)=>{"use strict";ux.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var dx=I(($2,lx)=>{"use strict";var sr=lx.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};cc(e,r,o,t,"",t)};sr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};sr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};sr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};sr.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 cc(t,e,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in sr.arrayKeywords)for(var f=0;f<d.length;f++)cc(t,e,n,d[f],o+"/"+l+"/"+f,s,o,l,r,f)}else if(l in sr.propsKeywords){if(d&&typeof d=="object")for(var m in d)cc(t,e,n,d[m],o+"/"+l+"/"+iI(m),s,o,l,r,m)}else(l in sr.keywords||t.allKeys&&!(l in sr.skipKeywords))&&cc(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function iI(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ai=I(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.getSchemaRefs=xt.resolveUrl=xt.normalizeId=xt._getFullPath=xt.getFullPath=xt.inlineRef=void 0;var aI=ue(),cI=uf(),uI=dx(),lI=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function dI(t,e=!0){return typeof t=="boolean"?!0:e===!0?!lf(t):e?px(t)<=e:!1}xt.inlineRef=dI;var pI=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function lf(t){for(let e in t){if(pI.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(lf)||typeof n=="object"&&lf(n))return!0}return!1}function px(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!lI.has(n)&&(typeof t[n]=="object"&&(0,aI.eachItem)(t[n],r=>e+=px(r)),e===1/0))return 1/0}return e}function fx(t,e="",n){n!==!1&&(e=Ho(e));let r=t.parse(e);return mx(t,r)}xt.getFullPath=fx;function mx(t,e){return t.serialize(e).split("#")[0]+"#"}xt._getFullPath=mx;var fI=/#\/?$/;function Ho(t){return t?t.replace(fI,""):""}xt.normalizeId=Ho;function mI(t,e,n){return n=Ho(n),t.resolve(e,n)}xt.resolveUrl=mI;var hI=/^[a-z_][-a-z0-9._]*$/i;function gI(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Ho(t[n]||e),s={"":o},i=fx(r,o,!1),a={},c=new Set;return uI(t,{allKeys:!0},(d,f,m,p)=>{if(p===void 0)return;let h=i+f,g=s[p];typeof d[n]=="string"&&(g=y.call(this,d[n])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[f]=g;function y(S){let k=this.opts.uriResolver.resolve;if(S=Ho(g?k(g,S):S),c.has(S))throw l(S);c.add(S);let v=this.refs[S];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(d,v.schema,S):S!==Ho(h)&&(S[0]==="#"?(u(d,a[S],S),a[S]=d):this.refs[S]=h),S}function _(S){if(typeof S=="string"){if(!hI.test(S))throw new Error(`invalid anchor "${S}"`);y.call(this,`#${S}`)}}}),a;function u(d,f,m){if(f!==void 0&&!cI(d,f))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}xt.getSchemaRefs=gI});var li=I(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.getData=ir.KeywordCxt=ir.validateFunctionCode=void 0;var Sx=KS(),hx=ii(),pf=tf(),uc=ii(),yI=tx(),ui=ix(),df=cx(),F=ee(),G=An(),_I=ai(),Nn=ue(),ci=si();function SI(t){if(bx(t)&&(vx(t),kx(t))){bI(t);return}xx(t,()=>(0,Sx.topBoolOrEmptySchema)(t))}ir.validateFunctionCode=SI;function xx({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,F._)`${G.default.data}, ${G.default.valCxt}`,r.$async,()=>{t.code((0,F._)`"use strict"; ${gx(n,o)}`),kI(t,o),t.code(s)}):t.func(e,(0,F._)`${G.default.data}, ${xI(o)}`,r.$async,()=>t.code(gx(n,o)).code(s))}function xI(t){return(0,F._)`{${G.default.instancePath}="", ${G.default.parentData}, ${G.default.parentDataProperty}, ${G.default.rootData}=${G.default.data}${t.dynamicRef?(0,F._)`, ${G.default.dynamicAnchors}={}`:F.nil}}={}`}function kI(t,e){t.if(G.default.valCxt,()=>{t.var(G.default.instancePath,(0,F._)`${G.default.valCxt}.${G.default.instancePath}`),t.var(G.default.parentData,(0,F._)`${G.default.valCxt}.${G.default.parentData}`),t.var(G.default.parentDataProperty,(0,F._)`${G.default.valCxt}.${G.default.parentDataProperty}`),t.var(G.default.rootData,(0,F._)`${G.default.valCxt}.${G.default.rootData}`),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,F._)`${G.default.valCxt}.${G.default.dynamicAnchors}`)},()=>{t.var(G.default.instancePath,(0,F._)`""`),t.var(G.default.parentData,(0,F._)`undefined`),t.var(G.default.parentDataProperty,(0,F._)`undefined`),t.var(G.default.rootData,G.default.data),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,F._)`{}`)})}function bI(t){let{schema:e,opts:n,gen:r}=t;xx(t,()=>{n.$comment&&e.$comment&&wx(t),PI(t),r.let(G.default.vErrors,null),r.let(G.default.errors,0),n.unevaluated&&vI(t),Ex(t),$I(t)})}function vI(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,F._)`${n}.evaluated`),e.if((0,F._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,F._)`${t.evaluated}.props`,(0,F._)`undefined`)),e.if((0,F._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,F._)`${t.evaluated}.items`,(0,F._)`undefined`))}function gx(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,F._)`/*# sourceURL=${n} */`:F.nil}function EI(t,e){if(bx(t)&&(vx(t),kx(t))){wI(t,e);return}(0,Sx.boolOrEmptySchema)(t,e)}function kx({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function bx(t){return typeof t.schema!="boolean"}function wI(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&wx(t),RI(t),CI(t);let s=r.const("_errs",G.default.errors);Ex(t,s),r.var(e,(0,F._)`${s} === ${G.default.errors}`)}function vx(t){(0,Nn.checkUnknownRules)(t),TI(t)}function Ex(t,e){if(t.opts.jtd)return yx(t,[],!1,e);let n=(0,hx.getSchemaTypes)(t.schema),r=(0,hx.coerceAndCheckDataType)(t,n);yx(t,n,!r,e)}function TI(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Nn.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function PI(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Nn.checkStrictMode)(t,"default is ignored in the schema root")}function RI(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,_I.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function CI(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function wx({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let s=n.$comment;if(o.$comment===!0)t.code((0,F._)`${G.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,F.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,F._)`${G.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function $I(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$async?e.if((0,F._)`${G.default.errors} === 0`,()=>e.return(G.default.data),()=>e.throw((0,F._)`new ${o}(${G.default.vErrors})`)):(e.assign((0,F._)`${r}.errors`,G.default.vErrors),s.unevaluated&&OI(t),e.return((0,F._)`${G.default.errors} === 0`))}function OI({gen:t,evaluated:e,props:n,items:r}){n instanceof F.Name&&t.assign((0,F._)`${e}.props`,n),r instanceof F.Name&&t.assign((0,F._)`${e}.items`,r)}function yx(t,e,n,r){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Nn.schemaHasRulesButRef)(s,l))){o.block(()=>Px(t,"$ref",l.all.$ref.definition));return}c.jtd||II(t,e),o.block(()=>{for(let f of l.rules)d(f);d(l.post)});function d(f){(0,pf.shouldUseGroup)(s,f)&&(f.type?(o.if((0,uc.checkDataType)(f.type,i,c.strictNumbers)),_x(t,f),e.length===1&&e[0]===f.type&&n&&(o.else(),(0,uc.reportTypeError)(t)),o.endIf()):_x(t,f),a||o.if((0,F._)`${G.default.errors} === ${r||0}`))}}function _x(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,yI.assignDefaults)(t,e.type),n.block(()=>{for(let s of e.rules)(0,pf.shouldUseRule)(r,s)&&Px(t,s.keyword,s.definition,e.type)})}function II(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(AI(t,e),t.opts.allowUnionTypes||NI(t,e),DI(t,t.dataTypes))}function AI(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Tx(t.dataTypes,n)||ff(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),jI(t,e)}}function NI(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ff(t,"use allowUnionTypes to allow union type keyword")}function DI(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,pf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>MI(e,i))&&ff(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function MI(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Tx(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function jI(t,e){let n=[];for(let r of t.dataTypes)Tx(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function ff(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Nn.checkStrictMode)(t,e,t.opts.strictTypes)}var lc=class{constructor(e,n,r){if((0,ui.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Nn.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",Rx(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ui.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",G.default.errors))}result(e,n,r){this.failResult((0,F.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,F.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,F._)`${n} !== undefined && (${(0,F.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?ci.reportExtraError:ci.reportError)(this,this.def.error,n)}$dataError(){(0,ci.reportError)(this,this.def.$dataError||ci.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ci.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=F.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=F.nil,n=F.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,F.or)((0,F._)`${o} === undefined`,n)),e!==F.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==F.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,F.or)(i(),a());function i(){if(r.length){if(!(n instanceof F.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,F._)`${(0,uc.checkDataTypes)(c,n,s.opts.strictNumbers,uc.DataType.Wrong)}`}return F.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,F._)`!${c}(${n})`}return F.nil}}subschema(e,n){let r=(0,df.getSubschema)(this.it,e);(0,df.extendSubschemaData)(r,this.it,e),(0,df.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return EI(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Nn.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Nn.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,F.Name)),!0}};ir.KeywordCxt=lc;function Px(t,e,n,r){let o=new lc(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,ui.funcKeywordCode)(o,n):"macro"in n?(0,ui.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,ui.funcKeywordCode)(o,n)}var zI=/^\/(?:[^~]|~0|~1)*$/,LI=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Rx(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return G.default.rootData;if(t[0]==="/"){if(!zI.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=G.default.rootData}else{let u=LI.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,F._)`${s}${(0,F.getProperty)((0,Nn.unescapeJsonPointer)(u))}`,i=(0,F._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}ir.getData=Rx});var dc=I(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var mf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};hf.default=mf});var di=I(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var gf=ai(),yf=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,gf.resolveUrl)(e,n,r),this.missingSchema=(0,gf.normalizeId)((0,gf.getFullPath)(e,this.missingRef))}};_f.default=yf});var fc=I(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.resolveSchema=Lt.getCompilingSchema=Lt.resolveRef=Lt.compileSchema=Lt.SchemaEnv=void 0;var en=ee(),HI=dc(),Kr=An(),tn=ai(),Cx=ue(),UI=li(),Uo=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,tn.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};Lt.SchemaEnv=Uo;function xf(t){let e=$x.call(this,t);if(e)return e;let n=(0,tn.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new en.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:HI.default,code:(0,en._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Kr.default.data,parentData:Kr.default.parentData,parentDataProperty:Kr.default.parentDataProperty,dataNames:[Kr.default.data],dataPathArr:[en.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,en.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:en.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,en._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,UI.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Kr.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${Kr.default.self}`,`${Kr.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:h}=u;m.evaluated={props:p instanceof en.Name?void 0:p,items:h instanceof en.Name?void 0:h,dynamicProps:p instanceof en.Name,dynamicItems:h instanceof en.Name},m.source&&(m.source.evaluated=(0,en.stringify)(m.evaluated))}return t.validate=m,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}Lt.compileSchema=xf;function FI(t,e,n){var r;n=(0,tn.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let s=qI.call(this,t,n);if(s===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Uo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=ZI.call(this,s)}Lt.resolveRef=FI;function ZI(t){return(0,tn.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:xf.call(this,t)}function $x(t){for(let e of this._compilations)if(BI(e,t))return e}Lt.getCompilingSchema=$x;function BI(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function qI(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||pc.call(this,t,e)}function pc(t,e){let n=this.opts.uriResolver.parse(e),r=(0,tn._getFullPath)(this.opts.uriResolver,n),o=(0,tn.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return Sf.call(this,n,t);let s=(0,tn.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=pc.call(this,t,i);return typeof a?.schema!="object"?void 0:Sf.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||xf.call(this,i),s===(0,tn.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,tn.resolveUrl)(this.opts.uriResolver,o,u)),new Uo({schema:a,schemaId:c,root:t,baseId:o})}return Sf.call(this,n,i)}}Lt.resolveSchema=pc;var VI=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Sf(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let c=n[(0,Cx.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!VI.has(a)&&u&&(e=(0,tn.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,Cx.schemaHasRulesButRef)(n,this.RULES)){let a=(0,tn.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=pc.call(this,r,a)}let{schemaId:i}=this.opts;if(s=s||new Uo({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}});var Ox=I((M2,WI)=>{WI.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 bf=I((j2,Dx)=>{"use strict";var KI=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ax=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 kf(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var GI=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ix(t){return t.length=0,!0}function JI(t,e,n){if(t.length){let r=kf(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function XI(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],s=!1,i=!1,a=JI;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=Ix}else{o.push(u);continue}}return o.length&&(a===Ix?n.zone=o.join(""):i?r.push(o.join("")):r.push(kf(o))),n.address=r.join(""),n}function Nx(t){if(YI(t,":")<2)return{host:t,isIPV6:!1};let e=XI(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function YI(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function QI(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}function eA(t,e){let n=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=n(t.scheme)),t.userinfo!==void 0&&(t.userinfo=n(t.userinfo)),t.host!==void 0&&(t.host=n(t.host)),t.path!==void 0&&(t.path=n(t.path)),t.query!==void 0&&(t.query=n(t.query)),t.fragment!==void 0&&(t.fragment=n(t.fragment)),t}function tA(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Ax(n)){let r=Nx(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=t.host}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Dx.exports={nonSimpleDomain:GI,recomposeAuthority:tA,normalizeComponentEncoding:eA,removeDotSegments:QI,isIPv4:Ax,isUUID:KI,normalizeIPv6:Nx,stringArrayToHexStripped:kf}});var Hx=I((z2,Lx)=>{"use strict";var{isUUID:nA}=bf(),rA=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,oA=["http","https","ws","wss","urn","urn:uuid"];function sA(t){return oA.indexOf(t)!==-1}function vf(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 Mx(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function jx(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 iA(t){return t.secure=vf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function aA(t){if((t.port===(vf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function cA(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(rA);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,s=Ef(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function uA(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=Ef(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function lA(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!nA(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function dA(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var zx={scheme:"http",domainHost:!0,parse:Mx,serialize:jx},pA={scheme:"https",domainHost:zx.domainHost,parse:Mx,serialize:jx},mc={scheme:"ws",domainHost:!0,parse:iA,serialize:aA},fA={scheme:"wss",domainHost:mc.domainHost,parse:mc.parse,serialize:mc.serialize},mA={scheme:"urn",parse:cA,serialize:uA,skipNormalize:!0},hA={scheme:"urn:uuid",parse:lA,serialize:dA,skipNormalize:!0},hc={http:zx,https:pA,ws:mc,wss:fA,urn:mA,"urn:uuid":hA};Object.setPrototypeOf(hc,null);function Ef(t){return t&&(hc[t]||hc[t.toLowerCase()])||void 0}Lx.exports={wsIsSecure:vf,SCHEMES:hc,isValidSchemeName:sA,getSchemeHandler:Ef}});var Zx=I((L2,yc)=>{"use strict";var{normalizeIPv6:gA,removeDotSegments:pi,recomposeAuthority:yA,normalizeComponentEncoding:gc,isIPv4:_A,nonSimpleDomain:SA}=bf(),{SCHEMES:xA,getSchemeHandler:Ux}=Hx();function kA(t,e){return typeof t=="string"?t=gn(Dn(t,e),e):typeof t=="object"&&(t=Dn(gn(t,e),e)),t}function bA(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Fx(Dn(t,r),Dn(e,r),r,!0);return r.skipEscape=!0,gn(o,r)}function Fx(t,e,n,r){let o={};return r||(t=Dn(gn(t,n),n),e=Dn(gn(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=pi(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=pi(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=pi(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=pi(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function vA(t,e,n){return typeof t=="string"?(t=unescape(t),t=gn(gc(Dn(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=gn(gc(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=gn(gc(Dn(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=gn(gc(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function gn(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],s=Ux(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let i=yA(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=pi(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var EA=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Dn(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let s=t.match(EA);if(s){if(r.scheme=s[1],r.userinfo=s[3],r.host=s[4],r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=s[7],r.fragment=s[8],isNaN(r.port)&&(r.port=s[5]),r.host)if(_A(r.host)===!1){let c=gA(r.host);r.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let i=Ux(n.scheme||r.scheme);if(!n.unicodeSupport&&(!i||!i.unicodeSupport)&&r.host&&(n.domainHost||i&&i.domainHost)&&o===!1&&SA(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(a){r.error=r.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),i&&i.parse&&i.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}var wf={SCHEMES:xA,normalize:kA,resolve:bA,resolveComponent:Fx,equal:vA,serialize:gn,parse:Dn};yc.exports=wf;yc.exports.default=wf;yc.exports.fastUri=wf});var qx=I(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var Bx=Zx();Bx.code='require("ajv/dist/runtime/uri").default';Tf.default=Bx});var Qx=I(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.CodeGen=Je.Name=Je.nil=Je.stringify=Je.str=Je._=Je.KeywordCxt=void 0;var wA=li();Object.defineProperty(Je,"KeywordCxt",{enumerable:!0,get:function(){return wA.KeywordCxt}});var Fo=ee();Object.defineProperty(Je,"_",{enumerable:!0,get:function(){return Fo._}});Object.defineProperty(Je,"str",{enumerable:!0,get:function(){return Fo.str}});Object.defineProperty(Je,"stringify",{enumerable:!0,get:function(){return Fo.stringify}});Object.defineProperty(Je,"nil",{enumerable:!0,get:function(){return Fo.nil}});Object.defineProperty(Je,"Name",{enumerable:!0,get:function(){return Fo.Name}});Object.defineProperty(Je,"CodeGen",{enumerable:!0,get:function(){return Fo.CodeGen}});var TA=dc(),Jx=di(),PA=ef(),fi=fc(),RA=ee(),mi=ai(),_c=ii(),Rf=ue(),Vx=Ox(),CA=qx(),Xx=(t,e)=>new RegExp(t,e);Xx.code="new RegExp";var $A=["removeAdditional","useDefaults","coerceTypes"],OA=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),IA={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."},AA={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Wx=200;function NA(t){var e,n,r,o,s,i,a,c,u,l,d,f,m,p,h,g,y,_,S,k,v,O,R,M,D;let V=t.strict,P=(e=t.code)===null||e===void 0?void 0:e.optimize,T=P===!0||P===void 0?1:P||0,H=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:Xx,pe=(o=t.uriResolver)!==null&&o!==void 0?o:CA.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:V)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:V)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:V)!==null&&l!==void 0?l:"log",strictTuples:(f=(d=t.strictTuples)!==null&&d!==void 0?d:V)!==null&&f!==void 0?f:"log",strictRequired:(p=(m=t.strictRequired)!==null&&m!==void 0?m:V)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:T,regExp:H}:{optimize:T,regExp:H},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Wx,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:Wx,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(S=t.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(v=t.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(O=t.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(R=t.validateFormats)!==null&&R!==void 0?R:!0,unicodeRegExp:(M=t.unicodeRegExp)!==null&&M!==void 0?M:!0,int32range:(D=t.int32range)!==null&&D!==void 0?D:!0,uriResolver:pe}}var hi=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...NA(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new RA.ValueScope({scope:{},prefixes:OA,es5:n,lines:r}),this.logger=HA(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,PA.getRules)(),Kx.call(this,IA,e,"NOT SUPPORTED"),Kx.call(this,AA,e,"DEPRECATED","warn"),this._metaOpts=zA.call(this),e.formats&&MA.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&jA.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),DA.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=Vx;r==="id"&&(o={...Vx},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);async function o(l,d){await s.call(this,l.$schema);let f=this._addSchema(l,d);return f.validate||i.call(this,f)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof Jx.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,n)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=r(l))}finally{delete this._loading[l]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return n=(0,mi.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let n;for(;typeof(n=Gx.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new fi.SchemaEnv({schema:{},schemaId:r});if(n=fi.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=Gx.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,mi.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(FA.call(this,r,n),!n)return(0,Rf.eachItem)(r,s=>Pf.call(this,s)),this;BA.call(this,n);let o={...n,type:(0,_c.getJSONTypes)(n.type),schemaType:(0,_c.getJSONTypes)(n.schemaType)};return(0,Rf.eachItem)(r,o.type.length===0?s=>Pf.call(this,s,o):s=>o.type.forEach(i=>Pf.call(this,s,o,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(s=>s.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,s)=>o+n+s)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=Yx(l))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;r=(0,mi.normalizeId)(i||r);let u=mi.getSchemaRefs.call(this,e,r);return c=new fi.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),this._cache.set(c.schema,c),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):fi.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{fi.compileSchema.call(this,e)}finally{this.opts=n}}};hi.ValidationError=TA.default;hi.MissingRefError=Jx.default;Je.default=hi;function Kx(t,e,n,r="error"){for(let o in t){let s=o;s in e&&this.logger[r](`${n}: option ${o}. ${t[s]}`)}}function Gx(t){return t=(0,mi.normalizeId)(t),this.schemas[t]||this.refs[t]}function DA(){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 MA(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function jA(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function zA(){let t={...this.opts};for(let e of $A)delete t[e];return t}var LA={log(){},warn(){},error(){}};function HA(t){if(t===!1)return LA;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 UA=/^[a-z_$][a-z0-9_$:-]*$/i;function FA(t,e){let{RULES:n}=this;if((0,Rf.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!UA.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Pf(t,e,n){var r;let o=e?.post;if(n&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===n);if(i||(i={type:n,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,_c.getJSONTypes)(e.type),schemaType:(0,_c.getJSONTypes)(e.schemaType)}};e.before?ZA.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function ZA(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function BA(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Yx(e)),t.validateSchema=this.compile(e,!0))}var qA={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Yx(t){return{anyOf:[t,qA]}}});var ek=I(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var VA={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Cf.default=VA});var ok=I(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.callRef=Gr.getValidate=void 0;var WA=di(),tk=zt(),kt=ee(),Zo=An(),nk=fc(),Sc=ue(),KA={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();let l=nk.resolveRef.call(c,u,o,n);if(l===void 0)throw new WA.default(r.opts.uriResolver,o,n);if(l instanceof nk.SchemaEnv)return f(l);return m(l);function d(){if(s===u)return xc(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return xc(t,(0,kt._)`${p}.validate`,u,u.$async)}function f(p){let h=rk(t,p);xc(t,h,p,p.$async)}function m(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,kt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:kt.nil,topSchemaRef:h,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function rk(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,kt._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Gr.getValidate=rk;function xc(t,e,n,r){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Zo.default.this:kt.nil;r?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=o.let("valid");o.try(()=>{o.code((0,kt._)`await ${(0,tk.callValidateCode)(t,e,u)}`),m(e),i||o.assign(p,!0)},h=>{o.if((0,kt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),f(h),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,tk.callValidateCode)(t,e,u),()=>m(e),()=>f(e))}function f(p){let h=(0,kt._)`${p}.errors`;o.assign(Zo.default.vErrors,(0,kt._)`${Zo.default.vErrors} === null ? ${h} : ${Zo.default.vErrors}.concat(${h})`),o.assign(Zo.default.errors,(0,kt._)`${Zo.default.vErrors}.length`)}function m(p){var h;if(!s.opts.unevaluated)return;let g=(h=n?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Sc.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,kt._)`${p}.evaluated.props`);s.props=Sc.mergeEvaluated.props(o,y,s.props,kt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Sc.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,kt._)`${p}.evaluated.items`);s.items=Sc.mergeEvaluated.items(o,y,s.items,kt.Name)}}}Gr.callRef=xc;Gr.default=KA});var sk=I($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var GA=ek(),JA=ok(),XA=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",GA.default,JA.default];$f.default=XA});var ik=I(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var kc=ee(),ar=kc.operators,bc={maximum:{okStr:"<=",ok:ar.LTE,fail:ar.GT},minimum:{okStr:">=",ok:ar.GTE,fail:ar.LT},exclusiveMaximum:{okStr:"<",ok:ar.LT,fail:ar.GTE},exclusiveMinimum:{okStr:">",ok:ar.GT,fail:ar.LTE}},YA={message:({keyword:t,schemaCode:e})=>(0,kc.str)`must be ${bc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,kc._)`{comparison: ${bc[t].okStr}, limit: ${e}}`},QA={keyword:Object.keys(bc),type:"number",schemaType:"number",$data:!0,error:YA,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,kc._)`${n} ${bc[e].fail} ${r} || isNaN(${n})`)}};Of.default=QA});var ak=I(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var gi=ee(),eN={message:({schemaCode:t})=>(0,gi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,gi._)`{multipleOf: ${t}}`},tN={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:eN,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,gi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,gi._)`${i} !== parseInt(${i})`;t.fail$data((0,gi._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};If.default=tN});var uk=I(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});function ck(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}Af.default=ck;ck.code='require("ajv/dist/runtime/ucs2length").default'});var lk=I(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var Jr=ee(),nN=ue(),rN=uk(),oN={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Jr.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Jr._)`{limit: ${t}}`},sN={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:oN,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?Jr.operators.GT:Jr.operators.LT,i=o.opts.unicode===!1?(0,Jr._)`${n}.length`:(0,Jr._)`${(0,nN.useFunc)(t.gen,rN.default)}(${n})`;t.fail$data((0,Jr._)`${i} ${s} ${r}`)}};Nf.default=sN});var dk=I(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var iN=zt(),aN=ue(),Bo=ee(),cN={message:({schemaCode:t})=>(0,Bo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Bo._)`{pattern: ${t}}`},uN={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:cN,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Bo._)`new RegExp`:(0,aN.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Bo._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,Bo._)`!${l}`)}else{let c=(0,iN.usePattern)(t,o);t.fail$data((0,Bo._)`!${c}.test(${n})`)}}};Df.default=uN});var pk=I(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var yi=ee(),lN={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,yi.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,yi._)`{limit: ${t}}`},dN={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:lN,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?yi.operators.GT:yi.operators.LT;t.fail$data((0,yi._)`Object.keys(${n}).length ${o} ${r}`)}};Mf.default=dN});var fk=I(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var _i=zt(),Si=ee(),pN=ue(),fN={message:({params:{missingProperty:t}})=>(0,Si.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Si._)`{missingProperty: ${t}}`},mN={keyword:"required",type:"object",schemaType:"array",$data:!0,error:fN,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;let c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:p}=t.it;for(let h of n)if(m?.[h]===void 0&&!p.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,pN.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Si.nil,d);else for(let m of n)(0,_i.checkReportMissingProp)(t,m)}function l(){let m=e.let("missing");if(c||s){let p=e.let("valid",!0);t.block$data(p,()=>f(m,p)),t.ok(p)}else e.if((0,_i.checkMissingProp)(t,n,m)),(0,_i.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",r,m=>{t.setParams({missingProperty:m}),e.if((0,_i.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function f(m,p){t.setParams({missingProperty:m}),e.forOf(m,r,()=>{e.assign(p,(0,_i.propertyInData)(e,o,m,a.ownProperties)),e.if((0,Si.not)(p),()=>{t.error(),e.break()})},Si.nil)}}};jf.default=mN});var mk=I(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var xi=ee(),hN={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,xi.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,xi._)`{limit: ${t}}`},gN={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:hN,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?xi.operators.GT:xi.operators.LT;t.fail$data((0,xi._)`${n}.length ${o} ${r}`)}};zf.default=gN});var vc=I(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var hk=uf();hk.code='require("ajv/dist/runtime/equal").default';Lf.default=hk});var gk=I(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var Hf=ii(),Xe=ee(),yN=ue(),_N=vc(),SN={message:({params:{i:t,j:e}})=>(0,Xe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Xe._)`{i: ${t}, j: ${e}}`},xN={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:SN,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),u=s.items?(0,Hf.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Xe._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,Xe._)`${n}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,Xe._)`${p} > 1`,()=>(d()?f:m)(p,h))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,h){let g=e.name("item"),y=(0,Hf.checkDataTypes)(u,g,a.opts.strictNumbers,Hf.DataType.Wrong),_=e.const("indices",(0,Xe._)`{}`);e.for((0,Xe._)`;${p}--;`,()=>{e.let(g,(0,Xe._)`${n}[${p}]`),e.if(y,(0,Xe._)`continue`),u.length>1&&e.if((0,Xe._)`typeof ${g} == "string"`,(0,Xe._)`${g} += "_"`),e.if((0,Xe._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,Xe._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,Xe._)`${_}[${g}] = ${p}`)})}function m(p,h){let g=(0,yN.useFunc)(e,_N.default),y=e.name("outer");e.label(y).for((0,Xe._)`;${p}--;`,()=>e.for((0,Xe._)`${h} = ${p}; ${h}--;`,()=>e.if((0,Xe._)`${g}(${n}[${p}], ${n}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Uf.default=xN});var yk=I(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var Ff=ee(),kN=ue(),bN=vc(),vN={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ff._)`{allowedValue: ${t}}`},EN={keyword:"const",$data:!0,error:vN,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,Ff._)`!${(0,kN.useFunc)(e,bN.default)}(${n}, ${o})`):t.fail((0,Ff._)`${s} !== ${n}`)}};Zf.default=EN});var _k=I(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var ki=ee(),wN=ue(),TN=vc(),PN={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ki._)`{allowedValues: ${t}}`},RN={keyword:"enum",schemaType:"array",$data:!0,error:PN,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,wN.useFunc)(e,TN.default)),l;if(a||r)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);l=(0,ki.or)(...o.map((p,h)=>f(m,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,m=>e.if((0,ki._)`${u()}(${n}, ${m})`,()=>e.assign(l,!0).break()))}function f(m,p){let h=o[p];return typeof h=="object"&&h!==null?(0,ki._)`${u()}(${n}, ${m}[${p}])`:(0,ki._)`${n} === ${h}`}}};Bf.default=RN});var Sk=I(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var CN=ik(),$N=ak(),ON=lk(),IN=dk(),AN=pk(),NN=fk(),DN=mk(),MN=gk(),jN=yk(),zN=_k(),LN=[CN.default,$N.default,ON.default,IN.default,AN.default,NN.default,DN.default,MN.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},jN.default,zN.default];qf.default=LN});var Wf=I(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.validateAdditionalItems=void 0;var Xr=ee(),Vf=ue(),HN={message:({params:{len:t}})=>(0,Xr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Xr._)`{limit: ${t}}`},UN={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:HN,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Vf.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}xk(t,r)}};function xk(t,e){let{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;let a=n.const("len",(0,Xr._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Xr._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Vf.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,Xr._)`${a} <= ${e.length}`);n.if((0,Xr.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Vf.Type.Num},u),i.allErrors||n.if((0,Xr.not)(u),()=>n.break())})}}bi.validateAdditionalItems=xk;bi.default=UN});var Kf=I(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.validateTuple=void 0;var kk=ee(),Ec=ue(),FN=zt(),ZN={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return bk(t,"additionalItems",e);n.items=!0,!(0,Ec.alwaysValidSchema)(n,e)&&t.ok((0,FN.validateArray)(t))}};function bk(t,e,n=t.schema){let{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Ec.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,kk._)`${s}.length`);n.forEach((d,f)=>{(0,Ec.alwaysValidSchema)(a,d)||(r.if((0,kk._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){let{opts:f,errSchemaPath:m}=a,p=n.length,h=p===d.minItems&&(p===d.maxItems||d[e]===!1);if(f.strictTuples&&!h){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,Ec.checkStrictMode)(a,g,f.strictTuples)}}}vi.validateTuple=bk;vi.default=ZN});var vk=I(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var BN=Kf(),qN={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,BN.validateTuple)(t,"items")};Gf.default=qN});var wk=I(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var Ek=ee(),VN=ue(),WN=zt(),KN=Wf(),GN={message:({params:{len:t}})=>(0,Ek.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ek._)`{limit: ${t}}`},JN={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:GN,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,VN.alwaysValidSchema)(r,e)&&(o?(0,KN.validateAdditionalItems)(t,o):t.ok((0,WN.validateArray)(t)))}};Jf.default=JN});var Tk=I(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var Ht=ee(),wc=ue(),XN={message:({params:{min:t,max:e}})=>e===void 0?(0,Ht.str)`must contain at least ${t} valid item(s)`:(0,Ht.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ht._)`{minContains: ${t}}`:(0,Ht._)`{minContains: ${t}, maxContains: ${e}}`},YN={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:XN,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,Ht._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,wc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,wc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,wc.alwaysValidSchema)(s,n)){let h=(0,Ht._)`${l} >= ${i}`;a!==void 0&&(h=(0,Ht._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?m(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,Ht._)`${o}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){let h=e.name("_valid"),g=e.let("count",0);m(h,()=>e.if(h,()=>p(g)))}function m(h,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:wc.Type.Num,compositeRule:!0},h),g()})}function p(h){e.code((0,Ht._)`${h}++`),a===void 0?e.if((0,Ht._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Ht._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Ht._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};Xf.default=YN});var Ck=I(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.validateSchemaDeps=yn.validatePropertyDeps=yn.error=void 0;var Yf=ee(),QN=ue(),Ei=zt();yn.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,Yf.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,Yf._)`{property: ${t},
|
|
7
|
+
missingProperty: ${r},
|
|
8
8
|
depsCount: ${e},
|
|
9
|
-
deps: ${r}}`};var aN={keyword:"dependencies",type:"object",schemaType:"object",error:gr.error,code(t){let[e,r]=cN(t);rv(t,e),nv(t,r)}};function cN({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function rv(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Si.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Si.checkReportMissingProp)(t,u)}):(r.if((0,Mf._)`${c} && (${(0,Si.checkMissingProp)(t,a,s)})`),(0,Si.reportMissingProp)(t,s),r.else())}}gr.validatePropertyDeps=rv;function nv(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,iN.alwaysValidSchema)(s,e[a])||(r.if((0,Si.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}gr.validateSchemaDeps=nv;gr.default=aN});var iv=N(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var sv=Q(),uN=ue(),lN={message:"property name must be valid",params:({params:t})=>(0,sv._)`{propertyName: ${t.propertyName}}`},dN={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:lN,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,uN.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,sv.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};jf.default=dN});var Lf=N(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var Sc=Mt(),tr=Q(),pN=Or(),vc=ue(),fN={message:"must NOT have additional properties",params:({params:t})=>(0,tr._)`{additionalProperty: ${t.additionalProperty}}`},mN={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:fN,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,vc.alwaysValidSchema)(i,r))return;let u=(0,Sc.allSchemaProperties)(n.properties),l=(0,Sc.allSchemaProperties)(n.patternProperties);d(),t.ok((0,tr._)`${s} === ${pN.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?p(g):e.if(f(g),()=>p(g))})}function f(g){let y;if(u.length>8){let _=(0,vc.schemaRefOrVal)(i,n.properties,"properties");y=(0,Sc.isOwnProperty)(e,_,g)}else u.length?y=(0,tr.or)(...u.map(_=>(0,tr._)`${g} === ${_}`)):y=tr.nil;return l.length&&(y=(0,tr.or)(y,...l.map(_=>(0,tr._)`${(0,Sc.usePattern)(t,_)}.test(${g})`))),(0,tr.not)(y)}function h(g){e.code((0,tr._)`delete ${o}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,vc.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,tr.not)(y),()=>{t.reset(),h(g)})):(m(g,y),a||e.if((0,tr.not)(y),()=>e.break()))}}function m(g,y,_){let x={keyword:"additionalProperties",dataProp:g,dataPropType:vc.Type.Str};_===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,y)}}};zf.default=mN});var uv=N(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var hN=ii(),av=Mt(),Hf=ue(),cv=Lf(),gN={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&cv.default.code(new hN.KeywordCxt(s,cv.default,"additionalProperties"));let i=(0,av.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Hf.mergeEvaluated.props(e,(0,Hf.toHash)(i),s.props));let a=i.filter(d=>!(0,Hf.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,av.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Uf.default=gN});var fv=N(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var lv=Mt(),bc=Q(),dv=ue(),pv=ue(),yN={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,lv.allSchemaProperties)(r),c=a.filter(m=>(0,dv.alwaysValidSchema)(s,r[m]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof bc.Name)&&(s.props=(0,pv.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let m of a)u&&h(m),s.allErrors?p(m):(e.var(l,!0),p(m),e.if(l))}function h(m){for(let g in u)new RegExp(m).test(g)&&(0,dv.checkStrictMode)(s,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,g=>{e.if((0,bc._)`${(0,lv.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:pv.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,bc._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,bc.not)(l),()=>e.break())})})}}};Ff.default=yN});var mv=N(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var _N=ue(),xN={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,_N.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Zf.default=xN});var hv=N(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var SN=Mt(),vN={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:SN.validateUnion,error:{message:"must match a schema in anyOf"}};qf.default=vN});var gv=N(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var kc=Q(),bN=ue(),kN={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,kc._)`{passingSchemas: ${t.passing}}`},EN={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:kN,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let f;(0,bN.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,kc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,kc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,kc.Name)})})}}};Bf.default=EN});var yv=N(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var wN=ue(),TN={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,wN.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Vf.default=TN});var Sv=N(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var Ec=Q(),xv=ue(),PN={message:({params:t})=>(0,Ec.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ec._)`{failingKeyword: ${t.ifClause}}`},RN={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:PN,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,xv.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=_v(n,"then"),s=_v(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Ec.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let f=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(f,i),d?e.assign(d,(0,Ec._)`${l}`):t.setParams({ifClause:l})}}}};function _v(t,e){let r=t.schema[e];return r!==void 0&&!(0,xv.alwaysValidSchema)(t,r)}Wf.default=RN});var vv=N(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var $N=ue(),CN={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,$N.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Kf.default=CN});var bv=N(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var ON=Of(),IN=YS(),AN=If(),NN=ev(),DN=tv(),MN=ov(),jN=iv(),zN=Lf(),LN=uv(),HN=fv(),UN=mv(),FN=hv(),ZN=gv(),qN=yv(),BN=Sv(),VN=vv();function WN(t=!1){let e=[UN.default,FN.default,ZN.default,qN.default,BN.default,VN.default,jN.default,zN.default,MN.default,LN.default,HN.default];return t?e.push(IN.default,NN.default):e.push(ON.default,AN.default),e.push(DN.default),e}Gf.default=WN});var kv=N(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var ze=Q(),KN={message:({schemaCode:t})=>(0,ze.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ze._)`{format: ${t}}`},GN={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:KN,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?f():h();function f(){let p=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=r.const("fDef",(0,ze._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,ze._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(g,(0,ze._)`${m}.type || "string"`).assign(y,(0,ze._)`${m}.validate`),()=>r.assign(g,(0,ze._)`"string"`).assign(y,m)),t.fail$data((0,ze.or)(_(),x()));function _(){return c.strictSchema===!1?ze.nil:(0,ze._)`${i} && !${y}`}function x(){let S=l.$async?(0,ze._)`(${m}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,ze._)`${y}(${n})`,k=(0,ze._)`(typeof ${y} == "function" ? ${S} : ${y}.test(${n}))`;return(0,ze._)`${y} && ${y} !== true && ${g} === ${e} && !${k}`}}function h(){let p=d.formats[s];if(!p){_();return}if(p===!0)return;let[m,g,y]=x(p);m===e&&t.pass(S());function _(){if(c.strictSchema===!1){d.logger.warn(k());return}throw new Error(k());function k(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function x(k){let R=k instanceof RegExp?(0,ze.regexpCode)(k):c.code.formats?(0,ze._)`${c.code.formats}${(0,ze.getProperty)(s)}`:void 0,$=r.scopeValue("formats",{key:s,ref:k,code:R});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,ze._)`${$}.validate`]:["string",k,$]}function S(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ze._)`await ${y}(${n})`}return typeof g=="function"?(0,ze._)`${y}(${n})`:(0,ze._)`${y}.test(${n})`}}}};Jf.default=GN});var Ev=N(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var JN=kv(),XN=[JN.default];Xf.default=XN});var wv=N(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.contentVocabulary=qo.metadataVocabulary=void 0;qo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];qo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Pv=N(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var YN=NS(),QN=KS(),eD=bv(),tD=Ev(),Tv=wv(),rD=[YN.default,QN.default,(0,eD.default)(),tD.default,Tv.metadataVocabulary,Tv.contentVocabulary];Yf.default=rD});var $v=N(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.DiscrError=void 0;var Rv;(function(t){t.Tag="tag",t.Mapping="mapping"})(Rv||(wc.DiscrError=Rv={}))});var Ov=N(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});var Bo=Q(),Qf=$v(),Cv=ac(),nD=ai(),oD=ue(),sD={message:({params:{discrError:t,tagName:e}})=>t===Qf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Bo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},iD={keyword:"discriminator",type:"object",schemaType:"object",error:sD,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Bo._)`${r}${(0,Bo.getProperty)(a)}`);e.if((0,Bo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Qf.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let h=f();e.if(!1);for(let p in h)e.elseIf((0,Bo._)`${u} === ${p}`),e.assign(c,d(h[p]));e.else(),t.error(!1,{discrError:Qf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(h){let p=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:h},p);return t.mergeEvaluated(m,Bo.Name),p}function f(){var h;let p={},m=y(o),g=!0;for(let S=0;S<i.length;S++){let k=i[S];if(k?.$ref&&!(0,oD.schemaHasRulesButRef)(k,s.self.RULES)){let $=k.$ref;if(k=Cv.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,$),k instanceof Cv.SchemaEnv&&(k=k.schema),k===void 0)throw new nD.default(s.opts.uriResolver,s.baseId,$)}let R=(h=k?.properties)===null||h===void 0?void 0:h[a];if(typeof R!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y(k)),_(R,S)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:S}){return Array.isArray(S)&&S.includes(a)}function _(S,k){if(S.const)x(S.const,k);else if(S.enum)for(let R of S.enum)x(R,k);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(S,k){if(typeof S!="string"||S in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[S]=k}}}};em.default=iD});var Iv=N((r2,aD)=>{aD.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 rm=N((Te,tm)=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.MissingRefError=Te.ValidationError=Te.CodeGen=Te.Name=Te.nil=Te.stringify=Te.str=Te._=Te.KeywordCxt=Te.Ajv=void 0;var cD=RS(),uD=Pv(),lD=Ov(),Av=Iv(),dD=["/properties"],Tc="http://json-schema.org/draft-07/schema",Vo=class extends cD.default{_addVocabularies(){super._addVocabularies(),uD.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(lD.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Av,dD):Av;this.addMetaSchema(e,Tc,!1),this.refs["http://json-schema.org/schema"]=Tc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Tc)?Tc:void 0)}};Te.Ajv=Vo;tm.exports=Te=Vo;tm.exports.Ajv=Vo;Object.defineProperty(Te,"__esModule",{value:!0});Te.default=Vo;var pD=ii();Object.defineProperty(Te,"KeywordCxt",{enumerable:!0,get:function(){return pD.KeywordCxt}});var Wo=Q();Object.defineProperty(Te,"_",{enumerable:!0,get:function(){return Wo._}});Object.defineProperty(Te,"str",{enumerable:!0,get:function(){return Wo.str}});Object.defineProperty(Te,"stringify",{enumerable:!0,get:function(){return Wo.stringify}});Object.defineProperty(Te,"nil",{enumerable:!0,get:function(){return Wo.nil}});Object.defineProperty(Te,"Name",{enumerable:!0,get:function(){return Wo.Name}});Object.defineProperty(Te,"CodeGen",{enumerable:!0,get:function(){return Wo.CodeGen}});var fD=sc();Object.defineProperty(Te,"ValidationError",{enumerable:!0,get:function(){return fD.default}});var mD=ai();Object.defineProperty(Te,"MissingRefError",{enumerable:!0,get:function(){return mD.default}})});var Uv=N(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.formatNames=_r.fastFormats=_r.fullFormats=void 0;function yr(t,e){return{validate:t,compare:e}}_r.fullFormats={date:yr(jv,im),time:yr(om(!0),am),"date-time":yr(Nv(!0),Lv),"iso-time":yr(om(),zv),"iso-date-time":yr(Nv(),Hv),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:SD,"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:PD,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:vD,int32:{type:"number",validate:ED},int64:{type:"number",validate:wD},float:{type:"number",validate:Mv},double:{type:"number",validate:Mv},password:!0,binary:!0};_r.fastFormats={..._r.fullFormats,date:yr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,im),time:yr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,am),"date-time":yr(/^\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,Lv),"iso-time":yr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,zv),"iso-date-time":yr(/^\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,Hv),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};_r.formatNames=Object.keys(_r.fullFormats);function hD(t){return t%4===0&&(t%100!==0||t%400===0)}var gD=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,yD=[0,31,28,31,30,31,30,31,31,30,31,30,31];function jv(t){let e=gD.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&hD(r)?29:yD[n])}function im(t,e){if(t&&e)return t>e?1:t<e?-1:0}var nm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function om(t){return function(r){let n=nm.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,f=o-u*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&i<61}}function am(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 zv(t,e){if(!(t&&e))return;let r=nm.exec(t),n=nm.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 sm=/t|\s/i;function Nv(t){let e=om(t);return function(n){let o=n.split(sm);return o.length===2&&jv(o[0])&&e(o[1])}}function Lv(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Hv(t,e){if(!(t&&e))return;let[r,n]=t.split(sm),[o,s]=e.split(sm),i=im(r,o);if(i!==void 0)return i||am(n,s)}var _D=/\/|:/,xD=/^(?:[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 SD(t){return _D.test(t)&&xD.test(t)}var Dv=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function vD(t){return Dv.lastIndex=0,Dv.test(t)}var bD=-(2**31),kD=2**31-1;function ED(t){return Number.isInteger(t)&&t<=kD&&t>=bD}function wD(t){return Number.isInteger(t)}function Mv(){return!0}var TD=/[^\\]\\Z/;function PD(t){if(TD.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Fv=N(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.formatLimitDefinition=void 0;var RD=rm(),rr=Q(),cn=rr.operators,Pc={formatMaximum:{okStr:"<=",ok:cn.LTE,fail:cn.GT},formatMinimum:{okStr:">=",ok:cn.GTE,fail:cn.LT},formatExclusiveMaximum:{okStr:"<",ok:cn.LT,fail:cn.GTE},formatExclusiveMinimum:{okStr:">",ok:cn.GT,fail:cn.LTE}},$D={message:({keyword:t,schemaCode:e})=>(0,rr.str)`should be ${Pc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,rr._)`{comparison: ${Pc[t].okStr}, limit: ${e}}`};Ko.formatLimitDefinition={keyword:Object.keys(Pc),type:"string",schemaType:"string",$data:!0,error:$D,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new RD.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,rr._)`${f}[${c.schemaCode}]`);t.fail$data((0,rr.or)((0,rr._)`typeof ${h} != "object"`,(0,rr._)`${h} instanceof RegExp`,(0,rr._)`typeof ${h}.compare != "function"`,d(h)))}function l(){let f=c.schema,h=a.formats[f];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let p=e.scopeValue("formats",{key:f,ref:h,code:i.code.formats?(0,rr._)`${i.code.formats}${(0,rr.getProperty)(f)}`:void 0});t.fail$data(d(p))}function d(f){return(0,rr._)`${f}.compare(${r}, ${n}) ${Pc[o].fail} 0`}},dependencies:["format"]};var CD=t=>(t.addKeyword(Ko.formatLimitDefinition),t);Ko.default=CD});var Vv=N((vi,Bv)=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});var Go=Uv(),OD=Fv(),cm=Q(),Zv=new cm.Name("fullFormats"),ID=new cm.Name("fastFormats"),um=(t,e={keywords:!0})=>{if(Array.isArray(e))return qv(t,e,Go.fullFormats,Zv),t;let[r,n]=e.mode==="fast"?[Go.fastFormats,ID]:[Go.fullFormats,Zv],o=e.formats||Go.formatNames;return qv(t,o,r,n),e.keywords&&(0,OD.default)(t),t};um.get=(t,e="full")=>{let n=(e==="fast"?Go.fastFormats:Go.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function qv(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,cm._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Bv.exports=vi=um;Object.defineProperty(vi,"__esModule",{value:!0});vi.default=um});function ki(t,e){let r=process.execPath.replace(/\\/g,"/");if(Mc(e?.platform)){let o=r.split("/").pop().replace(/\.exe$/i,"");fm.has(o)||(r=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let n=t.replace(/\\/g,"/");return`"${r}" "${n}"`}function Ze(t,e){if(Mc(e?.platform))return ki(t,e);let n=ib().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${n}" "${o}"`}function Dc(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}function Mc(t){return!!t&&HD.has(t)}var fm,HD,Nr=ne(()=>{"use strict";jc();fm=new Set(["node","bun","deno"]),HD=new Set(["opencode","kilo"])});import{execFileSync as gm,execSync as Jo}from"node:child_process";import{existsSync as zc}from"node:fs";function hm(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function FD(t){return UD.test(hm(t))}function ZD(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function Be(t){try{let e=Ei?`where ${t}`:`command -v ${t}`;return Jo(e,{stdio:"pipe"}),!0}catch{return!1}}function mm(t){if(Ei)try{let r=Jo(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(r.length===0||r.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!Be(t))return!1;try{return Ei?Jo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):gm(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function ym(){if(Be("bun"))return!0;for(let t of ub())if(zc(t))return!0;return!1}function cb(){for(let e of ub())if(zc(e))return e;if(Be("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Ei?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function ub(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Ei){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 qD(){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(zc(e))return e;try{let r=Jo("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean);for(let n of r){let o=n.toLowerCase();if(!(o.includes("system32")||o.includes("windowsapps")))return n}return null}catch{return null}}function Lt(t,e=["--version"]){try{if(process.platform==="win32"){let r=[t,...e].map(n=>/[\s"&|<>^()%!]/.test(n)?JSON.stringify(n):n).join(" ");return Jo(r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return gm(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function BD(t,e={}){if(t)return t;let r=e.execPath??process.execPath,n=e.commandExists??Be,o=r.split(/[\\/]/).pop().replace(/\.exe$/i,"");return fm.has(o)?r:n("node")?"node":null}function Lc(){let e=ym()?cb():null,r=process.env.SHELL,n=process.platform==="win32",o=r&&zc(r)&&FD(r)&&!(n&&ZD(r))?r:null;return{javascript:BD(e),typescript:e||(Be("tsx")?"tsx":Be("ts-node")?"ts-node":null),python:mm("python3")?"python3":mm("python")?"python":mm("py")?"py":null,shell:o??(n?qD()??(Be("sh")?"sh":Be("powershell")?"powershell":"cmd.exe"):Be("bash")?"bash":"sh"),ruby:Be("ruby")?"ruby":null,go:Be("go")?"go":null,rust:Be("rustc")?"rustc":null,php:Be("php")?"php":null,perl:Be("perl")?"perl":null,r:Be("Rscript")?"Rscript":Be("r")?"r":null,elixir:Be("elixir")?"elixir":null,csharp:Be("dotnet-script")?"dotnet-script":null}}function Hc(){return ym()}function VD(t){let e=t.trim(),r=/^(\d+)\.(\d+)\.(\d+)/.exec(e);if(!r)return!1;let n=Number(r[1]);return Number.isFinite(n)&&n>=1}function ib(){if(Ht)return Ht;let t={path:process.execPath,isBun:!1};try{if(!ym())return Ht=t,Ht;let e=cb(),r;try{if(process.platform==="win32"){let n=Jo(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});r=String(n)}else{let n=gm(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});r=String(n)}}catch{return Ht=t,Ht}return VD(r)?(Ht={path:e,isBun:!0},Ht):(Ht=t,Ht)}catch{return Ht=t,Ht}}function lb(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${Lt(t.javascript)})${r?" \u26A1":""}`):e.push(" JavaScript: not available (install node or bun \u2014 host process is not a JS runtime)"),t.typescript?e.push(` TypeScript: ${t.typescript} (${Lt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Lt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Lt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Lt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Lt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Lt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Lt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Lt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Lt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Lt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Lt(t.csharp)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
|
|
10
|
-
`)}function
|
|
11
|
-
`))}function
|
|
12
|
-
`)}function
|
|
9
|
+
deps: ${n}}`};var eD={keyword:"dependencies",type:"object",schemaType:"object",error:yn.error,code(t){let[e,n]=tD(t);Pk(t,e),Rk(t,n)}};function tD({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function Pk(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let s=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Ei.propertyInData)(n,r,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let u of a)(0,Ei.checkReportMissingProp)(t,u)}):(n.if((0,Yf._)`${c} && (${(0,Ei.checkMissingProp)(t,a,s)})`),(0,Ei.reportMissingProp)(t,s),n.else())}}yn.validatePropertyDeps=Pk;function Rk(t,e=t.schema){let{gen:n,data:r,keyword:o,it:s}=t,i=n.name("valid");for(let a in e)(0,QN.alwaysValidSchema)(s,e[a])||(n.if((0,Ei.propertyInData)(n,r,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>n.var(i,!0)),t.ok(i))}yn.validateSchemaDeps=Rk;yn.default=eD});var Ok=I(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var $k=ee(),nD=ue(),rD={message:"property name must be valid",params:({params:t})=>(0,$k._)`{propertyName: ${t.propertyName}}`},oD={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:rD,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,nD.alwaysValidSchema)(o,n))return;let s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,$k.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Qf.default=oD});var tm=I(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});var Tc=zt(),nn=ee(),sD=An(),Pc=ue(),iD={message:"must NOT have additional properties",params:({params:t})=>(0,nn._)`{additionalProperty: ${t.additionalProperty}}`},aD={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:iD,code(t){let{gen:e,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Pc.alwaysValidSchema)(i,n))return;let u=(0,Tc.allSchemaProperties)(r.properties),l=(0,Tc.allSchemaProperties)(r.patternProperties);d(),t.ok((0,nn._)`${s} === ${sD.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?p(g):e.if(f(g),()=>p(g))})}function f(g){let y;if(u.length>8){let _=(0,Pc.schemaRefOrVal)(i,r.properties,"properties");y=(0,Tc.isOwnProperty)(e,_,g)}else u.length?y=(0,nn.or)(...u.map(_=>(0,nn._)`${g} === ${_}`)):y=nn.nil;return l.length&&(y=(0,nn.or)(y,...l.map(_=>(0,nn._)`${(0,Tc.usePattern)(t,_)}.test(${g})`))),(0,nn.not)(y)}function m(g){e.code((0,nn._)`delete ${o}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){m(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Pc.alwaysValidSchema)(i,n)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,nn.not)(y),()=>{t.reset(),m(g)})):(h(g,y),a||e.if((0,nn.not)(y),()=>e.break()))}}function h(g,y,_){let S={keyword:"additionalProperties",dataProp:g,dataPropType:Pc.Type.Str};_===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,y)}}};em.default=aD});var Nk=I(rm=>{"use strict";Object.defineProperty(rm,"__esModule",{value:!0});var cD=li(),Ik=zt(),nm=ue(),Ak=tm(),uD={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Ak.default.code(new cD.KeywordCxt(s,Ak.default,"additionalProperties"));let i=(0,Ik.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=nm.mergeEvaluated.props(e,(0,nm.toHash)(i),s.props));let a=i.filter(d=>!(0,nm.alwaysValidSchema)(s,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,Ik.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};rm.default=uD});var zk=I(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});var Dk=zt(),Rc=ee(),Mk=ue(),jk=ue(),lD={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Dk.allSchemaProperties)(n),c=a.filter(h=>(0,Mk.alwaysValidSchema)(s,n[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Rc.Name)&&(s.props=(0,jk.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let h of a)u&&m(h),s.allErrors?p(h):(e.var(l,!0),p(h),e.if(l))}function m(h){for(let g in u)new RegExp(h).test(g)&&(0,Mk.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",r,g=>{e.if((0,Rc._)`${(0,Dk.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:jk.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Rc._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,Rc.not)(l),()=>e.break())})})}}};om.default=lD});var Lk=I(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var dD=ue(),pD={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,dD.alwaysValidSchema)(r,n)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};sm.default=pD});var Hk=I(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});var fD=zt(),mD={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:fD.validateUnion,error:{message:"must match a schema in anyOf"}};im.default=mD});var Uk=I(am=>{"use strict";Object.defineProperty(am,"__esModule",{value:!0});var Cc=ee(),hD=ue(),gD={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Cc._)`{passingSchemas: ${t.passing}}`},yD={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:gD,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let s=n,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let f;(0,hD.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Cc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Cc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,Cc.Name)})})}}};am.default=yD});var Fk=I(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});var _D=ue(),SD={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((s,i)=>{if((0,_D.alwaysValidSchema)(r,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};cm.default=SD});var qk=I(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});var $c=ee(),Bk=ue(),xD={message:({params:t})=>(0,$c.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,$c._)`{failingKeyword: ${t.ifClause}}`},kD={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:xD,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Bk.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=Zk(r,"then"),s=Zk(r,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,$c.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let f=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(f,i),d?e.assign(d,(0,$c._)`${l}`):t.setParams({ifClause:l})}}}};function Zk(t,e){let n=t.schema[e];return n!==void 0&&!(0,Bk.alwaysValidSchema)(t,n)}um.default=kD});var Vk=I(lm=>{"use strict";Object.defineProperty(lm,"__esModule",{value:!0});var bD=ue(),vD={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,bD.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};lm.default=vD});var Wk=I(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});var ED=Wf(),wD=vk(),TD=Kf(),PD=wk(),RD=Tk(),CD=Ck(),$D=Ok(),OD=tm(),ID=Nk(),AD=zk(),ND=Lk(),DD=Hk(),MD=Uk(),jD=Fk(),zD=qk(),LD=Vk();function HD(t=!1){let e=[ND.default,DD.default,MD.default,jD.default,zD.default,LD.default,$D.default,OD.default,CD.default,ID.default,AD.default];return t?e.push(wD.default,PD.default):e.push(ED.default,TD.default),e.push(RD.default),e}dm.default=HD});var Kk=I(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});var Me=ee(),UD={message:({schemaCode:t})=>(0,Me.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Me._)`{format: ${t}}`},FD={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:UD,code(t,e){let{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?f():m();function f(){let p=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=n.const("fDef",(0,Me._)`${p}[${i}]`),g=n.let("fType"),y=n.let("format");n.if((0,Me._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(g,(0,Me._)`${h}.type || "string"`).assign(y,(0,Me._)`${h}.validate`),()=>n.assign(g,(0,Me._)`"string"`).assign(y,h)),t.fail$data((0,Me.or)(_(),S()));function _(){return c.strictSchema===!1?Me.nil:(0,Me._)`${i} && !${y}`}function S(){let k=l.$async?(0,Me._)`(${h}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Me._)`${y}(${r})`,v=(0,Me._)`(typeof ${y} == "function" ? ${k} : ${y}.test(${r}))`;return(0,Me._)`${y} && ${y} !== true && ${g} === ${e} && !${v}`}}function m(){let p=d.formats[s];if(!p){_();return}if(p===!0)return;let[h,g,y]=S(p);h===e&&t.pass(k());function _(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function S(v){let O=v instanceof RegExp?(0,Me.regexpCode)(v):c.code.formats?(0,Me._)`${c.code.formats}${(0,Me.getProperty)(s)}`:void 0,R=n.scopeValue("formats",{key:s,ref:v,code:O});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Me._)`${R}.validate`]:["string",v,R]}function k(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Me._)`await ${y}(${r})`}return typeof g=="function"?(0,Me._)`${y}(${r})`:(0,Me._)`${y}.test(${r})`}}}};pm.default=FD});var Gk=I(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});var ZD=Kk(),BD=[ZD.default];fm.default=BD});var Jk=I(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.contentVocabulary=qo.metadataVocabulary=void 0;qo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];qo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Yk=I(mm=>{"use strict";Object.defineProperty(mm,"__esModule",{value:!0});var qD=sk(),VD=Sk(),WD=Wk(),KD=Gk(),Xk=Jk(),GD=[qD.default,VD.default,(0,WD.default)(),KD.default,Xk.metadataVocabulary,Xk.contentVocabulary];mm.default=GD});var eb=I(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});Oc.DiscrError=void 0;var Qk;(function(t){t.Tag="tag",t.Mapping="mapping"})(Qk||(Oc.DiscrError=Qk={}))});var nb=I(gm=>{"use strict";Object.defineProperty(gm,"__esModule",{value:!0});var Vo=ee(),hm=eb(),tb=fc(),JD=di(),XD=ue(),YD={message:({params:{discrError:t,tagName:e}})=>t===hm.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Vo._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},QD={keyword:"discriminator",type:"object",schemaType:"object",error:YD,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Vo._)`${n}${(0,Vo.getProperty)(a)}`);e.if((0,Vo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:hm.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let m=f();e.if(!1);for(let p in m)e.elseIf((0,Vo._)`${u} === ${p}`),e.assign(c,d(m[p]));e.else(),t.error(!1,{discrError:hm.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(m){let p=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:m},p);return t.mergeEvaluated(h,Vo.Name),p}function f(){var m;let p={},h=y(o),g=!0;for(let k=0;k<i.length;k++){let v=i[k];if(v?.$ref&&!(0,XD.schemaHasRulesButRef)(v,s.self.RULES)){let R=v.$ref;if(v=tb.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),v instanceof tb.SchemaEnv&&(v=v.schema),v===void 0)throw new JD.default(s.opts.uriResolver,s.baseId,R)}let O=(m=v?.properties)===null||m===void 0?void 0:m[a];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(v)),_(O,k)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:k}){return Array.isArray(k)&&k.includes(a)}function _(k,v){if(k.const)S(k.const,v);else if(k.enum)for(let O of k.enum)S(O,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function S(k,v){if(typeof k!="string"||k in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[k]=v}}}};gm.default=QD});var rb=I((P4,eM)=>{eM.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 _m=I((Ee,ym)=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.MissingRefError=Ee.ValidationError=Ee.CodeGen=Ee.Name=Ee.nil=Ee.stringify=Ee.str=Ee._=Ee.KeywordCxt=Ee.Ajv=void 0;var tM=Qx(),nM=Yk(),rM=nb(),ob=rb(),oM=["/properties"],Ic="http://json-schema.org/draft-07/schema",Wo=class extends tM.default{_addVocabularies(){super._addVocabularies(),nM.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(rM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ob,oM):ob;this.addMetaSchema(e,Ic,!1),this.refs["http://json-schema.org/schema"]=Ic}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ic)?Ic:void 0)}};Ee.Ajv=Wo;ym.exports=Ee=Wo;ym.exports.Ajv=Wo;Object.defineProperty(Ee,"__esModule",{value:!0});Ee.default=Wo;var sM=li();Object.defineProperty(Ee,"KeywordCxt",{enumerable:!0,get:function(){return sM.KeywordCxt}});var Ko=ee();Object.defineProperty(Ee,"_",{enumerable:!0,get:function(){return Ko._}});Object.defineProperty(Ee,"str",{enumerable:!0,get:function(){return Ko.str}});Object.defineProperty(Ee,"stringify",{enumerable:!0,get:function(){return Ko.stringify}});Object.defineProperty(Ee,"nil",{enumerable:!0,get:function(){return Ko.nil}});Object.defineProperty(Ee,"Name",{enumerable:!0,get:function(){return Ko.Name}});Object.defineProperty(Ee,"CodeGen",{enumerable:!0,get:function(){return Ko.CodeGen}});var iM=dc();Object.defineProperty(Ee,"ValidationError",{enumerable:!0,get:function(){return iM.default}});var aM=di();Object.defineProperty(Ee,"MissingRefError",{enumerable:!0,get:function(){return aM.default}})});var pb=I(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.formatNames=Sn.fastFormats=Sn.fullFormats=void 0;function _n(t,e){return{validate:t,compare:e}}Sn.fullFormats={date:_n(cb,bm),time:_n(xm(!0),vm),"date-time":_n(sb(!0),lb),"iso-time":_n(xm(),ub),"iso-date-time":_n(sb(),db),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:fM,"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:xM,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:mM,int32:{type:"number",validate:yM},int64:{type:"number",validate:_M},float:{type:"number",validate:ab},double:{type:"number",validate:ab},password:!0,binary:!0};Sn.fastFormats={...Sn.fullFormats,date:_n(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,bm),time:_n(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,vm),"date-time":_n(/^\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,lb),"iso-time":_n(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,ub),"iso-date-time":_n(/^\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,db),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};Sn.formatNames=Object.keys(Sn.fullFormats);function cM(t){return t%4===0&&(t%100!==0||t%400===0)}var uM=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,lM=[0,31,28,31,30,31,30,31,31,30,31,30,31];function cb(t){let e=uM.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&cM(n)?29:lM[r])}function bm(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Sm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function xm(t){return function(n){let r=Sm.exec(n);if(!r)return!1;let o=+r[1],s=+r[2],i=+r[3],a=r[4],c=r[5]==="-"?-1:1,u=+(r[6]||0),l=+(r[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,f=o-u*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&i<61}}function vm(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function ub(t,e){if(!(t&&e))return;let n=Sm.exec(t),r=Sm.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var km=/t|\s/i;function sb(t){let e=xm(t);return function(r){let o=r.split(km);return o.length===2&&cb(o[0])&&e(o[1])}}function lb(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function db(t,e){if(!(t&&e))return;let[n,r]=t.split(km),[o,s]=e.split(km),i=bm(n,o);if(i!==void 0)return i||vm(r,s)}var dM=/\/|:/,pM=/^(?:[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 fM(t){return dM.test(t)&&pM.test(t)}var ib=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function mM(t){return ib.lastIndex=0,ib.test(t)}var hM=-(2**31),gM=2**31-1;function yM(t){return Number.isInteger(t)&&t<=gM&&t>=hM}function _M(t){return Number.isInteger(t)}function ab(){return!0}var SM=/[^\\]\\Z/;function xM(t){if(SM.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var fb=I(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.formatLimitDefinition=void 0;var kM=_m(),rn=ee(),cr=rn.operators,Ac={formatMaximum:{okStr:"<=",ok:cr.LTE,fail:cr.GT},formatMinimum:{okStr:">=",ok:cr.GTE,fail:cr.LT},formatExclusiveMaximum:{okStr:"<",ok:cr.LT,fail:cr.GTE},formatExclusiveMinimum:{okStr:">",ok:cr.GT,fail:cr.LTE}},bM={message:({keyword:t,schemaCode:e})=>(0,rn.str)`should be ${Ac[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,rn._)`{comparison: ${Ac[t].okStr}, limit: ${e}}`};Go.formatLimitDefinition={keyword:Object.keys(Ac),type:"string",schemaType:"string",$data:!0,error:bM,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new kM.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,rn._)`${f}[${c.schemaCode}]`);t.fail$data((0,rn.or)((0,rn._)`typeof ${m} != "object"`,(0,rn._)`${m} instanceof RegExp`,(0,rn._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let f=c.schema,m=a.formats[f];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let p=e.scopeValue("formats",{key:f,ref:m,code:i.code.formats?(0,rn._)`${i.code.formats}${(0,rn.getProperty)(f)}`:void 0});t.fail$data(d(p))}function d(f){return(0,rn._)`${f}.compare(${n}, ${r}) ${Ac[o].fail} 0`}},dependencies:["format"]};var vM=t=>(t.addKeyword(Go.formatLimitDefinition),t);Go.default=vM});var yb=I((wi,gb)=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});var Jo=pb(),EM=fb(),Em=ee(),mb=new Em.Name("fullFormats"),wM=new Em.Name("fastFormats"),wm=(t,e={keywords:!0})=>{if(Array.isArray(e))return hb(t,e,Jo.fullFormats,mb),t;let[n,r]=e.mode==="fast"?[Jo.fastFormats,wM]:[Jo.fullFormats,mb],o=e.formats||Jo.formatNames;return hb(t,o,n,r),e.keywords&&(0,EM.default)(t),t};wm.get=(t,e="full")=>{let r=(e==="fast"?Jo.fastFormats:Jo.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function hb(t,e,n,r){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Em._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}gb.exports=wi=wm;Object.defineProperty(wi,"__esModule",{value:!0});wi.default=wm});function Pi(t,e){let n=process.execPath.replace(/\\/g,"/");if(Fc(e?.platform)){let o=n.split("/").pop().replace(/\.exe$/i,"");Cm.has(o)||(n=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let r=t.replace(/\\/g,"/");return`"${n}" "${r}"`}function Le(t,e){if(Fc(e?.platform))return Pi(t,e);let r=Ob().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${r}" "${o}"`}function Uc(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}function Fc(t){return!!t&&AM.has(t)}var Cm,AM,Mn=X(()=>{"use strict";Zc();Cm=new Set(["node","bun","deno"]),AM=new Set(["opencode","kilo"])});import{execFileSync as Im,execSync as Xo}from"node:child_process";import{existsSync as Yo}from"node:fs";function Om(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function DM(t){return NM.test(Om(t))}function MM(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function jM(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\cmd\.exe$/.test(e)}function He(t){try{let e=Ri?`where ${t}`:`command -v ${t}`;return Xo(e,{stdio:"pipe"}),!0}catch{return!1}}function $m(t){if(Ri)try{let n=Xo(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(n.length===0||n.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!He(t))return!1;try{return Ri?Xo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):Im(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function Am(){if(He("bun"))return!0;for(let t of Nb())if(Yo(t))return!0;return!1}function Ab(){for(let e of Nb())if(Yo(e))return e;if(He("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Ri?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Nb(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Ri){let e=process.env.LOCALAPPDATA??"",n=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...n?[`${n}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function Db(){let t;try{t=Xo("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean)}catch{return null}for(let e of t){let n=e.toLowerCase();if(!(n.includes("system32")||n.includes("windowsapps"))){for(let r of zM)if(Yo(r))return r;return e}}return null}function LM(t=Db()){return t??(He("sh")?"sh":He("pwsh")?"pwsh":He("powershell")?"powershell":"cmd.exe")}function Ut(t,e=["--version"]){try{if(process.platform==="win32"){let n=[t,...e].map(r=>/[\s"&|<>^()%!]/.test(r)?JSON.stringify(r):r).join(" ");return Xo(n,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return Im(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function HM(t,e={}){if(t)return t;let n=e.execPath??process.execPath,r=e.commandExists??He,o=n.split(/[\\/]/).pop().replace(/\.exe$/i,"");return Cm.has(o)&&Yo(n)?n:r("node")?"node":null}function Bc(){let e=Am()?Ab():null,n=process.env.SHELL,r=process.platform==="win32",o=r?Db():null,s=n&&Yo(n)&&DM(n)&&!(r&&MM(n))&&!(r&&o&&jM(n))?n:null;return{javascript:HM(e),typescript:e||(He("tsx")?"tsx":He("ts-node")?"ts-node":null),python:$m("python3")?"python3":$m("python")?"python":$m("py")?"py":null,shell:s??(r?LM(o):He("bash")?"bash":"sh"),ruby:He("ruby")?"ruby":null,go:He("go")?"go":null,rust:He("rustc")?"rustc":null,php:He("php")?"php":null,perl:He("perl")?"perl":null,r:He("Rscript")?"Rscript":He("r")?"r":null,elixir:He("elixir")?"elixir":null,csharp:He("dotnet-script")?"dotnet-script":null}}function qc(){return Am()}function UM(t){let e=t.trim(),n=/^(\d+)\.(\d+)\.(\d+)/.exec(e);if(!n)return!1;let r=Number(n[1]);return Number.isFinite(r)&&r>=1}function FM(){return Yo(process.execPath)?{path:process.execPath,isBun:!1}:He("node")?{path:"node",isBun:!1}:{path:process.execPath,isBun:!1}}function Ob(){if(Ft)return Ft;let t=FM();try{if(!Am())return Ft=t,Ft;let e=Ab(),n;try{if(process.platform==="win32"){let r=Xo(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}else{let r=Im(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}}catch{return Ft=t,Ft}return UM(n)?(Ft={path:e,isBun:!0},Ft):(Ft=t,Ft)}catch{return Ft=t,Ft}}function Mb(t){let e=[],n=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${Ut(t.javascript)})${n?" \u26A1":""}`):e.push(" JavaScript: not available (install node or bun \u2014 host process is not a JS runtime)"),t.typescript?e.push(` TypeScript: ${t.typescript} (${Ut(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Ut(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Ut(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Ut(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Ut(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Ut(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Ut(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Ut(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Ut(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Ut(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Ut(t.csharp)})`),n||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
|
|
10
|
+
`)}function jb(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),t.csharp&&e.push("csharp"),e}function zb(t,e,n){switch(e){case"javascript":if(!t.javascript)throw new Error("No JavaScript runtime available. Install Node.js or Bun on PATH (the host process is not itself a JS runtime).");return Ib.test(Om(t.javascript))?[t.javascript,"run",n]:[t.javascript,n];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return Ib.test(Om(t.typescript))?[t.typescript,"run",n]:t.typescript==="tsx"?["tsx",n]:["ts-node",n];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,n];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let i=n.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${i}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-NoProfile","-ExecutionPolicy","Bypass","-File",n];let s=o.split(/[\\/]/).pop()??o;if(s==="cmd"||s==="cmd.exe")return[t.shell,"/d","/s","/c",n]}return[t.shell,n]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,n];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",n];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",n]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",n];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",n];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,n];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",n];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,n]}}var NM,Ib,Ri,zM,Ft,Zc=X(()=>{"use strict";Mn();NM=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,Ib=/^bun(\.exe)?$/i;Ri=process.platform==="win32";zM=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];Ft=null});import{createRequire as rj}from"node:module";import{existsSync as oj,unlinkSync as qb,renameSync as sj}from"node:fs";import{tmpdir as ij}from"node:os";import{join as aj}from"node:path";function cj(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 uj(t,e){let n=e!==void 0?e:globalThis.Bun;if(typeof n<"u"&&n!==null)return!0;let r=t??process.versions,[o,s]=(r.node??"0.0.0").split("."),i=Number(o),a=Number(s);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function Ye(){if(!Qo){let t=rj(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;Qo=function(r,o){let s=new e(r,{readonly:o?.readonly,create:!0}),i=new jm(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(uj()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&cj(e)?Qo=function(r,o){let s=new e(r,{readOnly:o?.readonly??!1}),i=new zm(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:Qo=t("better-sqlite3")}else Qo=t("better-sqlite3")}return Qo}function Oi(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function Ii(t){if(!oj(t))for(let e of["-wal","-shm"])try{qb(t+e)}catch{}}function Lm(t){for(let e of["","-wal","-shm"])try{qb(t+e)}catch{}}function Ai(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function Vb(t="context-mode"){return aj(ij(),`${t}-${process.pid}.db`)}function Yr(t,e=[100,500,2e3]){let n;for(let r=0;r<=e.length;r++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(n=o instanceof Error?o:new Error(s),r<e.length){let i=e[r],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${n?.message}`)}function Hm(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 lj(t){let e=Date.now();for(let n of["","-wal","-shm"])try{sj(t+n,`${t}${n}.corrupt-${e}`)}catch{}}var jm,zm,Qo,$i,Mm,Wc,es=X(()=>{"use strict";jm=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){let n="",r=null;for(let s=0;s<e.length;s++){let i=e[s];if(r)n+=i,i===r&&(r=null);else if(i==="'"||i==='"')n+=i,r=i;else if(i===";"){let a=n.trim();a&&this.#e.prepare(a).run(),n=""}else n+=i}let o=n.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>{let o=n.get(...r);return o===null?void 0:o},all:(...r)=>n.all(...r),iterate:(...r)=>n.iterate(...r)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},zm=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){return this.#e.exec(e),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>n.get(...r),all:(...r)=>n.all(...r),iterate:(...r)=>typeof n.iterate=="function"?n.iterate(...r):n.all(...r)[Symbol.iterator]()}}transaction(e){return(...n)=>{this.#e.exec("BEGIN");try{let r=e(...n);return this.#e.exec("COMMIT"),r}catch(r){throw this.#e.exec("ROLLBACK"),r}}}close(){this.#e.close()}},Qo=null;$i=Symbol.for("__context_mode_live_dbs_v3__"),Mm=(()=>{let t=globalThis;return t[$i]||(t[$i]=new Set,process.on("exit",()=>{for(let e of t[$i])Ai(e);t[$i].clear()})),t[$i]})(),Wc=class{#e;#t;constructor(e){let n=Ye();this.#e=e,Ii(e);let r;try{r=new n(e,{timeout:3e4}),Oi(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(Hm(s)){lj(e),Ii(e);try{r=new n(e,{timeout:3e4}),Oi(r)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=r,Mm.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){Mm.delete(this.#t),Ai(this.#t)}withRetry(e){return Yr(e)}cleanup(){Mm.delete(this.#t),Ai(this.#t),Lm(this.#e)}}});var av,cv=X(()=>{"use strict";av={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","antigravity-cli":"antigravity-cli",agy:"antigravity-cli","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","copilot-cli":"copilot-cli","GitHub Copilot CLI":"copilot-cli","github-copilot-cli":"copilot-cli","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code","kimi-code":"kimi",kimi:"kimi","Kimi Code":"kimi"}});import{createHash as Di}from"node:crypto";import{execFileSync as jj}from"node:child_process";import{accessSync as zj,constants as Lj,existsSync as Yc,mkdirSync as Hj,realpathSync as Uj,renameSync as Km}from"node:fs";import{homedir as mv}from"node:os";import{dirname as Fj,isAbsolute as hv,join as lr,resolve as ns}from"node:path";function Gm(t){let e=t.env??process.env,n=t.legacySessionDirEnv,r=n?e[n]?.trim():void 0;return r&&n?(t.onLegacySessionDir?.(n,r),r):lr(Zj(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function Zj(t,e,n){let r=e?n[e]:void 0;return r&&r.trim()!==""?lv(r.trim()):lv(t,mv())}function lv(t,e){return t.startsWith("~")?ns(mv(),t.replace(/^~[/\\]?/,"")):hv(t)?ns(t):e?ns(e,t):ns(t)}function Bj(t,e,n){return new dr(t,e,xn,void 0,[`Invalid ${xn} for context-mode ${t} directory: ${n}`,xv()].join(`
|
|
11
|
+
`))}function yv(t){let e=process.env[xn];if(e===void 0)return{kind:"unset"};let n=e.trim();if(!n)return{kind:"ignored-empty",ignoredEnvVar:xn,ignoredReason:"empty"};if(!hv(n))throw Bj(t,n,`${xn} must be an absolute path.`);return{kind:"override",root:ns(n)}}function qj(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function _v(t,e){let n=yv(t);return n.kind!=="override"?null:{kind:t,path:lr(n.root,e),envVar:xn,source:"override"}}function Vj(t,e,n){return{kind:t,path:ns(e()),envVar:null,source:"default",...n}}function Mi(t){let e=yv("session");return e.kind==="override"?{kind:"session",path:lr(e.root,gv),envVar:xn,source:"override"}:Vj("session",t,qj(e))}function Jm(t){let e=_v("content",uv);if(e)return e;let n=Mi(t);return{kind:"content",path:lr(Fj(n.path),uv),envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function Xm(t){let e=_v("stats",gv);if(e)return e;let n=Mi(t);return{kind:"stats",path:n.path,envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function Sv(t){return t.message}function Qc(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function eu(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),n=Wm.get(e);if(n instanceof dr)throw n;if(n===t.path)return n;try{return Hj(t.path,{recursive:!0}),zj(t.path,Lj.W_OK),Wm.set(e,t.path),t.path}catch(r){let o=new dr(t.kind,Gj(r)??t.path,xn,r,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw Wm.set(e,o),o}}function Wj(t,e,n={}){return[`context-mode ${t} directory is not writable: ${e}`,Kj(n),xv()].filter(Boolean).join(`
|
|
12
|
+
`)}function Kj(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function xv(){return`Set ${xn} to a writable absolute path.`}function Gj(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function Qr(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function dv(t){let e=t;try{e=Uj.native(t)}catch{}let n=Qr(e);return process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n}function kv(t,e){return jj("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function Jj(t){let e=kv(t,["rev-parse","--show-toplevel"]);return e.length>0?Qr(e):null}function Xj(t){let e=kv(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(n=>n.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?Qr(e):null}function tu(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(Ni&&Ni.projectDir===t&&Ni.envSuffix===e)return Ni.suffix;let n="";if(e!==void 0)n=e?`__${e}`:"";else try{let r=Jj(t),o=Xj(t);if(r&&o){let s=dv(r),i=dv(o);s!==i&&(n=`__${Di("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return Ni={projectDir:t,envSuffix:e,suffix:n},n}function jn(t){return Di("sha256").update(Qr(t)).digest("hex").slice(0,16)}function Qe(t){let e=Qr(t),n=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Di("sha256").update(n).digest("hex").slice(0,16)}function bv(t){let{projectDir:e,contentDir:n}=t,r=Qe(e),o=lr(n,`${r}.db`);if(Yc(o))return o;let s=jn(e);if(s===r)return o;let i=lr(n,`${s}.db`);if(Yc(i))try{Km(i,o);for(let a of["-wal","-shm"])try{Km(i+a,o+a)}catch{}}catch{}return o}function ji(t){return Yj({...t,ext:".db"})}function Yj(t){let{projectDir:e,sessionsDir:n,ext:r}=t,o=t.suffix??tu(e),s=Qe(e),i=lr(n,`${s}${o}${r}`);if(Yc(i))return i;let a=jn(e);if(a===s)return i;let c=lr(n,`${a}${o}${r}`);if(Yc(c))try{Km(c,i)}catch{}return i}function Xc(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function vv(t){let e=t.pragma("table_xinfo(session_events)"),n=new Set(e.map(o=>o.name)),r=!1;for(let[o,s]of Qj)n.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),r=!0);return r&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),r}function Ev(t,e){let n=null;try{n=new e(t),vv(n)}catch{}finally{try{n?.close()}catch{}}}var xn,gv,uv,dr,Wm,Ni,pv,fv,j,Qj,on,kn=X(()=>{"use strict";es();xn="CONTEXT_MODE_DIR",gv="sessions",uv="content",dr=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,n,r=xn,o,s,i={}){super(s??Wj(e,n,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=n,this.overrideEnvVar=r,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},Wm=new Map;pv=1e3,fv=5;j={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",getSessionRollup:"getSessionRollup",getMaxFileEdits:"getMaxFileEdits",getLatestCommitMessage:"getLatestCommitMessage",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",claimLatestUnconsumedResume:"claimLatestUnconsumedResume",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions",searchEvents:"searchEvents",incrementToolCall:"incrementToolCall",getToolCallTotals:"getToolCallTotals",getToolCallByTool:"getToolCallByTool",getEventBytesSummary:"getEventBytesSummary"},Qj=[["project_dir","TEXT NOT NULL DEFAULT ''"],["attribution_source","TEXT NOT NULL DEFAULT 'unknown'"],["attribution_confidence","REAL NOT NULL DEFAULT 0"],["bytes_avoided","INTEGER NOT NULL DEFAULT 0"],["bytes_returned","INTEGER NOT NULL DEFAULT 0"]];on=class extends Wc{constructor(e){super(e?.dbPath??Vb("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let n=this.db.pragma("table_xinfo(session_events)").find(r=>r.name==="data_hash");n&&n.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
|
|
13
13
|
CREATE TABLE IF NOT EXISTS session_events (
|
|
14
14
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
15
15
|
session_id TEXT NOT NULL,
|
|
@@ -59,7 +59,7 @@ var Uw=Object.create;var Mu=Object.defineProperty;var Fw=Object.getOwnPropertyDe
|
|
|
59
59
|
);
|
|
60
60
|
|
|
61
61
|
CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
|
|
62
|
-
`);try{
|
|
62
|
+
`);try{vv(this.db)}catch{}}prepareStatements(){this.stmts=new Map;let e=(n,r)=>{this.stmts.set(n,this.db.prepare(r))};e(j.insertEvent,`INSERT INTO session_events (
|
|
63
63
|
session_id, type, category, priority, data,
|
|
64
64
|
project_dir, attribution_source, attribution_confidence,
|
|
65
65
|
bytes_avoided, bytes_returned,
|
|
@@ -148,106 +148,114 @@ var Uw=Object.create;var Mu=Object.defineProperty;var Fw=Object.getOwnPropertyDe
|
|
|
148
148
|
FROM tool_calls WHERE session_id = ?`),e(j.getToolCallByTool,`SELECT tool, calls, bytes_returned
|
|
149
149
|
FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(j.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
150
150
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
151
|
-
FROM session_events WHERE session_id = ?`)}insertEvent(e,r
|
|
151
|
+
FROM session_events WHERE session_id = ?`)}insertEvent(e,n,r="PostToolUse",o,s){let i=Di("sha256").update(n.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??n.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??n.attribution_source??"unknown"),u=Number(o?.confidence??n.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=Xc(s?.bytesAvoided),f=Xc(s?.bytesReturned),m=this.db.transaction(()=>{if(this.stmt(j.checkDuplicate).get(e,fv,n.type,i))return;this.stmt(j.getEventCount).get(e).cnt>=pv&&this.stmt(j.evictLowestPriority).run(e),this.stmt(j.insertEvent).run(e,n.type,n.category,n.priority,n.data,a,c,l,d,f,r,i),this.stmt(j.updateMetaLastEvent).run(e)});this.withRetry(()=>m())}bulkInsertEvents(e,n,r="PostToolUse",o,s){if(!n||n.length===0)return;if(n.length===1){this.insertEvent(e,n[0],r,o?.[0],s?.[0]);return}let i=n.map((c,u)=>{let l=Di("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),d=o?.[u],f=String(d?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),m=f===""?"":Qr(f),p=String(d?.source??c.attribution_source??"unknown"),h=Number(d?.confidence??c.attribution_confidence??0),g=Number.isFinite(h)?Math.max(0,Math.min(1,h)):0,y=s?.[u],_=Xc(y?.bytesAvoided),S=Xc(y?.bytesReturned);return{event:c,dataHash:l,projectDir:m,attributionSource:p,attributionConfidence:g,bytesAvoided:_,bytesReturned:S}}),a=this.db.transaction(()=>{let c=this.stmt(j.getEventCount).get(e).cnt;for(let u of i)this.stmt(j.checkDuplicate).get(e,fv,u.event.type,u.dataHash)||(c>=pv?this.stmt(j.evictLowestPriority).run(e):c++,this.stmt(j.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,r,u.dataHash));this.stmt(j.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,n){let r=n?.limit??1e3,o=n?.type,s=n?.minPriority;return o&&s!==void 0?this.stmt(j.getEventsByTypeAndPriority).all(e,o,s,r):o?this.stmt(j.getEventsByType).all(e,o,r):s!==void 0?this.stmt(j.getEventsByPriority).all(e,s,r):this.stmt(j.getEvents).all(e,r)}getEventCount(e){return this.stmt(j.getEventCount).get(e).cnt}getEventBytesSummary(e){let n=this.stmt(j.getEventBytesSummary).get(e);return{bytesAvoided:Number(n?.bytes_avoided??0),bytesReturned:Number(n?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(j.getLatestAttributedProject).get(e)?.project_dir||null}_getSessionProjectDir(e){try{return this.db.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(e)?.project_dir||""}catch{return""}}searchEvents(e,n,r,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(j.searchEvents).all(r,s,s,i,i,n)}catch{return[]}}getSessionIdsForProject(e){try{let n=Qr(e);return this.db.prepare(`SELECT DISTINCT session_id
|
|
152
152
|
FROM session_events
|
|
153
|
-
WHERE project_dir = ?`).all(
|
|
154
|
-
`,"utf-8")}validateHooks(e){let
|
|
155
|
-
`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let
|
|
156
|
-
`,"utf-8")}validateHooks(e){let
|
|
157
|
-
`,"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}`}}});
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
`)
|
|
153
|
+
WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(n).map(o=>o.session_id)}catch{return[]}}ensureSession(e,n){this.stmt(j.ensureSession).run(e,n)}getSessionStats(e){return this.stmt(j.getSessionStats).get(e)??null}getSessionRollup(e){let n=this.stmt(j.getSessionRollup).get(e),r=this.stmt(j.getMaxFileEdits).get(e),o=this.stmt(j.getLatestCommitMessage).get(e),s=this.getSessionStats(e),i=(n?.tool_calls??0)>0?n?.unique_files??0:0,a=n?.errors??0,c=Math.min(i,a);return{tool_calls:n?.tool_calls??0,errors:n?.errors??0,unique_tools:n?.unique_tools??0,unique_files:n?.unique_files??0,max_file_edits:r?.max_file_edits??0,has_commit:n?.has_commit??0,commit_message:o?.data??"",edit_test_cycles:c,duration_min:n?.duration_min??0,compact_count:s?.compact_count??0,sources_indexed:n?.sources_indexed??0,total_chunks:n?.total_chunks??0,search_queries:n?.search_queries??0}}incrementCompactCount(e){this.stmt(j.incrementCompactCount).run(e)}upsertResume(e,n,r){this.stmt(j.upsertResume).run(e,n,r??0)}getResume(e){return this.stmt(j.getResume).get(e)??null}markResumeConsumed(e){this.stmt(j.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let n=this.stmt(j.claimLatestUnconsumedResume).get(e);return n?{sessionId:n.session_id,snapshot:n.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,n,r=0){let o=Number.isFinite(r)&&r>0?Math.round(r):0;try{this.stmt(j.incrementToolCall).run(e,n,o)}catch{}}getToolCallStats(e){try{let n=this.stmt(j.getToolCallTotals).get(e),r=this.stmt(j.getToolCallByTool).all(e),o={};for(let s of r)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:n?.calls??0,totalBytesReturned:n?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(j.deleteEvents).run(e),this.stmt(j.deleteResume).run(e),this.stmt(j.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let n=`-${e}`,r=this.stmt(j.getOldSessions).all(n);for(let{session_id:o}of r)this.deleteSession(o);return r.length}pruneOrphanedEvents(){let e=this.db.prepare("DELETE FROM session_events WHERE session_id NOT IN (SELECT session_id FROM session_meta)").run();return Number(e.changes??0)}}});import{join as rs,resolve as wv}from"node:path";import{accessSync as ez,copyFileSync as tz,constants as nz,mkdirSync as rz}from"node:fs";import{homedir as Ym}from"node:os";function it(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?wv(Ym(),e.replace(/^~[/\\]?/,"")):wv(e)}var ge,et=X(()=>{"use strict";kn();ge=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=it(),n=e?rs(e,"context-mode","sessions"):rs(Ym(),...this.sessionDirSegments,"context-mode","sessions");return rz(n,{recursive:!0}),n}getConfigDir(e){return rs(Ym(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let n=it(),r=n?rs(n,"context-mode","memory"):rs(this.getConfigDir(),"memory");return e?rs(r,Qe(e)):r}backupSettings(){let e=this.getSettingsPath();try{ez(e,nz.R_OK);let n=e+".bak";return tz(e,n),n}catch{return null}}}});var os,Qm=X(()=>{"use strict";et();os=class extends ge{parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),e.updatedOutput&&(n.updatedMCPToolOutput=e.updatedOutput),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});import{existsSync as eh}from"node:fs";import{join as th}from"node:path";async function oz(){if(ss)return ss;if(is)return null;try{let t=[new URL("../../scripts/plugin-cache-integrity.mjs",import.meta.url),new URL("./scripts/plugin-cache-integrity.mjs",import.meta.url)],e=null;for(let n of t)try{let r=await import(n.href);if(typeof r?.assertPluginCacheIntegrity=="function")return ss=r,ss}catch(r){e=r}return is=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return is=t instanceof Error?t.message:String(t),null}}function sz(t){let e=[];return eh(th(t,"start.mjs"))||e.push("start.mjs"),!eh(th(t,"server.bundle.mjs"))&&!eh(th(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function Tv(t){if(ss){let e=ss.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(is){let e=sz(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${is}); the MCP server cannot start. Reinstall: npm install -g context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${is}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var ss,is,Pv=X(()=>{"use strict";ss=null,is=null;oz()});function zi(t,e){let n=eo[e],r=rh(e);return t.hooks?.some(o=>o.command?.includes(n)||o.command?.includes(r))??!1}function rh(t,e){if(e){let n=eo[t];return Le(`${e}/hooks/${n}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function oh(t){let e=Uc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function $v(t){let e=Object.values(eo);return t.hooks?.some(n=>n.command!=null&&(e.some(r=>n.command.includes(r))||n.command.includes("context-mode hook")))??!1}var Zt,iz,nh,Rv,az,oV,eo,Cv,sV,Ov=X(()=>{"use strict";Mn();Zt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit",STOP:"Stop"},iz="mcp__",nh=["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",iz],Rv=nh.join("|"),az=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],oV=az.join("|"),eo={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs",Stop:"stop.mjs"},Cv=[Zt.PRE_TOOL_USE,Zt.SESSION_START],sV=[Zt.POST_TOOL_USE,Zt.PRE_COMPACT,Zt.USER_PROMPT_SUBMIT,Zt.STOP]});var ih={};De(ih,{ClaudeCodeAdapter:()=>sh});import{readFileSync as nu,writeFileSync as Iv,existsSync as Av,readdirSync as cz,chmodSync as uz,accessSync as lz,mkdirSync as dz,constants as pz}from"node:fs";import{resolve as ru,join as pr}from"node:path";import{homedir as Nv}from"node:os";var sh,ah=X(()=>{"use strict";Qm();et();to();Pv();Mn();Ov();sh=class extends os{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 Rt()}getSessionDir(){let e=it(),n=e?pr(e,"context-mode","sessions"):pr(this.getConfigDir(),"context-mode","sessions");return dz(n,{recursive:!0}),n}getSettingsPath(){return pr(this.getConfigDir(),"settings.json")}generateHookConfig(e){let n=Le(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...nh].map(o=>({matcher:o,hooks:[{type:"command",command:n}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/sessionstart.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/stop.mjs`)}]}]}}readSettings(){try{let e=nu(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){Iv(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
154
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),n;let o=r.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,Zt.PRE_TOOL_USE);n.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(o,s,Zt.SESSION_START);return n.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),n}getHealthChecks(e){let n=Object.entries(eo).map(([o,s])=>{let i=pr(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>Av(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),r={name:"Plugin cache integrity",check:()=>Tv(e)};return[...n,r]}readPluginHooks(e){let n=[pr(e,"hooks","hooks.json"),pr(e,".claude-plugin","hooks","hooks.json")];for(let r of n)try{let o=nu(r,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,n,r){let o=e?.[r];if(o&&o.length>0&&o.some(i=>zi(i,r)))return!0;let s=n?.[r];return!!(s&&s.length>0&&s.some(i=>zi(i,r)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let n=e.enabledPlugins;if(!n)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let r=Object.keys(n).find(o=>o.startsWith("context-mode"));return r&&n[r]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${r}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let n=pr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(nu(n,"utf-8")).plugins??{};for(let[s,i]of Object.entries(o)){if(!s.toLowerCase().includes("context-mode"))continue;let a=i;if(a.length>0&&typeof a[0].version=="string")return a[0].version}}catch{}let e=Array.from(new Set([this.getConfigDir(),Rt(),ru(Nv(),".claude"),ru(Nv(),".config","claude")]));for(let n of e){let r=ru(n,"plugins","cache","context-mode","context-mode");try{let s=cz(r).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let l=0;l<3;l++)if((c[l]??0)!==(u[l]??0))return(c[l]??0)-(u[l]??0);return 0});if(s.length>0)return s[s.length-1]}catch{}}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[];for(let u of Object.keys(r)){let l=r[u];if(!Array.isArray(l))continue;let d=l.filter(m=>{let p=m;if(!$v(p))return!0;let h=p.hooks??[];return h.every(y=>!y.command||!oh(y.command))?!0:h.every(y=>{let _=y.command?oh(y.command):null;return _?Av(_):!0})}),f=l.length-d.length;f>0&&(r[u]=d,o.push(`Removed ${f} stale ${u} hook(s)`))}let a=this.checkPluginRegistration().status==="pass"?this.readPluginHooks(e):void 0;if(a&&Cv.every(l=>this.checkHookType(void 0,a,l))){let l=Object.values(eo),d=f=>f!=null&&(l.some(m=>f.includes(m))||f.includes("context-mode hook"));for(let f of Object.keys(r)){let m=r[f];if(!Array.isArray(m))continue;let p=0;for(let g of m){let y=g,_=y.hooks??[],S=_.length;y.hooks=_.filter(k=>!d(k.command)),p+=S-y.hooks.length}let h=m.filter(g=>{let y=g.hooks;return Array.isArray(y)&&y.length>0});(p>0||h.length!==m.length)&&(r[f]=h,p>0&&o.push(`Removed ${p} duplicate ${f} hook(s) \u2014 covered by plugin hooks.json`))}return n.hooks=r,this.writeSettings(n),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let c=[Zt.PRE_TOOL_USE,Zt.SESSION_START];for(let u of c){let l=rh(u,e);if(u===Zt.PRE_TOOL_USE){let d={matcher:Rv,hooks:[{type:"command",command:l}]},f=r.PreToolUse;if(f&&Array.isArray(f)){let m=f.findIndex(p=>zi(p,u));m>=0?(f[m]=d,o.push(`Updated existing ${u} hook entry`)):(f.push(d),o.push(`Added ${u} hook entry`)),r.PreToolUse=f}else r.PreToolUse=[d],o.push(`Created ${u} hooks section`)}else{let d={matcher:"",hooks:[{type:"command",command:l}]},f=r[u];if(f&&Array.isArray(f)){let m=f.findIndex(p=>zi(p,u));m>=0?(f[m]=d,o.push(`Updated existing ${u} hook entry`)):(f.push(d),o.push(`Added ${u} hook entry`)),r[u]=f}else r[u]=[d],o.push(`Created ${u} hooks section`)}}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[];for(let[,r]of Object.entries(eo)){let o=ru(e,"hooks",r);try{lz(o,pz.R_OK),uz(o,493),n.push(o)}catch{}}return n}updatePluginRegistry(e,n){try{let r=pr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(nu(r,"utf-8"));for(let[s,i]of Object.entries(o.plugins||{}))if(s.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=n,a.lastUpdated=new Date().toISOString();Iv(r,JSON.stringify(o,null,2)+`
|
|
155
|
+
`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function no(t,e){let n=ou[t];return e&&n?Le(`${e}/hooks/gemini-cli/${n}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var we,Dv,ou,yV,_V,Mv=X(()=>{"use strict";Mn();we={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},Dv="mcp__(?!.*context-mode)",ou={[we.BEFORE_AGENT]:"beforeagent.mjs",[we.BEFORE_TOOL]:"beforetool.mjs",[we.AFTER_TOOL]:"aftertool.mjs",[we.PRE_COMPRESS]:"precompress.mjs",[we.SESSION_START]:"sessionstart.mjs"},yV=[we.BEFORE_TOOL,we.SESSION_START],_V=[we.AFTER_TOOL,we.PRE_COMPRESS]});var Lv={};De(Lv,{GeminiCLIAdapter:()=>uh});import{readFileSync as ch,writeFileSync as jv,mkdirSync as fz,accessSync as mz,chmodSync as hz,existsSync as gz,constants as yz}from"node:fs";import{resolve as Li,join as zv}from"node:path";import{homedir as su}from"node:os";var uh,Hv=X(()=>{"use strict";et();Mv();uh=class extends ge{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Li(su(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[we.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:no(we.BEFORE_AGENT,e)}]}],[we.BEFORE_TOOL]:[{matcher:`run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|${Dv}`,hooks:[{type:"command",command:no(we.BEFORE_TOOL,e)}]}],[we.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:no(we.AFTER_TOOL,e)}]}],[we.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:no(we.PRE_COMPRESS,e)}]}],[we.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:no(we.SESSION_START,e)}]}]}}readSettings(){try{let e=ch(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=Li(su(),".gemini");fz(n,{recursive:!0}),jv(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
156
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),n;let o=r.hooks,s=o?.[we.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else n.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[we.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else n.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return n}getHealthChecks(e){return Object.entries(ou).map(([n,r])=>{let o=zv(e,"hooks","gemini-cli",r);return{name:`Hook script: ${n} (${r})`,check:()=>gz(o)?{status:"OK",detail:o}:{status:"FAIL",detail:`not found at ${o}`}}})}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let n=e.extensions;return n&&(Array.isArray(n)?n.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(n).some(o=>o.includes("context-mode")))?{check:"Plugin registration",status:"pass",message:"context-mode found in extensions"}:{check:"Plugin registration",status:"warn",message:"context-mode not found in extensions (might be using standalone MCP mode)"}}getInstalledVersion(){try{let e=Li(su(),".gemini","extensions","context-mode","package.json"),n=JSON.parse(ch(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[],s=[{name:we.BEFORE_AGENT},{name:we.BEFORE_TOOL},{name:we.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:no(i.name,e)}]},u=r[i.name];if(u&&Array.isArray(u)){let l=u.findIndex(d=>d.hooks?.some(m=>m.command?.includes("context-mode")));l>=0?(u[l]=c,o.push(`Updated existing ${i.name} hook entry`)):(u.push(c),o.push(`Added ${i.name} hook entry`)),r[i.name]=u}else r[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[],r=zv(e,"hooks","gemini-cli");for(let o of Object.values(ou)){let s=Li(r,o);try{mz(s,yz.R_OK),hz(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){try{let r=Li(su(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(ch(r,"utf-8"));o.version=n,o.installPath=e,o.lastUpdated=new Date().toISOString(),jv(r,JSON.stringify(o,null,2)+`
|
|
157
|
+
`,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});function Hi(t){let e="",n=!1,r=!1,o=!1;for(let c=0;c<t.length;c++){let u=t[c],l=t[c+1];if(o){u==="*"&&l==="/"&&(o=!1,c++);continue}if(r){e+=u,r=!1;continue}if(u==="\\"){e+=u,r=n;continue}if(u==='"'){n=!n,e+=u;continue}if(!n&&u==="/"&&l==="/"){for(;c<t.length&&t[c]!==`
|
|
158
|
+
`;)c++;c<t.length&&(e+=`
|
|
159
|
+
`);continue}if(!n&&u==="/"&&l==="*"){o=!0,c++;continue}e+=u}let s="",i=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];if(a){s+=u,a=!1;continue}if(u==="\\"){s+=u,a=i;continue}if(u==='"'){i=!i,s+=u;continue}if(!i&&u===","){let l=c+1;for(;l<e.length&&(e[l]===" "||e[l]===" "||e[l]==="\r"||e[l]===`
|
|
160
|
+
`);)l++;if(e[l]==="}"||e[l]==="]")continue}s+=u}return s}function zn(t){for(let e of[t,Hi(t)])try{return JSON.parse(e)}catch{}}var Ui=X(()=>{"use strict"});var ro,TV,PV,Uv=X(()=>{"use strict";ro={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},TV=[ro.BEFORE,ro.AFTER],PV=[ro.COMPACTING]});var Zv={};De(Zv,{OpenCodeAdapter:()=>lh});import{readFileSync as Fv,writeFileSync as _z,mkdirSync as Sz,copyFileSync as xz,accessSync as kz,existsSync as bz,constants as vz}from"node:fs";import{resolve as Ct,join as Ln}from"node:path";import{homedir as fr}from"node:os";var lh,Bv=X(()=>{"use strict";et();Ui();Uv();lh=class extends ge{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},toolOutput:n.output,isError:void 0,sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let n={};return e.updatedOutput&&(n.output=e.updatedOutput),e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){if(this.settingsPath)return this.settingsPath;let e=Ct(`${this.platform}.jsonc`);return bz(e)?e:Ct(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Ct("kilo.jsonc"),Ct("kilo.json"),Ct(".kilo","kilo.jsonc"),Ct(".kilo","kilo.json"),Ct(".kilocode","kilo.jsonc"),Ct(".kilocode","kilo.json"),Ln(fr(),".config","kilo","kilo.jsonc"),Ln(fr(),".config","kilo","kilo.json")]:[Ct("opencode.jsonc"),Ct("opencode.json"),Ct(".opencode","opencode.jsonc"),Ct(".opencode","opencode.json"),Ln(fr(),".config","opencode","opencode.jsonc"),Ln(fr(),".config","opencode","opencode.json")]}getSessionDir(){let e=it(),n=e?Ln(e,"context-mode","sessions"):Ln(this.getConfigDir(),"context-mode","sessions");return Sz(n,{recursive:!0}),n}getConfigDir(e){let n;return process.platform==="win32"?n=process.env.APPDATA||Ln(fr(),"AppData","Roaming"):n=process.env.XDG_CONFIG_HOME||Ln(fr(),".config"),Ln(n,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[ro.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ro.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ro.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),n=new Set(e.filter(s=>s.includes(fr()))),r=null,o;for(let s of e)try{let i=Fv(s,"utf-8"),a=s.endsWith(".jsonc")?Hi(i):i,c=JSON.parse(a);r||(r=c,o=s);let u=n.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return r?(this.settingsPath=o,r):null}writeSettings(e){_z(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
161
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),n;let o=this.hasContextModePlugin(r);return Array.isArray(r.plugin)?n.push({check:"Plugin registration",status:o?"pass":"fail",message:o?"context-mode found in plugin array":"context-mode not found in plugin array",fix:o?void 0:"context-mode upgrade"}):n.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),this.hasLegacyContextModeMcp(r)&&n.push({check:"Legacy MCP registration",status:"warn",message:"mcp.context-mode is redundant: ctx_* tools are now provided by the plugin",fix:"context-mode upgrade (removes only mcp.context-mode; preserves other MCP servers)"}),n.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),n}checkPluginRegistration(){let e=this.readSettings();return e?this.hasContextModePlugin(e)?{check:"Plugin registration",status:"pass",message:"context-mode found in plugin array"}:{check:"Plugin registration",status:"fail",message:`context-mode not found in ${this.platform}.json plugin array`,fix:"context-mode upgrade"}:{check:"Plugin registration",status:"warn",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`}}getInstalledVersion(){try{let e=Ct(fr(),".cache",this.platform,"node_modules","context-mode","package.json"),n=JSON.parse(Fv(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[],o=n.plugin??[];o.some(i=>i.includes("context-mode"))?r.push("context-mode already in plugin array"):(o.push("context-mode"),r.push("Added context-mode to plugin array")),n.plugin=o;let s=n.mcp;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s;Object.prototype.hasOwnProperty.call(i,"context-mode")&&(delete i["context-mode"],r.push("Removed legacy context-mode MCP block (plugin-native tools)")),Object.keys(i).length===0&&delete n.mcp}return this.writeSettings(n),r}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{kz(this.settingsPath,vz.R_OK);let n=this.settingsPath+".bak";return xz(this.settingsPath,n),n}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}hasContextModePlugin(e){let n=e.plugin;return Array.isArray(n)&&n.some(r=>typeof r=="string"&&r.includes("context-mode"))}hasLegacyContextModeMcp(e){let n=e.mcp;return!!(n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var oo,DV,MV,qv=X(()=>{"use strict";oo={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},DV=[oo.TOOL_CALL_BEFORE,oo.TOOL_CALL_AFTER],MV=[oo.COMMAND_NEW]});var Vv={};De(Vv,{OpenClawAdapter:()=>mh});import{readFileSync as dh,writeFileSync as Ez,copyFileSync as wz,accessSync as Tz,constants as Pz}from"node:fs";import{resolve as Hn,join as ph}from"node:path";import{homedir as fh}from"node:os";var mh,Wv=X(()=>{"use strict";et();qv();mh=class extends ge{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},toolOutput:n.output??n.tool_output,isError:n.isError??n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Hn("openclaw.json")}getConfigDir(e){return Hn(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return ph(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[oo.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[oo.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[oo.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Hn("openclaw.json"),Hn(".openclaw","openclaw.json"),ph(fh(),".openclaw","openclaw.json")];for(let n of e)try{let r=dh(n,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let n=Hn("openclaw.json");Ez(n,JSON.stringify(e,null,2)+`
|
|
162
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),n;let o=r.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(n.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=s["context-mode"]?.enabled!==!1;n.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else n.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?n.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):n.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),n}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let r=e.plugins?.entries;return r&&Object.keys(r).some(s=>s.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in plugins.entries"}:{check:"Plugin registration",status:"fail",message:"context-mode not found in openclaw.json plugins.entries",fix:"context-mode upgrade"}}getInstalledVersion(){try{let e=Hn(fh(),".openclaw","extensions","context-mode","package.json"),n=JSON.parse(dh(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}try{let e=Hn("node_modules","context-mode","package.json"),n=JSON.parse(dh(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[];n.plugins||(n.plugins={});let o=n.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},r.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,r.push("Enabled context-mode plugin")):r.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&r.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",r.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(n),r}backupSettings(){let e=[Hn("openclaw.json"),Hn(".openclaw","openclaw.json"),ph(fh(),".openclaw","openclaw.json")];for(let n of e)try{Tz(n,Pz.R_OK);let r=n+".bak";return wz(n,r),r}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getProjectDir(e){return e.cwd??process.env.OPENCLAW_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.sessionId?e.sessionId:`pid-${process.ppid}`}}});import{homedir as Kv}from"node:os";import{resolve as hh}from"node:path";function Gv(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?hh(Kv(),t.replace(/^~[/\\]?/,"")):hh(t):hh(Kv(),".codex")}var Jv=X(()=>{"use strict"});var oE={};De(oE,{CodexAdapter:()=>_h,parseCodexContextModePluginRoot:()=>au,probeCodexCliVersion:()=>nE});import{execFileSync as tE}from"node:child_process";import{existsSync as Rz,readFileSync as as,writeFileSync as Xv,accessSync as Cz,copyFileSync as $z,constants as Oz,mkdirSync as gh}from"node:fs";import{resolve as iu,dirname as yh,join as Un}from"node:path";import{fileURLToPath as Iz}from"node:url";function nE(t=tE){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","codex --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("codex",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function au(t){for(let e of t.split(/\r?\n/)){let n=e.match(/^\s*context-mode@context-mode\s+installed,\s+enabled\s+\S+\s+(.+?)\s*$/);if(n?.[1])return n[1].trim()}return null}function cu(t,e){let n=t.split(/\r?\n/),r=!1,o=[];for(let s of n){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(r)break;r=i[1]?.trim()===e;continue}r&&o.push(s)}return r?o.join(`
|
|
163
|
+
`):null}function rE(t){let e=cu(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function Dz(t){let e=cu(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function Yv(t){let e=cu(t,'plugins."context-mode@context-mode"');return e!==null&&/^\s*enabled\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function Qv(t){return cu(t,"mcp_servers.context-mode")!==null}function Mz(t){if(rE(t))return{text:t,changed:!1};let e=t.includes(`\r
|
|
161
164
|
`)?`\r
|
|
162
165
|
`:`
|
|
163
|
-
`,
|
|
164
|
-
`)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=
|
|
166
|
+
`,n=t.split(/\r?\n/),r=n.findIndex(s=>/^\s*\[features\]\s*(?:#.*)?$/.test(s));if(r===-1){let s=t.length>0&&!t.endsWith(`
|
|
167
|
+
`)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=n.length;for(let s=r+1;s<n.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(n[s]??"")){o=s;break}for(let s=r+1;s<o;s++)if(/^\s*hooks\s*=/.test(n[s]??""))return n[s]="hooks = true",{text:n.join(e),changed:!0};return n.splice(r+1,0,"hooks = true"),{text:n.join(e),changed:!0}}function eE(t,e){let n=t.includes(`\r
|
|
165
168
|
`)?`\r
|
|
166
169
|
`:`
|
|
167
|
-
`,n=t.split(/\r?\n/),o=[],s=[],i=!1;for(let a of n){let c=a.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(c){let u=c[1]?.trim()??"";i=e(u),i&&s.push(u)}i||o.push(a)}return{text:o.join(r),removed:s}}function Dj(t){let e=t.trim();if(!e.startsWith('"')||!e.endsWith('"'))return null;try{let r=JSON.parse(e);return typeof r=="string"?r:null}catch{let r="",n=!1;for(let o of e.slice(1,-1))n?(r+=o==='"'||o==="\\"?o:`\\${o}`,n=!1):o==="\\"?n=!0:r+=o;return n&&(r+="\\"),r}}var Oj,ro,Ij,nh,Ok=ne(()=>{"use strict";st();Sr();Ek();Oj="local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",ro={PreToolUse:"context-mode hook codex pretooluse",PostToolUse:"context-mode hook codex posttooluse",SessionStart:"context-mode hook codex sessionstart",PreCompact:"context-mode hook codex precompact",UserPromptSubmit:"context-mode hook codex userpromptsubmit",Stop:"context-mode hook codex stop"},Ij={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"]};nh=class extends ge{constructor(){super([".codex"])}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return kk()}getSettingsPath(){return zr(this.getConfigDir(),"config.toml")}getSessionDir(){let e=St(),r=e?zr(e,"context-mode","sessions"):zr(this.getConfigDir(),"context-mode","sessions");return eh(r,{recursive:!0}),r}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let r=St(),n=r?zr(r,"context-mode","memories"):zr(this.getConfigDir(),"memories");return e?zr(n,Qe(e)):n}generateHookConfig(e){return{PreToolUse:[{matcher:Oj,hooks:[{type:"command",command:ro.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:ro.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:ro.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:ro.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:ro.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:ro.Stop}]}]}}readSettings(){try{return{_raw_toml:ss(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[],n=Rk(),o="",s=!1;r.push({check:"Codex CLI binary",status:n?"pass":"warn",message:n?`codex --version resolved to ${n}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...n?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{o=ss(this.getSettingsPath(),"utf-8"),s=!0;let f=$k(o),h=!f&&Aj(o);r.push({check:"Codex hooks feature flag",status:f?"pass":"fail",message:f?`[features].hooks enabled in ${this.getSettingsPath()}`:h?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...f?{}:{fix:"context-mode upgrade"}})}catch{r.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let i=this.generateHookConfig(""),a=s&&rh(o),c=a&&this.hasCodexPluginHookManifest(e);a&&!c&&r.push({check:"Codex plugin hooks",status:"fail",message:`context-mode Codex plugin is enabled, but ${zr(e,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"}),a&&Tk(o)&&r.push({check:"Standalone MCP duplicate",status:"warn",message:"[mcp_servers.context-mode] is still registered while context-mode@context-mode is enabled; Codex may start both plugin and standalone MCP surfaces",fix:"context-mode upgrade (removes the standalone Codex MCP registration when the plugin owns context-mode)"});let u=this.readHooksConfig();if(!u.ok){if(u.reason==="missing"&&c){let f=Object.keys(i).map(h=>({check:`${h} hook`,status:"pass",message:`${h} hook provided by context-mode@context-mode plugin`}));return r.concat(f)}return u.reason==="missing"?r.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):u.reason==="invalid_json"?r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${u.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):r.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${u.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}])}if(!u.config.hooks&&!c)return r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let l=c?Object.keys(i).map(f=>({check:`${f} hook`,status:"pass",message:`${f} hook provided by context-mode@context-mode plugin`})):Object.entries(i).map(([f,h])=>{let p=u.config.hooks?.[f],m=h[0],g=Array.isArray(p)&&p.some(_=>this.isExpectedHookEntry(f,_,m)),y=f==="PreCompact"?"warn":"fail";return{check:`${f} hook`,status:g?"pass":y,message:g?`${f} hook configured in ${this.getHooksPath()}`:f==="PreCompact"?`${f} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${f} hook missing or not pointing to context-mode`,fix:g?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),d=[];for(let f of Object.keys(i)){let h=u.config.hooks?.[f];if(!Array.isArray(h))continue;let p=h.filter(m=>this.isManagedContextModeEntry(f,m)).length;p>1?d.push({check:`${f} duplicates`,status:"warn",message:`${p} context-mode entries found for ${f} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"}):c&&p===1&&d.push({check:`${f} plugin duplicate`,status:"warn",message:`${f} is configured in both ${this.getHooksPath()} and the context-mode Codex plugin; Codex will fire both hooks`,fix:"context-mode upgrade (removes user config context-mode hooks; preserves unrelated hooks)"})}return r.concat(l,d)}checkPluginRegistration(){try{let e=ss(this.getSettingsPath(),"utf-8"),r=rh(e),n=Tk(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return r&&n?{check:"MCP registration",status:"warn",message:"context-mode@context-mode plugin is enabled, but standalone [mcp_servers.context-mode] is also configured",fix:"context-mode upgrade"}:r?{check:"MCP registration",status:"pass",message:"context-mode@context-mode plugin enabled"}:n?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:o?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let r=this.readHooksConfig(),n=[],o=this.getSettingsPath(),s="";try{s=ss(o,"utf-8")}catch{s=""}let i=rh(s)&&this.hasCodexPluginHookManifest(e),a;if(r.ok)a=r.config;else if(r.reason==="missing")a={hooks:{}};else if(r.reason==="invalid_json"){let h=this.backupFile(this.getHooksPath(),".broken");n.push(`Backed up malformed Codex hooks to ${h}`),a={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${r.error}`);let c=a.hooks&&typeof a.hooks=="object"&&!Array.isArray(a.hooks)?a.hooks:{},u=this.generateHookConfig(e),l=n.length;if(i)for(let h of Object.keys(u))this.removeManagedHookEntries(c,h,n);else for(let[h,p]of Object.entries(u))this.upsertManagedHookEntry(c,h,p[0],n);n.length>l&&(a.hooks=c,this.writeHooksConfig(a),n.push(i?`Removed duplicate context-mode user hooks from ${this.getHooksPath()}`:`Wrote native Codex hooks to ${this.getHooksPath()}`));let d=Nj(s).text,f=d!==s;if(i){let h=Pk(d,m=>m==="mcp_servers.context-mode"||m.startsWith("mcp_servers.context-mode.tools."));h.removed.length>0&&(d=h.text,n.push("Removed standalone Codex context-mode MCP registration"));let p=this.pruneStaleUserHookTrustState(d,c);p.removed.length>0&&(d=p.text,n.push(`Removed ${p.removed.length} stale Codex hook trust entr${p.removed.length===1?"y":"ies"}`))}if(d!==s){let h=d.includes(`\r
|
|
170
|
+
`,r=t.split(/\r?\n/),o=[],s=[],i=!1;for(let a of r){let c=a.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(c){let u=c[1]?.trim()??"";i=e(u),i&&s.push(u)}i||o.push(a)}return{text:o.join(n),removed:s}}function jz(t){let e=t.trim();if(!e.startsWith('"')||!e.endsWith('"'))return null;try{let n=JSON.parse(e);return typeof n=="string"?n:null}catch{let n="",r=!1;for(let o of e.slice(1,-1))r?(n+=o==='"'||o==="\\"?o:`\\${o}`,r=!1):o==="\\"?r=!0:n+=o;return r&&(n+="\\"),n}}var Az,so,Nz,_h,Sh=X(()=>{"use strict";et();kn();Jv();Az="local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",so={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"},Nz={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"]};_h=class extends ge{codexPluginListRunner;constructor(e={}){super([".codex"]),this.codexPluginListRunner=e.codexPluginListRunner??tE}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return Gv()}getSettingsPath(){return Un(this.getConfigDir(),"config.toml")}getSessionDir(){let e=it(),n=e?Un(e,"context-mode","sessions"):Un(this.getConfigDir(),"context-mode","sessions");return gh(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=it(),r=n?Un(n,"context-mode","memories"):Un(this.getConfigDir(),"memories");return e?Un(r,Qe(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:Az,hooks:[{type:"command",command:so.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:so.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:so.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:so.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:so.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:so.Stop}]}]}}readSettings(){try{return{_raw_toml:as(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=nE(),o="",s=!1;n.push({check:"Codex CLI binary",status:r?"pass":"warn",message:r?`codex --version resolved to ${r}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...r?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{o=as(this.getSettingsPath(),"utf-8"),s=!0;let m=rE(o),p=!m&&Dz(o);n.push({check:"Codex hooks feature flag",status:m?"pass":"fail",message:m?`[features].hooks enabled in ${this.getSettingsPath()}`:p?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...m?{}:{fix:"context-mode upgrade"}})}catch{n.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let i=this.generateHookConfig(""),a=this.getCodexPluginHookStatus(e,o,s),c=a.enabled,u=a.hooksAvailable;if(c&&a.runtimeRoot?n.push({check:"Codex plugin root",status:a.rootMismatch?"warn":"pass",message:a.rootMismatch?`context-mode doctor is running from ${a.configuredRoot}, but Codex plugin manager reports ${a.runtimeRoot}`:`Codex plugin manager reports ${a.runtimeRoot}`,...a.rootMismatch?{fix:"Restart Codex after upgrade; run context-mode upgrade to keep native user-hook fallback until the plugin root converges"}:{}}):c&&n.push({check:"Codex plugin root",status:"warn",message:"context-mode@context-mode is enabled, but `codex plugin list` did not report its runtime root",fix:"Restart Codex or verify `codex plugin list` shows context-mode@context-mode installed and enabled"}),c&&!u){let m=a.runtimeRoot??e;n.push({check:"Codex plugin hooks",status:"fail",message:`context-mode Codex plugin is enabled, but ${Un(m,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"})}c&&Qv(o)&&n.push({check:"Standalone MCP duplicate",status:"warn",message:"[mcp_servers.context-mode] is still registered while context-mode@context-mode is enabled; Codex may start both plugin and standalone MCP surfaces",fix:"context-mode upgrade (removes the standalone Codex MCP registration when the plugin owns context-mode)"});let l=this.readHooksConfig();if(!l.ok){if(l.reason==="missing"&&u){let m=Object.keys(i).map(p=>({check:`${p} hook`,status:"pass",message:`${p} hook provided by context-mode@context-mode plugin`}));return n.concat(m)}return l.reason==="missing"?n.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):l.reason==="invalid_json"?n.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${l.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):n.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${l.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}])}if(!l.config.hooks&&!u)return n.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let d=u?Object.keys(i).map(m=>({check:`${m} hook`,status:"pass",message:`${m} hook provided by context-mode@context-mode plugin`})):Object.entries(i).map(([m,p])=>{let h=l.config.hooks?.[m],g=p[0],y=Array.isArray(h)&&h.some(S=>this.isExpectedHookEntry(m,S,g)),_=m==="PreCompact"?"warn":"fail";return{check:`${m} hook`,status:y?"pass":_,message:y?`${m} hook configured in ${this.getHooksPath()}`:m==="PreCompact"?`${m} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${m} hook missing or not pointing to context-mode`,fix:y?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),f=[];for(let m of Object.keys(i)){let p=l.config.hooks?.[m];if(!Array.isArray(p))continue;let h=p.filter(g=>this.isManagedContextModeEntry(m,g)).length;h>1?f.push({check:`${m} duplicates`,status:"warn",message:`${h} context-mode entries found for ${m} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"}):u&&h===1&&f.push({check:`${m} plugin duplicate`,status:"warn",message:`${m} is configured in both ${this.getHooksPath()} and the context-mode Codex plugin; Codex will fire both hooks`,fix:"context-mode upgrade (removes user config context-mode hooks; preserves unrelated hooks)"})}return n.concat(d,f)}checkPluginRegistration(){try{let e=as(this.getSettingsPath(),"utf-8"),n=Yv(e),r=Qv(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return n&&r?{check:"MCP registration",status:"warn",message:"context-mode@context-mode plugin is enabled, but standalone [mcp_servers.context-mode] is also configured",fix:"context-mode upgrade"}:n?{check:"MCP registration",status:"pass",message:"context-mode@context-mode plugin enabled"}:r?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:o?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let n=this.readHooksConfig(),r=[],o=this.getSettingsPath(),s="";try{s=as(o,"utf-8")}catch{s=""}let a=this.getCodexPluginHookStatus(e,s,s.length>0).ownsHooksForUpgrade,c;if(n.ok)c=n.config;else if(n.reason==="missing")c={hooks:{}};else if(n.reason==="invalid_json"){let p=this.backupFile(this.getHooksPath(),".broken");r.push(`Backed up malformed Codex hooks to ${p}`),c={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${n.error}`);let u=c.hooks&&typeof c.hooks=="object"&&!Array.isArray(c.hooks)?c.hooks:{},l=this.generateHookConfig(e),d=r.length;if(a)for(let p of Object.keys(l))this.removeManagedHookEntries(u,p,r);else for(let[p,h]of Object.entries(l))this.upsertManagedHookEntry(u,p,h[0],r);r.length>d&&(c.hooks=u,this.writeHooksConfig(c),r.push(a?`Removed duplicate context-mode user hooks from ${this.getHooksPath()}`:`Wrote native Codex hooks to ${this.getHooksPath()}`));let f=Mz(s).text,m=f!==s;if(a){let p=eE(f,g=>g==="mcp_servers.context-mode"||g.startsWith("mcp_servers.context-mode.tools."));p.removed.length>0&&(f=p.text,r.push("Removed standalone Codex context-mode MCP registration"));let h=this.pruneStaleUserHookTrustState(f,u);h.removed.length>0&&(f=h.text,r.push(`Removed ${h.removed.length} stale Codex hook trust entr${h.removed.length===1?"y":"ies"}`))}if(f!==s){let p=f.includes(`\r
|
|
168
171
|
`)?`\r
|
|
169
172
|
`:`
|
|
170
|
-
`,
|
|
171
|
-
`)?
|
|
173
|
+
`,h=f.endsWith(`
|
|
174
|
+
`)?f:`${f}${p}`;gh(yh(o),{recursive:!0}),Xv(o,h,"utf-8"),m&&r.push("Enabled Codex hooks feature flag")}return r}backupSettings(){let e=null;for(let n of[this.getHooksPath(),this.getSettingsPath()])try{Cz(n,Oz.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=iu(yh(Iz(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return as(e,"utf-8")}catch{return`# context-mode
|
|
172
175
|
|
|
173
|
-
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
|
|
174
|
-
`,"utf-8")}upsertManagedHookEntry(e,r,
|
|
175
|
-
`,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},o=n.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=o,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=Uj(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=tu(n,o);try{zj(s,Hj.R_OK),Lj(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}}});function Ak(t,e){if(!sh[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Zt,sh,C9,O9,Nk=ne(()=>{"use strict";Zt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},sh={[Zt.PRE_TOOL_USE]:"pretooluse.mjs",[Zt.POST_TOOL_USE]:"posttooluse.mjs",[Zt.PRE_COMPACT]:"precompact.mjs",[Zt.SESSION_START]:"sessionstart.mjs"},C9=[Zt.PRE_TOOL_USE,Zt.SESSION_START],O9=[Zt.POST_TOOL_USE,Zt.PRE_COMPACT]});var Mk={};He(Mk,{VSCodeCopilotAdapter:()=>ch});import{readFileSync as ih,mkdirSync as Dk,accessSync as Fj,existsSync as Zj,constants as qj}from"node:fs";import{resolve as as,join as ji}from"node:path";import{homedir as ah}from"node:os";var ch,jk=ne(()=>{"use strict";oh();st();Nk();ch=class extends is{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Zt,HOOK_SCRIPTS:sh,buildHookCommand:Ak};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.env.VSCODE_CWD||process.cwd()}getSessionDir(){let e=St();if(e){let s=ji(e,"context-mode","sessions");return Dk(s,{recursive:!0}),s}let r=as(".github","context-mode","sessions"),n=ji(ah(),".vscode","context-mode","sessions"),o=Zj(as(".github"))?r:n;return Dk(o,{recursive:!0}),o}getConfigDir(e){return as(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=as(".github","hooks");try{Fj(n,qj.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let o=as(n,"context-mode.json");try{let s=ih(o,"utf-8"),a=JSON.parse(s).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=as(".vscode","mcp.json"),r=ih(e,"utf-8"),o=JSON.parse(r).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[ji(ah(),".vscode","extensions"),ji(ah(),".vscode-insiders","extensions")];for(let r of e)try{let n=ih(ji(r,"extensions.json"),"utf-8"),s=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function zk(t,e){if(!uh[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var qt,uh,L9,H9,Lk=ne(()=>{"use strict";qt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},uh={[qt.PRE_TOOL_USE]:"pretooluse.mjs",[qt.POST_TOOL_USE]:"posttooluse.mjs",[qt.PRE_COMPACT]:"precompact.mjs",[qt.SESSION_START]:"sessionstart.mjs"},L9=[qt.PRE_TOOL_USE,qt.SESSION_START],H9=[qt.POST_TOOL_USE,qt.PRE_COMPACT]});var Hk={};He(Hk,{JetBrainsCopilotAdapter:()=>lh});import{readFileSync as Bj}from"node:fs";import{resolve as Vj}from"node:path";var lh,Uk=ne(()=>{"use strict";oh();Lk();lh=class extends is{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:qt,HOOK_SCRIPTS:uh,buildHookCommand:zk};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 Vj(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=Bj(this.getSettingsPath(),"utf-8"),s=JSON.parse(n).hooks;s?.[qt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[qt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),r}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let r=this.readSettings()?.hooks;return r&&Object.keys(r).length>0?"configured":"unknown"}}});function zi(t,e){let r=dh[e],n=Bt(e);if("command"in t){let s=t.command??"";return r!=null&&s.includes(r)||s.includes(n)}return t.hooks?.some(s=>{let i=s.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function Bt(t){return`context-mode hook cursor ${t.toLowerCase()}`}var ye,dh,Wj,Kj,ph,Fk,Zk,qk=ne(()=>{"use strict";ye={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},dh={[ye.PRE_TOOL_USE]:"pretooluse.mjs",[ye.POST_TOOL_USE]:"posttooluse.mjs",[ye.SESSION_START]:"sessionstart.mjs",[ye.STOP]:"stop.mjs",[ye.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},Wj="MCP:(?!ctx_)",Kj=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",Wj],ph=Kj.join("|"),Fk=[ye.PRE_TOOL_USE],Zk=[ye.POST_TOOL_USE]});var Gk={};He(Gk,{CursorAdapter:()=>fh});import{readFileSync as ru,writeFileSync as Gj,mkdirSync as Jj,accessSync as Bk,chmodSync as Xj,constants as Vk,existsSync as Wk,readdirSync as Yj}from"node:fs";import{execSync as Qj}from"node:child_process";import{resolve as no,join as oo}from"node:path";import{homedir as nu}from"node:os";var Kk,fh,Jk=ne(()=>{"use strict";st();Yn();qk();Kk="/Library/Application Support/Cursor/hooks.json",fh=class extends ge{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return no(".cursor","hooks.json")}getConfigDir(e){return no(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[ye.PRE_TOOL_USE]:[{type:"command",command:Bt(ye.PRE_TOOL_USE),matcher:ph,loop_limit:null,failClosed:!1}],[ye.POST_TOOL_USE]:[{type:"command",command:Bt(ye.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[ye.SESSION_START]:[{type:"command",command:Bt(ye.SESSION_START),loop_limit:null,failClosed:!1}],[ye.STOP]:[{type:"command",command:Bt(ye.STOP),loop_limit:null,failClosed:!1}],[ye.AFTER_AGENT_RESPONSE]:[{type:"command",command:Bt(ye.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=ru(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();Jj(no(".cursor"),{recursive:!0}),Gj(r,JSON.stringify(e,null,2)+`
|
|
176
|
-
`,"utf-8")}
|
|
176
|
+
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 Un(this.getConfigDir(),"hooks.json")}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return $z(e,r),r}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(as(e,"utf-8"))}}catch(n){let r=n instanceof Error?n.message:String(n);return(typeof n=="object"&&n!==null&&"code"in n?String(n.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:n instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:r}:{ok:!1,reason:"read_error",error:r}}}writeHooksConfig(e){let n=this.getHooksPath();gh(yh(n),{recursive:!0}),Xv(n,JSON.stringify(e,null,2)+`
|
|
177
|
+
`,"utf-8")}upsertManagedHookEntry(e,n,r,o){let s=Array.isArray(e[n])?[...e[n]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(n,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(r),e[n]=s,o.push(`Added ${n} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(r)&&(s[a]=r,o.push(`Updated ${n} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${n} context-mode hook`);e[n]=s}removeManagedHookEntries(e,n,r){let o=Array.isArray(e[n])?[...e[n]]:[],s=o.filter(a=>!this.isManagedContextModeEntry(n,a)),i=o.length-s.length;i!==0&&(s.length>0?e[n]=s:delete e[n],r.push(`Removed ${i} ${n} context-mode user hook${i===1?"":"s"}`))}hasCodexPluginHookManifest(e){return Rz(Un(e,".codex-plugin","hooks.json"))}getCodexPluginHookStatus(e,n,r){let o=r&&Yv(n),s=iu(e),i=this.hasCodexPluginHookManifest(s),a=o?this.probeCodexContextModePluginRoot():null,c=a?this.hasCodexPluginHookManifest(a):!1,u=a?!this.samePath(s,a):!1;return{enabled:o,configuredRoot:s,configuredManifestAvailable:i,runtimeRoot:a,runtimeManifestAvailable:c,rootMismatch:u,hooksAvailable:o&&(c||!a&&i),ownsHooksForUpgrade:o&&a!==null&&c&&!u}}probeCodexContextModePluginRoot(){try{let e=process.platform==="win32"?this.codexPluginListRunner("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):this.codexPluginListRunner("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});return au(String(e))}catch{return null}}samePath(e,n){return this.normalizeCommand(iu(e))===this.normalizeCommand(iu(n))}pruneStaleUserHookTrustState(e,n){let r=this.normalizeCommand(this.getHooksPath()),o={post_compact:"PostCompact",post_tool_use:"PostToolUse",pre_compact:"PreCompact",pre_tool_use:"PreToolUse",session_start:"SessionStart",stop:"Stop",user_prompt_submit:"UserPromptSubmit"};return eE(e,s=>{let i="hooks.state.";if(!s.startsWith(i))return!1;let a=jz(s.slice(i.length));if(a===null)return!1;let u=this.normalizeCommand(a).split(":"),l=Number(u.pop()),d=Number(u.pop()),f=o[u.pop()??""];if(u.join(":")!==r||!f||!Number.isInteger(d)||!Number.isInteger(l))return!1;let p=n[f]?.[d];return!p||!Array.isArray(p.hooks)||!p.hooks[l]})}isExpectedHookEntry(e,n,r){return!n||typeof n!="object"||e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}isManagedContextModeEntry(e,n){return!n||typeof n!="object"?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(Array.isArray(n.hooks)?n.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(so[e]??""),s=Nz[e]??[];return r.some(i=>i.includes(o)||s.some(a=>i.includes(a)))}normalizeCommand(e){return(e??"").replace(/\\/g,"/")}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});import{readFileSync as sE,writeFileSync as zz,mkdirSync as Lz,accessSync as Hz,chmodSync as Uz,constants as Fz}from"node:fs";import{resolve as uu,join as Zz}from"node:path";var mr,lu=X(()=>{"use strict";et();mr=class extends ge{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,updatedInput:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,additionalContext:e.additionalContext}};if(e.decision==="ask")return{permissionDecision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,decision:"block",reason:e.updatedOutput}};if(e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(e){return uu(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule;return{[n.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_TOOL_USE,e)}]}],[n.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.POST_TOOL_USE,e)}]}],[n.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_COMPACT,e)}]}],[n.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:r(n.SESSION_START,e)}]}]}}readSettings(){try{let e=sE(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=sE(uu(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();Lz(uu(".github","hooks"),{recursive:!0}),zz(n,JSON.stringify(e,null,2)+`
|
|
178
|
+
`,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],n.push(`Configured ${u} hook`));return r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`),n}setHookPermissions(e){let n=[],r=Zz(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=uu(r,o);try{Hz(s,Fz.R_OK),Uz(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function iE(t,e){if(!xh[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Bt,xh,rW,oW,aE=X(()=>{"use strict";Bt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},xh={[Bt.PRE_TOOL_USE]:"pretooluse.mjs",[Bt.POST_TOOL_USE]:"posttooluse.mjs",[Bt.PRE_COMPACT]:"precompact.mjs",[Bt.SESSION_START]:"sessionstart.mjs"},rW=[Bt.PRE_TOOL_USE,Bt.SESSION_START],oW=[Bt.POST_TOOL_USE,Bt.PRE_COMPACT]});var uE={};De(uE,{VSCodeCopilotAdapter:()=>vh});import{readFileSync as kh,mkdirSync as cE,accessSync as Bz,existsSync as qz,constants as Vz}from"node:fs";import{resolve as cs,join as Fi}from"node:path";import{homedir as bh}from"node:os";var vh,lE=X(()=>{"use strict";lu();et();aE();vh=class extends mr{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Bt,HOOK_SCRIPTS:xh,buildHookCommand:iE};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.env.VSCODE_CWD||process.cwd()}getSessionDir(){let e=it();if(e){let s=Fi(e,"context-mode","sessions");return cE(s,{recursive:!0}),s}let n=cs(".github","context-mode","sessions"),r=Fi(bh(),".vscode","context-mode","sessions"),o=qz(cs(".github"))?n:r;return cE(o,{recursive:!0}),o}getConfigDir(e){return cs(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=cs(".github","hooks");try{Bz(r,Vz.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=cs(r,"context-mode.json");try{let s=kh(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Bt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Bt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),n.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),n}checkPluginRegistration(){try{let e=cs(".vscode","mcp.json"),n=kh(e,"utf-8"),o=JSON.parse(n).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[Fi(bh(),".vscode","extensions"),Fi(bh(),".vscode-insiders","extensions")];for(let n of e)try{let r=kh(Fi(n,"extensions.json"),"utf-8"),s=JSON.parse(r).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function dE(t,e){if(!Eh[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var qt,Eh,pW,fW,pE=X(()=>{"use strict";qt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Eh={[qt.PRE_TOOL_USE]:"pretooluse.mjs",[qt.POST_TOOL_USE]:"posttooluse.mjs",[qt.PRE_COMPACT]:"precompact.mjs",[qt.SESSION_START]:"sessionstart.mjs"},pW=[qt.PRE_TOOL_USE,qt.SESSION_START],fW=[qt.POST_TOOL_USE,qt.PRE_COMPACT]});var fE={};De(fE,{JetBrainsCopilotAdapter:()=>wh});import{readFileSync as Wz}from"node:fs";import{resolve as Kz}from"node:path";var wh,mE=X(()=>{"use strict";lu();pE();wh=class extends mr{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:qt,HOOK_SCRIPTS:Eh,buildHookCommand:dE};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 Kz(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=Wz(this.getSettingsPath(),"utf-8"),s=JSON.parse(r).hooks;s?.[qt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[qt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),n}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let n=this.readSettings()?.hooks;return n&&Object.keys(n).length>0?"configured":"unknown"}}});function hE(t,e){let n=Th[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var dt,Th,xW,kW,gE=X(()=>{"use strict";dt={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},Th={[dt.PRE_TOOL_USE]:"pretooluse.mjs",[dt.POST_TOOL_USE]:"posttooluse.mjs",[dt.PRE_COMPACT]:"precompact.mjs",[dt.SESSION_START]:"sessionstart.mjs",[dt.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[dt.STOP]:"stop.mjs"},xW=[dt.PRE_TOOL_USE,dt.SESSION_START],kW=[dt.POST_TOOL_USE,dt.PRE_COMPACT,dt.USER_PROMPT_SUBMIT,dt.STOP]});var bE={};De(bE,{CopilotCliAdapter:()=>Rh,copilotCliHome:()=>pu,copilotCliMcpConfigPath:()=>du});import{existsSync as yE,mkdirSync as _E,readFileSync as Ph,writeFileSync as Gz}from"node:fs";import{homedir as SE}from"node:os";import{dirname as Jz,join as us,resolve as kE}from"node:path";function xE(){return process.env[Xz]==="1"}function Yz(t){return kE(t,"configs","copilot-cli","hooks.json")}function Qz(t){return zn(Ph(t,"utf-8"))??{}}function eL(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function pu(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?us(SE(),t.replace(/^~[/\\]?/,"")):kE(t):us(SE(),".copilot")}function du(){return us(pu(),"mcp-config.json")}var Xz,Rh,vE=X(()=>{"use strict";lu();et();Ui();gE();Xz="CONTEXT_MODE_COPILOT_PLUGIN";Rh=class extends mr{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:dt,HOOK_SCRIPTS:Th,buildHookCommand:hE};hookSubdir="copilot-cli";extractSessionId(e){let n=e;if(n.transcript_path){let r=n.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return n.conversation_id?n.conversation_id:n.session_id?n.session_id:e.sessionId?e.sessionId:`pid-${process.ppid}`}getProjectDir(){return process.cwd()}parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_result?.text_result_for_llm??n.toolResult?.textResultForLlm??(typeof n.tool_response=="string"?n.tool_response:void 0)??n.tool_output;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},toolOutput:r,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}getSettingsPath(e){return us(pu(),"hooks","context-mode.json")}getConfigDir(e){return pu()}getSessionDir(){let e=it(),n=e?us(e,"context-mode","sessions"):us(this.getConfigDir(),"context-mode","sessions");return _E(n,{recursive:!0}),n}getInstructionFiles(){return[".github/copilot-instructions.md","AGENTS.md"]}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule,o=i=>[{type:"command",command:r(i,e)}],s={};for(let i of Object.values(n))s[i]=o(i);return s}writeSettings(e){let n=this.getSettingsPath();_E(Jz(n),{recursive:!0}),Gz(n,JSON.stringify(e,null,2)+`
|
|
179
|
+
`,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule;for(let c of Object.values(s)){if(!i[c])continue;let u=[{type:"command",command:a(c,e)}];JSON.stringify(o[c])!==JSON.stringify(u)&&(o[c]=u,n.push(`Configured ${c} hook`))}return r.version!==1&&n.push("Set hooks schema version to 1"),n.length>0&&(r.version=1,r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`)),n}readSettings(){try{let e=Ph(this.getSettingsPath(),"utf-8");return zn(e)??null}catch{return null}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="ask")return{permissionDecision:"ask",permissionDecisionReason:e.reason??"Action requires user confirmation"};if(e.decision==="modify"&&e.updatedInput)return{modifiedArgs:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext}}formatPostToolUseResponse(e){if(e.updatedOutput)return{modifiedResult:{resultType:"success",textResultForLlm:e.updatedOutput}};if(e.additionalContext)return{additionalContext:e.additionalContext}}formatPreCompactResponse(e){}formatSessionStartResponse(e){return e.context?{additionalContext:e.context}:void 0}validateHooks(e){let n=[],r=xE(),o=r?Yz(e):this.getSettingsPath(),s=r?`Copilot CLI plugin bundle hooks.json (${o})`:o,i=r?"copilot plugin install mksglu/context-mode:configs/copilot-cli":"context-mode upgrade";try{let a=Qz(o),c=a.hooks;n.push({check:"Hooks schema version",status:a.version===1?"pass":"fail",message:a.version===1?`${s} declares the required "version": 1`:`${s} is missing top-level "version": 1`,...a.version===1?{}:{fix:i}});for(let u of Object.values(dt)){let l=eL(c,u);n.push({check:`${u} hook`,status:l?"pass":"fail",message:l?`${u} hook configured in ${s}`:`${u} not found in ${s}`,...l?{}:{fix:i}})}}catch{n.push({check:"Hook configuration",status:"fail",message:`Could not read ${s}`,fix:i})}return n}checkPluginRegistration(){if(xE())return{check:"MCP registration",status:"pass",message:"context-mode loaded from the Copilot CLI plugin bundle"};try{let e=Ph(du(),"utf-8");return"context-mode"in((zn(e)??{})?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in Copilot CLI mcp-config.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in Copilot CLI mcpServers",fix:"copilot mcp add context-mode -- context-mode"}}catch{return{check:"MCP registration",status:"fail",message:`Could not read ${du()}`,fix:"copilot mcp add context-mode -- context-mode"}}}getInstalledVersion(){return yE(du())||yE(this.getSettingsPath())?"standalone":"not installed"}}});function Zi(t,e){let n=Ch[e],r=Vt(e);if("command"in t){let s=t.command??"";return n!=null&&s.includes(n)||s.includes(r)}return t.hooks?.some(s=>{let i=s.command??"";return n!=null&&i.includes(n)||i.includes(r)})??!1}function Vt(t){return`context-mode hook cursor ${t.toLowerCase()}`}var ye,Ch,tL,nL,$h,EE,wE,TE=X(()=>{"use strict";ye={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Ch={[ye.PRE_TOOL_USE]:"pretooluse.mjs",[ye.POST_TOOL_USE]:"posttooluse.mjs",[ye.SESSION_START]:"sessionstart.mjs",[ye.STOP]:"stop.mjs",[ye.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},tL="MCP:(?!ctx_)",nL=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",tL],$h=nL.join("|"),EE=[ye.PRE_TOOL_USE],wE=[ye.POST_TOOL_USE]});var OE={};De(OE,{CursorAdapter:()=>Oh});import{readFileSync as fu,writeFileSync as rL,mkdirSync as oL,accessSync as PE,chmodSync as sL,constants as RE,existsSync as CE,readdirSync as iL}from"node:fs";import{execSync as aL}from"node:child_process";import{resolve as io,join as ao}from"node:path";import{homedir as mu}from"node:os";var $E,Oh,IE=X(()=>{"use strict";et();to();TE();$E="/Library/Application Support/Cursor/hooks.json",Oh=class extends ge{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output??n.error_message,isError:!!n.error_message,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??n.trigger??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let n=e;return{sessionId:n.conversation_id??`pid-${process.ppid}`,status:n.status??"completed",loopCount:n.loop_count??0,generationId:n.generation_id,transcriptPath:n.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return io(".cursor","hooks.json")}getConfigDir(e){return io(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[ye.PRE_TOOL_USE]:[{type:"command",command:Vt(ye.PRE_TOOL_USE),matcher:$h,loop_limit:null,failClosed:!1}],[ye.POST_TOOL_USE]:[{type:"command",command:Vt(ye.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[ye.SESSION_START]:[{type:"command",command:Vt(ye.SESSION_START),loop_limit:null,failClosed:!1}],[ye.STOP]:[{type:"command",command:Vt(ye.STOP),loop_limit:null,failClosed:!1}],[ye.AFTER_AGENT_RESPONSE]:[{type:"command",command:Vt(ye.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let n=fu(e,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let n=this.getSettingsPath();oL(io(".cursor"),{recursive:!0}),rL(n,JSON.stringify(e,null,2)+`
|
|
180
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.loadNativeHookConfig();if(!r)n.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let s=r.config.hooks??{};n.push({check:"Native hook config",status:"pass",message:`Loaded ${r.path}`});for(let i of EE){let a=s[i],c=Array.isArray(a)&&a.some(u=>Zi(u,i));n.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${r.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of wE){let a=s[i],c=Array.isArray(a)&&a.some(u=>Zi(u,i));n.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}CE($E)&&n.push({check:"Enterprise hook config",status:"warn",message:"Enterprise Cursor hook config detected at /Library/Application Support/Cursor/hooks.json (read-only informational layer)"}),this.hasClaudeCompatibilityHooks()&&n.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let o=this.detectPluginInstalls();return o.length>0&&((r?Object.entries(r.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>Zi(c,i))):!1)&&r?n.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${r.path} \u2014 each event will fire twice. Remove one configuration to avoid duplicate routing.`,fix:"Remove the native .cursor/hooks.json entries OR uninstall the plugin"}):n.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),n}detectPluginInstalls(){let e=[ao(mu(),".cursor","plugins","local"),ao(mu(),".cursor","plugins","cache")],n=[];for(let r of e){try{PE(r,RE.F_OK)}catch{continue}let o=[];try{o=iL(r)}catch{continue}for(let s of o){let i=ao(r,s,".cursor-plugin","plugin.json");try{let a=fu(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&n.push(i)}catch{continue}}}return n}checkPluginRegistration(){let e=[io(".cursor","mcp.json"),ao(mu(),".cursor","mcp.json")];for(let r of e)try{let o=fu(r,"utf-8"),s=JSON.parse(o),i=s.mcpServers??s.servers;if(!i)continue;if(Object.entries(i).some(([c,u])=>c.includes("context-mode")?!0:!u||typeof u!="object"?!1:u.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${r}`}}catch{continue}let n=this.detectPluginInstalls();return n.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${n[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return aL("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=this.readSettings()??{version:1,hooks:{}},r=n.hooks??{},o=[];return this.upsertHookEntry(r,ye.PRE_TOOL_USE,{type:"command",command:Vt(ye.PRE_TOOL_USE),matcher:$h,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ye.POST_TOOL_USE,{type:"command",command:Vt(ye.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ye.SESSION_START,{type:"command",command:Vt(ye.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ye.STOP,{type:"command",command:Vt(ye.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ye.AFTER_AGENT_RESPONSE,{type:"command",command:Vt(ye.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),n.version=1,n.hooks=r,this.writeSettings(n),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let n=[],r=ao(e,"hooks","cursor");for(let o of Object.values(Ch)){let s=io(r,o);try{PE(s,RE.R_OK),sL(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),ao(mu(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push($E),e}getProjectDir(e){return e.cwd||e.workspace_roots?.[0]||process.env.CURSOR_CWD||process.cwd()}extractSessionId(e){return e.conversation_id?e.conversation_id:e.session_id?e.session_id:process.env.CURSOR_SESSION_ID?process.env.CURSOR_SESSION_ID:process.env.CURSOR_TRACE_ID?process.env.CURSOR_TRACE_ID:`pid-${process.ppid}`}loadNativeHookConfig(){for(let e of this.getCandidateHookConfigPaths())try{let n=fu(e,"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object")return{path:e,config:r}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[io(".claude","settings.json"),io(".claude","settings.local.json"),ao(Rt(),"settings.json")].some(n=>CE(n))}upsertHookEntry(e,n,r,o){let s=e[n],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>Zi(c,n));a>=0?(i[a]=r,o.push(`Updated existing ${n} hook entry`)):(i.push(r),o.push(`Added ${n} hook entry`)),e[n]=i}}});var NE={};De(NE,{AntigravityAdapter:()=>Bi});import{readFileSync as hu,writeFileSync as cL,mkdirSync as uL}from"node:fs";import{resolve as gu,dirname as AE}from"node:path";import{fileURLToPath as lL}from"node:url";import{homedir as Ih}from"node:os";var Bi,Ah=X(()=>{"use strict";et();Bi=class extends ge{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 gu(Ih(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return gu(Ih(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=hu(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();uL(AE(n),{recursive:!0}),cL(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Antigravity does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=hu(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=gu(Ih(),".gemini","extensions","context-mode","package.json");return JSON.parse(hu(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=gu(AE(lL(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return hu(e,"utf-8")}catch{return`# context-mode
|
|
177
181
|
|
|
178
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});
|
|
182
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});var ZE={};De(ZE,{AntigravityCliAdapter:()=>Lh,antigravityCliConfigDir:()=>UE,antigravityCliHooksPath:()=>Dh,antigravityCliMcpConfigPath:()=>HE,antigravityCliPluginDir:()=>Su});import{mkdirSync as dL,readFileSync as yu,writeFileSync as pL}from"node:fs";import{dirname as fL,resolve as co}from"node:path";import{homedir as _u}from"node:os";function HE(){return co(_u(),".gemini","config","mcp_config.json")}function UE(){return co(_u(),".gemini","antigravity-cli")}function Dh(){return co(_u(),".gemini","config","hooks.json")}function Su(){return co(_u(),".gemini","config","plugins","context-mode")}function mL(){return co(Su(),"mcp_config.json")}function hL(){return co(Su(),"hooks.json")}function DE(t){for(let e of t)try{if("context-mode"in((zn(yu(e,"utf-8"))??{})?.mcpServers??{}))return{ok:!0,where:e}}catch{}return{ok:!1}}function bn(t){return t&&typeof t=="object"?t:{}}function ME(t){let e=bn(t.workspace);if(typeof e.current_dir=="string"&&e.current_dir)return e.current_dir;let n=t.workspacePaths;return Array.isArray(n)&&n.length>0?String(n[0]):void 0}function jE(t){return typeof t.conversationId=="string"&&t.conversationId?t.conversationId:`pid-${process.ppid}`}function FE(t,e){let n=bn(t);return(Array.isArray(n.hooks)?n.hooks:[]).some(o=>bn(o).command===e)}function zE(t,e){return JSON.stringify(t).includes(e)}function gL(t){return typeof t!="string"?!1:["run_command","view_file","grep_search","web_fetch","read_url_content"].every(e=>t.includes(e))}function LE(t,e){return Array.isArray(t)&&t.some(n=>FE(n,e))}function yL(t){return Array.isArray(t)&&t.some(e=>{let n=bn(e);return gL(n.matcher)&&FE(e,Mh)})}function _L(t){let e={preOk:!1,postOk:!1,stopOk:!1,where:void 0};for(let n of t)try{let o=(zn(yu(n,"utf-8"))??{}).hooks??{},s=yL(o.PreToolUse),i=LE(o.PostToolUse,jh),a=LE(o.Stop,zh);(s||i||a)&&!e.where&&(e.where=n),e.preOk||=s,e.postOk||=i,e.stopOk||=a}catch{}return{...e,ok:e.preOk&&e.postOk}}function xL(t){let e=String(t??"").replace(/<\/?context_guidance>/g," ").replace(/<\/?tip>/g," ").replace(/\s+/g," ").trim();return e?`context-mode: use the context-mode MCP tools instead of this native tool. ${e}`:"context-mode: use the context-mode MCP tools instead of this native tool so raw bytes stay out of the conversation."}function Nh(t,e,n,r){let o=Array.isArray(t[e])?t[e]:[],s=JSON.stringify(n);return o.some(a=>JSON.stringify(a)===s)&&o.every(a=>!zE(a,r)||JSON.stringify(a)===s)?!1:(t[e]=[...o.filter(a=>!zE(a,r)),n],!0)}var Mh,SL,jh,zh,Lh,BE=X(()=>{"use strict";Ah();Ui();Mh="context-mode hook antigravity-cli pretooluse",SL="run_command|view_file|grep_search|web_fetch|read_url_content",jh="context-mode hook antigravity-cli posttooluse",zh="context-mode hook antigravity-cli stop";Lh=class extends Bi{name="Antigravity CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};getSettingsPath(){return HE()}getConfigDir(e){return UE()}parsePreToolUseInput(e){let n=bn(e),r=bn(n.toolCall);return{toolName:typeof r.name=="string"?r.name:"",toolInput:bn(r.args),sessionId:jE(n),projectDir:ME(n),raw:e}}parsePostToolUseInput(e){let n=bn(e),r=bn(n.toolCall),o=typeof n.error=="string"?n.error:"";return{toolName:typeof r.name=="string"?r.name:"",toolInput:bn(r.args),toolOutput:o,isError:o.length>0,sessionId:jE(n),projectDir:ME(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{decision:"deny",reason:e.reason??"Denied by context-mode"}:e.decision==="ask"?{decision:"ask",reason:e.reason??"Action requires user confirmation"}:e.decision==="context"&&e.additionalContext?{decision:"deny",reason:xL(e.additionalContext)}:null}formatPostToolUseResponse(e){}checkPluginRegistration(){let{ok:e,where:n}=DE([mL(),this.getSettingsPath()]);return e?{check:"MCP registration",status:"pass",message:`context-mode found in Antigravity CLI mcpServers (${n})`}:{check:"MCP registration",status:"fail",message:"context-mode not found in Antigravity CLI mcpServers",fix:"npm run install:agy"}}getInstalledVersion(){try{let e=zn(yu(co(Su(),"plugin.json"),"utf-8"));if(e&&typeof e.version=="string"&&e.version)return e.version}catch{}return DE([this.getSettingsPath()]).ok?"standalone":"not installed"}configureAllHooks(e){let n=[],r=Dh(),o={};try{o=zn(yu(r,"utf-8"))??{}}catch{}let s=o.hooks??{},i={matcher:SL,hooks:[{type:"command",command:Mh}]},a={matcher:"",hooks:[{type:"command",command:jh}]},c={matcher:"",hooks:[{type:"command",command:zh}]},u=Nh(s,"PreToolUse",i,Mh),l=Nh(s,"PostToolUse",a,jh),d=Nh(s,"Stop",c,zh);return(u||l||d)&&(o.hooks=s,dL(fL(r),{recursive:!0}),pL(r,JSON.stringify(o,null,2)+`
|
|
183
|
+
`,"utf-8"),n.push(`Configured Antigravity CLI PreToolUse/PostToolUse hooks and best-effort Stop hook in ${r}`)),n}validateHooks(e){let{ok:n,where:r,preOk:o,postOk:s,stopOk:i}=_L([hL(),Dh()]),a=[o?null:"PreToolUse",s?null:"PostToolUse"].filter(Boolean).join(", ");return[{check:"Antigravity CLI hooks",status:n?"pass":"warn",message:n?`PreToolUse guard and PostToolUse capture configured in ${r}${i?"; best-effort Stop hook also configured":""}`:`Antigravity CLI hooks incomplete (${a||"none found"} missing) \u2014 MCP tools still work, but bounded routing enforcement and session capture are degraded. Run \`npm run install:agy\` (agy plugin) or \`context-mode upgrade\` to repair hooks.`,...n?{}:{fix:"npm run install:agy"}}]}}});function xu(t,e){let n=qE[e];return n&&(t.command?.includes(n)||t.command?.includes("context-mode hook kiro"))||!1}function ls(t,e){let n=qE[t];return e&&n?Le(`${e}/hooks/kiro/${n}`):`context-mode hook kiro ${t.toLowerCase()}`}var Ie,qE,kL,bL,Hh,GW,JW,VE=X(()=>{"use strict";Mn();Ie={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},qE={[Ie.PRE_TOOL_USE]:"pretooluse.mjs",[Ie.POST_TOOL_USE]:"posttooluse.mjs",[Ie.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Ie.AGENT_SPAWN]:"agentspawn.mjs"},kL="@(?!context-mode/)",bL=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",kL],Hh=bL.join("|"),GW=[Ie.PRE_TOOL_USE,Ie.AGENT_SPAWN],JW=[Ie.POST_TOOL_USE,Ie.USER_PROMPT_SUBMIT]});var JE={};De(JE,{KiroAdapter:()=>Uh});import{readFileSync as ds,writeFileSync as WE,mkdirSync as KE}from"node:fs";import{resolve as uo,dirname as GE}from"node:path";import{fileURLToPath as vL}from"node:url";import{homedir as ku}from"node:os";var Uh,XE=X(()=>{"use strict";et();VE();Uh=class extends ge{constructor(){super([".kiro"])}name="Kiro";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_response;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:typeof r=="string"?r:JSON.stringify(r??""),sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let n=e??{};return{source:n.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}formatPreToolUseResponse(e){switch(e.decision){case"deny":return{exitCode:2,stderr:e.reason??"Blocked by context-mode"};case"context":return{exitCode:0,stdout:e.additionalContext??""};default:return}}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){if(e?.context)return{hookSpecificOutput:{hookEventName:"agentSpawn",additionalContext:e.context}}}getSettingsPath(){return uo(ku(),".kiro","settings","mcp.json")}getConfigDir(e){return uo(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Ie.PRE_TOOL_USE]:[{matcher:Hh,hooks:[{type:"command",command:ls(Ie.PRE_TOOL_USE,e)}]}],[Ie.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:ls(Ie.POST_TOOL_USE,e)}]}],[Ie.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:ls(Ie.AGENT_SPAWN,e)}]}],[Ie.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:ls(Ie.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=ds(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();KE(GE(n),{recursive:!0}),WE(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let n=[],r=uo(ku(),".kiro","agents","default.json");try{let s=JSON.parse(ds(r,"utf-8")).hooks??{};for(let i of[Ie.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>xu(u,i));n.push({check:`Hook: ${i}`,status:c?"pass":"fail",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured`,...c?{}:{fix:"Run: context-mode upgrade"}})}for(let i of[Ie.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>xu(u,i));n.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{n.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return n}checkPluginRegistration(){try{let e=ds(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=uo(ku(),".kiro","extensions","context-mode","package.json");return JSON.parse(ds(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=[],r=uo(ku(),".kiro","agents"),o=uo(r,"default.json");try{KE(r,{recursive:!0});let s={};try{s=JSON.parse(ds(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[Ie.PRE_TOOL_USE,Hh],[Ie.POST_TOOL_USE,"*"],[Ie.AGENT_SPAWN,"*"],[Ie.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>xu(d,c))||(l.push({matcher:u,command:ls(c,e)}),i[c]=l,n.push(`Added ${c} hook to ${o}`))}s.hooks=i,WE(o,JSON.stringify(s,null,2),"utf-8")}catch(s){n.push(`Failed to configure hooks: ${s.message}`)}return n}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=uo(GE(vL(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return ds(e,"utf-8")}catch{return`# context-mode
|
|
179
184
|
|
|
180
|
-
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
|
|
185
|
+
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 ew={};De(ew,{ZedAdapter:()=>Zh});import{readFileSync as Fh,writeFileSync as EL,mkdirSync as wL}from"node:fs";import{resolve as YE,dirname as QE}from"node:path";import{fileURLToPath as TL}from"node:url";import{homedir as PL}from"node:os";var Zh,tw=X(()=>{"use strict";et();Zh=class extends ge{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 YE(PL(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Fh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();wL(QE(n),{recursive:!0}),EL(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Zed does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Fh(this.getSettingsPath(),"utf-8"),r=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:r?{check:"MCP registration",status:"fail",message:"context_servers section exists but context-mode not found",fix:"Add context-mode to context_servers in ~/.config/zed/settings.json"}:{check:"MCP registration",status:"fail",message:"No context_servers section in settings.json",fix:"Add context_servers.context-mode to ~/.config/zed/settings.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.config/zed/settings.json"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=YE(QE(TL(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return Fh(e,"utf-8")}catch{return`# context-mode
|
|
181
186
|
|
|
182
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var
|
|
187
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var Bh,nw=X(()=>{"use strict";Bh="mcp__(?!.*context-mode)"});var sw={};De(sw,{QwenCodeAdapter:()=>qh});import{readFileSync as RL,writeFileSync as CL,existsSync as $L}from"node:fs";import{resolve as rw,join as OL}from"node:path";import{homedir as ow}from"node:os";var qh,iw=X(()=>{"use strict";Qm();nw();Mn();qh=class extends os{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 rw(ow(),".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",Bh].join("|"),hooks:[{type:"command",command:Le(`${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:Le(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=RL(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){CL(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let n=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit"]){let i=Array.isArray(o[s])&&o[s].length>0;n.push({check:`${s} hook`,status:i?"pass":"fail",message:i?`${s} hook configured in ~/.qwen/settings.json`:`${s} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${s} hook to ~/.qwen/settings.json`}})}return n}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let n=e.mcpServers;return Object.keys(n).some(r=>r.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in mcpServers"}:{check:"Plugin registration",status:"fail",message:"mcpServers exists but context-mode not found",fix:"Add context-mode to mcpServers in ~/.qwen/settings.json"}}return{check:"Plugin registration",status:"warn",message:"No mcpServers in ~/.qwen/settings.json"}}catch{return{check:"Plugin registration",status:"warn",message:"Could not read ~/.qwen/settings.json"}}}getInstalledVersion(){let e=this.readSettings();if(!e)return"not installed";let n=e.hooks;if(!n)return"not installed";let r=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(n))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&r.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[];for(let i of Object.keys(r)){let a=r[i];if(!Array.isArray(a))continue;let c=a.filter(l=>{let f=l.hooks??[];return f.some(p=>p.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(p.command))?f.every(p=>{if(!p.command)return!0;let h=p.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=p.command.match(/node\s+"?([^"]+\.mjs)"?/),y=h||g;return y?$L(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(r[i]=c,o.push(`Removed ${u} stale ${i} hook(s)`))}let s=[{name:"PreToolUse",script:"pretooluse.mjs",matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",Bh].join("|")},{name:"PostToolUse",script:"posttooluse.mjs",matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__"},{name:"SessionStart",script:"sessionstart.mjs",matcher:""},{name:"PreCompact",script:"precompact.mjs",matcher:""},{name:"UserPromptSubmit",script:"userpromptsubmit.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:Le(`${e}/hooks/${a}`)}]},l=r[i];if(l&&Array.isArray(l)){let d=l.findIndex(f=>f.hooks?.some(p=>p.command?.includes(a))??!1);d>=0?(l[d]=u,o.push(`Updated ${i} hook`)):(l.push(u),o.push(`Added ${i} hook`)),r[i]=l}else r[i]=[u],o.push(`Created ${i} hooks`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructionsConfig(){return{instructionsPath:rw(OL(ow(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var aw={};De(aw,{OMPAdapter:()=>Kh});import{readFileSync as Vh,writeFileSync as IL,mkdirSync as AL}from"node:fs";import{resolve as Wh,dirname as NL}from"node:path";import{homedir as DL}from"node:os";var Kh,cw=X(()=>{"use strict";et();Kh=class extends ge{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??Wh(DL(),".omp","agent")}getSettingsPath(){return Wh(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Vh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();AL(NL(n),{recursive:!0}),IL(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"context-mode delivers via MCP for OMP. Native OMP pre/post tool-call hooks are not yet wired by this adapter."}]}checkPluginRegistration(){try{let e=Vh(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=Wh(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(Vh(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
|
|
183
188
|
|
|
184
|
-
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
|
|
189
|
+
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 uw={};De(uw,{PiAdapter:()=>Yh});import{readFileSync as Gh,writeFileSync as ML,mkdirSync as jL}from"node:fs";import{resolve as Jh,dirname as zL}from"node:path";import{homedir as Xh}from"node:os";var Yh,lw=X(()=>{"use strict";et();Yh=class extends ge{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 Jh(Xh(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Gh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();jL(zL(n),{recursive:!0}),ML(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"pass",message:"Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/), not via JSON-stdio."}]}checkPluginRegistration(){let e=Jh(Xh(),".pi","extensions","context-mode","package.json");try{return JSON.parse(Gh(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=Jh(Xh(),".pi","extensions","context-mode","package.json");return JSON.parse(Gh(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
|
|
185
190
|
|
|
186
|
-
Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});import{homedir as
|
|
187
|
-
`)}function
|
|
191
|
+
Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});import{homedir as dw}from"node:os";import{resolve as Qh}from"node:path";function pw(){let t=process.env.KIMI_CODE_HOME;return t?t.startsWith("~")?Qh(dw(),t.replace(/^~[/\\]?/,"")):Qh(t):Qh(dw(),".kimi-code")}var fw=X(()=>{"use strict"});var _w={};De(_w,{KimiAdapter:()=>tg,probeKimiCliVersion:()=>yw});import{execFileSync as LL}from"node:child_process";import{readFileSync as qi,writeFileSync as HL,accessSync as UL,copyFileSync as FL,constants as ZL,mkdirSync as mw}from"node:fs";import{resolve as BL,dirname as hw,join as lo}from"node:path";import{fileURLToPath as qL}from"node:url";function yw(t=LL){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","kimi --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("kimi",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function gw(t){let e=[],n=t.split(/\r?\n/),r=null;for(let o of n){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(o)){r&&r.event&&r.command&&e.push(r),r={};continue}if(!r)continue;let s=o.match(/^\s*(\w+)\s*=\s*(?:"([^"]*)"|(\d+))\s*(?:#.*)?$/);if(s){let i=s[1],a=s[2],c=s[3];a!==void 0?r[i]=a:c!==void 0&&(r[i]=Number(c))}}return r&&r.event&&r.command&&e.push(r),e}function KL(t){let e=["[[hooks]]"];return e.push(`event = "${t.event}"`),t.matcher&&e.push(`matcher = "${t.matcher}"`),e.push(`command = "${t.command}"`),t.timeout!==void 0&&e.push(`timeout = ${t.timeout}`),e.join(`
|
|
192
|
+
`)}function eg(t){return t.command.includes("context-mode hook kimi")}function GL(t,e){let n=(e.hooks?.[0]?.command??"").trim();return n?{event:t,matcher:e.matcher||void 0,command:n,timeout:30}:null}var VL,hr,WL,tg,Sw=X(()=>{"use strict";et();kn();fw();VL="Bash|Shell|Read|Edit|Write|WebFetch|Agent|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",hr={PreToolUse:"context-mode hook kimi pretooluse",PostToolUse:"context-mode hook kimi posttooluse",SessionStart:"context-mode hook kimi sessionstart",SessionEnd:"context-mode hook kimi sessionend",PreCompact:"context-mode hook kimi precompact",UserPromptSubmit:"context-mode hook kimi userpromptsubmit",Stop:"context-mode hook kimi stop"},WL={PreToolUse:["hooks/pretooluse.mjs","hooks/kimi/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/kimi/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/kimi/sessionstart.mjs"],SessionEnd:["hooks/sessionend.mjs","hooks/kimi/sessionend.mjs"],PreCompact:["hooks/precompact.mjs","hooks/kimi/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/kimi/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/kimi/stop.mjs"]};tg=class extends ge{constructor(){super([".kimi-code"])}name="Kimi Code CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,o=(n.source??"startup")==="resume"?"resume":"startup";return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return pw()}getSettingsPath(){return lo(this.getConfigDir(),"config.toml")}getMcpPath(){return lo(this.getConfigDir(),"mcp.json")}getSessionDir(){let e=it(),n=e?lo(e,"context-mode","sessions"):lo(this.getConfigDir(),"context-mode","sessions");return mw(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=it(),r=n?lo(n,"context-mode","memory"):lo(this.getConfigDir(),"memory");return e?lo(r,Qe(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:VL,hooks:[{type:"command",command:hr.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:hr.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:hr.SessionStart}]}],SessionEnd:[{matcher:"",hooks:[{type:"command",command:hr.SessionEnd}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:hr.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:hr.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:hr.Stop}]}]}}readSettings(){try{return{_raw_toml:qi(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=yw();n.push({check:"Kimi Code CLI binary",status:r?"pass":"warn",message:r?`kimi --version resolved to ${r}`:"Could not run kimi --version; hooks need the Kimi Code CLI available on PATH",...r?{}:{fix:"Install Kimi Code CLI or make kimi available on PATH"}});let o="";try{o=qi(this.getSettingsPath(),"utf-8")}catch{return n.push({check:"Hooks config",status:"fail",message:`No readable ${this.getSettingsPath()} found`,fix:"Run context-mode upgrade to generate the initial config.toml"}),n}let s=gw(o),i=this.generateHookConfig("");for(let[a,c]of Object.entries(i)){let u=c[0],l=s.some(f=>f.event===a&&this.isExpectedHookEntry(a,f,u)),d=a==="PreCompact"?"warn":"fail";n.push({check:`${a} hook`,status:l?"pass":d,message:l?`${a} hook configured in ${this.getSettingsPath()}`:a==="PreCompact"?`${a} hook missing or not pointing to context-mode; compaction snapshots require a Kimi build that emits PreCompact`:`${a} hook missing or not pointing to context-mode`,fix:l?void 0:`Update ${this.getSettingsPath()} to include the managed ${a} [[hooks]] entry`})}for(let a of Object.keys(i)){let c=s.filter(u=>u.event===a&&eg(u)).length;c>1&&n.push({check:`${a} duplicates`,status:"warn",message:`${c} context-mode entries found for ${a} in ${this.getSettingsPath()}; Kimi will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"})}return n}checkPluginRegistration(){try{let e=qi(this.getMcpPath(),"utf-8"),n=JSON.parse(e),r=e.includes("context-mode"),o=n.mcpServers!==void 0||n.mcp_servers!==void 0;return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in mcp.json"}:o?{check:"MCP registration",status:"fail",message:"mcpServers section exists but context-mode not found",fix:`Add context-mode to mcpServers in ${this.getMcpPath()}`}:{check:"MCP registration",status:"fail",message:"No mcpServers section in mcp.json",fix:`Add mcpServers.context-mode to ${this.getMcpPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getMcpPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let n=[],r=this.generateHookConfig(""),o="";try{o=qi(this.getSettingsPath(),"utf-8")}catch{o=""}let s=gw(o),i=s.filter(l=>!eg(l)),a=[];for(let[l,d]of Object.entries(r)){let f=GL(l,d[0]);f&&a.push(f)}let c=s.some(eg),u=this.rebuildToml(o,i,a);return u!==o&&(mw(hw(this.getSettingsPath()),{recursive:!0}),HL(this.getSettingsPath(),u,"utf-8"),c?n.push(`Updated managed Kimi hooks in ${this.getSettingsPath()}`):n.push(`Wrote managed Kimi hooks to ${this.getSettingsPath()}`)),n}backupSettings(){let e=null;for(let n of[this.getSettingsPath(),this.getMcpPath()])try{UL(n,ZL.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=BL(hw(qL(import.meta.url)),"..","..","..","configs","kimi","AGENTS.md");try{return qi(e,"utf-8")}catch{return`# context-mode
|
|
188
193
|
|
|
189
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.KIMI_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}backupFile(e,
|
|
190
|
-
`)}}});var cu={};He(cu,{PLATFORM_ENV_VARS:()=>ls,__resetClaudeCodePluginCacheForTests:()=>Nz,__seedClaudeCodePluginCacheMissForTests:()=>Dz,detectPlatform:()=>Lr,foreignIdentificationEnv:()=>Lz,foreignWorkspaceEnv:()=>zz,getAdapter:()=>Hz,getEnvVarNames:()=>jz,getSessionDirSegments:()=>Hi,workspaceEnvVarsFor:()=>Ih});import{existsSync as vt,readFileSync as Iz}from"node:fs";import{resolve as lt}from"node:path";import{homedir as $E}from"node:os";function Az(){if(ao!==null)return ao!=="miss"&&ao.hasCM;try{let t=lt($E(),".claude","plugins","installed_plugins.json"),e=Iz(t,"utf-8"),r=JSON.parse(e),o=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(s=>s.includes("context-mode"));return ao={hasCM:o},o}catch{return ao="miss",!1}}function Nz(){ao=null}function Dz(){ao="miss"}function jz(t){return(ls.get(t)??[]).map(e=>e.name)}function Ih(t){return(ls.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function zz(t){let e=new Set;for(let[r,n]of ls)if(r!==t)for(let o of n)o.role==="workspace"&&e.add(o.name);return e}function Lz(t){let e=new Set;for(let[r,n]of ls)if(r!==t)for(let o of n)o.role==="identification"&&e.add(o.name);return e}function Hi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kimi":return[".kimi-code"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function Lr(t){if(t?.name){let n=Db[t.name];if(n)return{platform:n,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","cursor","antigravity","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,o]of ls)if(o.some(s=>s.detect!==!1&&process.env[s.name]))return n==="vscode-copilot"&&Az()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:n,confidence:"high",reason:`${o.filter(s=>s.detect!==!1).map(s=>s.name).join(" or ")} env var set`};let r=$E();return vt(lt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:vt(lt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:vt(lt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:vt(lt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:vt(lt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:vt(lt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:vt(lt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:vt(lt(r,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:vt(lt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:vt(lt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:vt(lt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:vt(lt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:vt(lt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:vt(lt(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 Hz(t){let e=t??Lr().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Bm(),qm));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(mk(),fk));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(_k(),yk));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(vk(),Sk));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(Ok(),Ck));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(jk(),Mk));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(Uk(),Hk));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(Jk(),Gk));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(Qk(),Yk));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(iE(),sE));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(lE(),uE));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(hE(),mE));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(yE(),gE));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(xE(),_E));return new r}case"kimi":{let{KimiAdapter:r}=await Promise.resolve().then(()=>(RE(),PE));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Bm(),qm));return new r}}}var ao,Mz,ls,co=ne(()=>{"use strict";Mb();ao=null;Mz=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"}]]],ls=new Map(Mz)});import{resolve as Ui}from"node:path";import{homedir as Ah}from"node:os";function wt(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Ui(Ah(),e.replace(/^~[/\\]?/,"")):Ui(e):Ui(Ah(),".claude")}function Uz(t=process.env){return Ui(wt(t),"settings.json")}function Nh(t=process.env){let e=[],r=Lr();if(r.platform!=="claude-code"){let o=Hi(r.platform);o&&o.length>0&&e.push(Ui(Ah(),...o,"settings.json"))}let n=Uz(t);return e.includes(n)||e.push(n),e}var Yn=ne(()=>{"use strict";co()});var O={};He(O,{BRAND:()=>_T,DIRTY:()=>yn,EMPTY_PATH:()=>Jw,INVALID:()=>B,NEVER:()=>tP,OK:()=>tt,ParseStatus:()=>Ve,Schema:()=>Y,ZodAny:()=>Vr,ZodArray:()=>Pr,ZodBigInt:()=>xn,ZodBoolean:()=>Sn,ZodBranded:()=>Ss,ZodCatch:()=>On,ZodDate:()=>vn,ZodDefault:()=>Cn,ZodDiscriminatedUnion:()=>Qi,ZodEffects:()=>Ot,ZodEnum:()=>Rn,ZodError:()=>pt,ZodFirstPartyTypeKind:()=>P,ZodFunction:()=>ta,ZodIntersection:()=>wn,ZodIssueCode:()=>w,ZodLazy:()=>Tn,ZodLiteral:()=>Pn,ZodMap:()=>yo,ZodNaN:()=>xo,ZodNativeEnum:()=>$n,ZodNever:()=>Kt,ZodNull:()=>kn,ZodNullable:()=>dr,ZodNumber:()=>_n,ZodObject:()=>mt,ZodOptional:()=>ft,ZodParsedType:()=>D,ZodPipeline:()=>vs,ZodPromise:()=>Wr,ZodReadonly:()=>In,ZodRecord:()=>ea,ZodSchema:()=>Y,ZodSet:()=>_o,ZodString:()=>Br,ZodSymbol:()=>ho,ZodTransformer:()=>Ot,ZodTuple:()=>lr,ZodType:()=>Y,ZodUndefined:()=>bn,ZodUnion:()=>En,ZodUnknown:()=>Tr,ZodVoid:()=>go,addIssueToContext:()=>I,any:()=>PT,array:()=>OT,bigint:()=>bT,boolean:()=>kg,coerce:()=>eP,custom:()=>Sg,date:()=>kT,datetimeRegex:()=>_g,defaultErrorMap:()=>Er,discriminatedUnion:()=>NT,effect:()=>VT,enum:()=>ZT,function:()=>HT,getErrorMap:()=>po,getParsedType:()=>ur,instanceof:()=>ST,intersection:()=>DT,isAborted:()=>Xi,isAsync:()=>fo,isDirty:()=>Yi,isValid:()=>qr,late:()=>xT,lazy:()=>UT,literal:()=>FT,makeIssue:()=>xs,map:()=>zT,nan:()=>vT,nativeEnum:()=>qT,never:()=>$T,null:()=>TT,nullable:()=>KT,number:()=>bg,object:()=>Hu,objectUtil:()=>ju,oboolean:()=>QT,onumber:()=>YT,optional:()=>WT,ostring:()=>XT,pipeline:()=>JT,preprocess:()=>GT,promise:()=>BT,quotelessJson:()=>Ww,record:()=>jT,set:()=>LT,setErrorMap:()=>Gw,strictObject:()=>IT,string:()=>vg,symbol:()=>ET,transformer:()=>VT,tuple:()=>MT,undefined:()=>wT,union:()=>AT,unknown:()=>RT,util:()=>oe,void:()=>CT});var oe;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(oe||(oe={}));var ju;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(ju||(ju={}));var D=oe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ur=t=>{switch(typeof t){case"undefined":return D.undefined;case"string":return D.string;case"number":return Number.isNaN(t)?D.nan:D.number;case"boolean":return D.boolean;case"function":return D.function;case"bigint":return D.bigint;case"symbol":return D.symbol;case"object":return Array.isArray(t)?D.array:t===null?D.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?D.promise:typeof Map<"u"&&t instanceof Map?D.map:typeof Set<"u"&&t instanceof Set?D.set:typeof Date<"u"&&t instanceof Date?D.date:D.object;default:return D.unknown}};var w=oe.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"]),Ww=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),pt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,oe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};pt.create=t=>new pt(t);var Kw=(t,e)=>{let r;switch(t.code){case w.invalid_type:t.received===D.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case w.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,oe.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:r=`Unrecognized key(s) in object: ${oe.joinValues(t.keys,", ")}`;break;case w.invalid_union:r="Invalid input";break;case w.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${oe.joinValues(t.options)}`;break;case w.invalid_enum_value:r=`Invalid enum value. Expected ${oe.joinValues(t.options)}, received '${t.received}'`;break;case w.invalid_arguments:r="Invalid function arguments";break;case w.invalid_return_type:r="Invalid function return type";break;case w.invalid_date:r="Invalid date";break;case w.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}"`:oe.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case w.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 w.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 w.custom:r="Invalid input";break;case w.invalid_intersection_types:r="Intersection results could not be merged";break;case w.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case w.not_finite:r="Number must be finite";break;default:r=e.defaultError,oe.assertNever(t)}return{message:r}},Er=Kw;var fg=Er;function Gw(t){fg=t}function po(){return fg}var xs=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},Jw=[];function I(t,e){let r=po(),n=xs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Er?void 0:Er].filter(o=>!!o)});t.common.issues.push(n)}var Ve=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return B;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return B;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},B=Object.freeze({status:"aborted"}),yn=t=>({status:"dirty",value:t}),tt=t=>({status:"valid",value:t}),Xi=t=>t.status==="aborted",Yi=t=>t.status==="dirty",qr=t=>t.status==="valid",fo=t=>typeof Promise<"u"&&t instanceof Promise;var z;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}));var Ct=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},mg=(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 pt(t.common.issues);return this._error=r,this._error}}};function J(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var Y=class{get description(){return this._def.description}_getType(e){return ur(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ur(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ve,ctx:{common:e.parent.common,data:e.data,parsedType:ur(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(fo(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:ur(e)},o=this._parseSync({data:e,path:n.path,parent:n});return mg(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ur(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:ur(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(fo(o)?o:Promise.resolve(o));return mg(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:w.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Ot({schema:this,typeName:P.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 ft.create(this,this._def)}nullable(){return dr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Pr.create(this)}promise(){return Wr.create(this,this._def)}or(e){return En.create([this,e],this._def)}and(e){return wn.create(this,e,this._def)}transform(e){return new Ot({...J(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Cn({...J(this._def),innerType:this,defaultValue:r,typeName:P.ZodDefault})}brand(){return new Ss({typeName:P.ZodBranded,type:this,...J(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new On({...J(this._def),innerType:this,catchValue:r,typeName:P.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return vs.create(this,e)}readonly(){return In.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Xw=/^c[^\s-]{8,}$/i,Yw=/^[0-9a-z]+$/,Qw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,eT=/^[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,tT=/^[a-z0-9_-]{21}$/i,rT=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nT=/^[-+]?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)?)??$/,oT=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",zu,iT=/^(?:(?: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])$/,aT=/^(?:(?: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])$/,cT=/^(([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]))$/,uT=/^(([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])$/,lT=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,dT=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gg="((\\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])))",pT=new RegExp(`^${gg}$`);function yg(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 fT(t){return new RegExp(`^${yg(t)}$`)}function _g(t){let e=`${gg}T${yg(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 mT(t,e){return!!((e==="v4"||!e)&&iT.test(t)||(e==="v6"||!e)&&cT.test(t))}function hT(t,e){if(!rT.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function gT(t,e){return!!((e==="v4"||!e)&&aT.test(t)||(e==="v6"||!e)&&uT.test(t))}var Br=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==D.string){let s=this._getOrReturnCtx(e);return I(s,{code:w.invalid_type,expected:D.string,received:s.parsedType}),B}let n=new Ve,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),I(o,{code:w.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),I(o,{code:w.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?I(o,{code:w.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&I(o,{code:w.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")oT.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"email",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")zu||(zu=new RegExp(sT,"u")),zu.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"emoji",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")eT.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"uuid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")tT.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"nanoid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Xw.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"cuid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Yw.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"cuid2",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Qw.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"ulid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),I(o,{validation:"url",code:w.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"regex",code:w.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),I(o,{code:w.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),I(o,{code:w.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),I(o,{code:w.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?_g(s).test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{code:w.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?pT.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{code:w.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?fT(s).test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{code:w.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?nT.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"duration",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?mT(e.data,s.version)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"ip",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?hT(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"jwt",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?gT(e.data,s.version)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"cidr",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?lT.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"base64",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?dT.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"base64url",code:w.invalid_string,message:s.message}),n.dirty()):oe.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:w.invalid_string,...z.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.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,...z.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,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...z.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...z.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...z.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...z.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...z.errToObj(r)})}nonempty(e){return this.min(1,z.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}};Br.create=t=>new Br({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...J(t)});function yT(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var _n=class t extends Y{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)!==D.number){let s=this._getOrReturnCtx(e);return I(s,{code:w.invalid_type,expected:D.number,received:s.parsedType}),B}let n,o=new Ve;for(let s of this._def.checks)s.kind==="int"?oe.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:w.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:w.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:w.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?yT(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),I(n,{code:w.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:w.not_finite,message:s.message}),o.dirty()):oe.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,z.toString(r))}gt(e,r){return this.setLimit("min",e,!1,z.toString(r))}lte(e,r){return this.setLimit("max",e,!0,z.toString(r))}lt(e,r){return this.setLimit("max",e,!1,z.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:z.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.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"&&oe.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)}};_n.create=t=>new _n({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...J(t)});var xn=class t extends Y{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)!==D.bigint)return this._getInvalidInput(e);let n,o=new Ve;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:w.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:w.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),I(n,{code:w.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):oe.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return I(r,{code:w.invalid_type,expected:D.bigint,received:r.parsedType}),B}gte(e,r){return this.setLimit("min",e,!0,z.toString(r))}gt(e,r){return this.setLimit("min",e,!1,z.toString(r))}lte(e,r){return this.setLimit("max",e,!0,z.toString(r))}lt(e,r){return this.setLimit("max",e,!1,z.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:z.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:z.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}};xn.create=t=>new xn({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...J(t)});var Sn=class extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==D.boolean){let n=this._getOrReturnCtx(e);return I(n,{code:w.invalid_type,expected:D.boolean,received:n.parsedType}),B}return tt(e.data)}};Sn.create=t=>new Sn({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...J(t)});var vn=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==D.date){let s=this._getOrReturnCtx(e);return I(s,{code:w.invalid_type,expected:D.date,received:s.parsedType}),B}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return I(s,{code:w.invalid_date}),B}let n=new Ve,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),I(o,{code:w.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),I(o,{code:w.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):oe.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:z.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}};vn.create=t=>new vn({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...J(t)});var ho=class extends Y{_parse(e){if(this._getType(e)!==D.symbol){let n=this._getOrReturnCtx(e);return I(n,{code:w.invalid_type,expected:D.symbol,received:n.parsedType}),B}return tt(e.data)}};ho.create=t=>new ho({typeName:P.ZodSymbol,...J(t)});var bn=class extends Y{_parse(e){if(this._getType(e)!==D.undefined){let n=this._getOrReturnCtx(e);return I(n,{code:w.invalid_type,expected:D.undefined,received:n.parsedType}),B}return tt(e.data)}};bn.create=t=>new bn({typeName:P.ZodUndefined,...J(t)});var kn=class extends Y{_parse(e){if(this._getType(e)!==D.null){let n=this._getOrReturnCtx(e);return I(n,{code:w.invalid_type,expected:D.null,received:n.parsedType}),B}return tt(e.data)}};kn.create=t=>new kn({typeName:P.ZodNull,...J(t)});var Vr=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return tt(e.data)}};Vr.create=t=>new Vr({typeName:P.ZodAny,...J(t)});var Tr=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return tt(e.data)}};Tr.create=t=>new Tr({typeName:P.ZodUnknown,...J(t)});var Kt=class extends Y{_parse(e){let r=this._getOrReturnCtx(e);return I(r,{code:w.invalid_type,expected:D.never,received:r.parsedType}),B}};Kt.create=t=>new Kt({typeName:P.ZodNever,...J(t)});var go=class extends Y{_parse(e){if(this._getType(e)!==D.undefined){let n=this._getOrReturnCtx(e);return I(n,{code:w.invalid_type,expected:D.void,received:n.parsedType}),B}return tt(e.data)}};go.create=t=>new go({typeName:P.ZodVoid,...J(t)});var Pr=class t extends Y{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==D.array)return I(r,{code:w.invalid_type,expected:D.array,received:r.parsedType}),B;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(I(r,{code:i?w.too_big:w.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(I(r,{code:w.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(I(r,{code:w.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Ct(r,i,r.path,a)))).then(i=>Ve.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Ct(r,i,r.path,a)));return Ve.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:z.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:z.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:z.toString(r)}})}nonempty(e){return this.min(1,e)}};Pr.create=(t,e)=>new Pr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...J(e)});function mo(t){if(t instanceof mt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ft.create(mo(n))}return new mt({...t._def,shape:()=>e})}else return t instanceof Pr?new Pr({...t._def,type:mo(t.element)}):t instanceof ft?ft.create(mo(t.unwrap())):t instanceof dr?dr.create(mo(t.unwrap())):t instanceof lr?lr.create(t.items.map(e=>mo(e))):t}var mt=class t extends Y{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=oe.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==D.object){let u=this._getOrReturnCtx(e);return I(u,{code:w.invalid_type,expected:D.object,received:u.parsedType}),B}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Kt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ct(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Kt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(I(o,{code:w.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ct(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Ve.mergeObjectSync(n,u)):Ve.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:z.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:P.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 oe.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 oe.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return mo(this)}partial(e){let r={};for(let n of oe.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of oe.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ft;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return xg(oe.objectKeys(this.shape))}};mt.create=(t,e)=>new mt({shape:()=>t,unknownKeys:"strip",catchall:Kt.create(),typeName:P.ZodObject,...J(e)});mt.strictCreate=(t,e)=>new mt({shape:()=>t,unknownKeys:"strict",catchall:Kt.create(),typeName:P.ZodObject,...J(e)});mt.lazycreate=(t,e)=>new mt({shape:t,unknownKeys:"strip",catchall:Kt.create(),typeName:P.ZodObject,...J(e)});var En=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new pt(a.ctx.common.issues));return I(r,{code:w.invalid_union,unionErrors:i}),B}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new pt(c));return I(r,{code:w.invalid_union,unionErrors:a}),B}}get options(){return this._def.options}};En.create=(t,e)=>new En({options:t,typeName:P.ZodUnion,...J(e)});var wr=t=>t instanceof Tn?wr(t.schema):t instanceof Ot?wr(t.innerType()):t instanceof Pn?[t.value]:t instanceof Rn?t.options:t instanceof $n?oe.objectValues(t.enum):t instanceof Cn?wr(t._def.innerType):t instanceof bn?[void 0]:t instanceof kn?[null]:t instanceof ft?[void 0,...wr(t.unwrap())]:t instanceof dr?[null,...wr(t.unwrap())]:t instanceof Ss||t instanceof In?wr(t.unwrap()):t instanceof On?wr(t._def.innerType):[],Qi=class t extends Y{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==D.object)return I(r,{code:w.invalid_type,expected:D.object,received:r.parsedType}),B;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(I(r,{code:w.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),B)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=wr(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:P.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...J(n)})}};function Lu(t,e){let r=ur(t),n=ur(e);if(t===e)return{valid:!0,data:t};if(r===D.object&&n===D.object){let o=oe.objectKeys(e),s=oe.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Lu(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===D.array&&n===D.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Lu(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===D.date&&n===D.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var wn=class extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Xi(s)||Xi(i))return B;let a=Lu(s.value,i.value);return a.valid?((Yi(s)||Yi(i))&&r.dirty(),{status:r.value,value:a.data}):(I(n,{code:w.invalid_intersection_types}),B)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};wn.create=(t,e,r)=>new wn({left:t,right:e,typeName:P.ZodIntersection,...J(r)});var lr=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==D.array)return I(n,{code:w.invalid_type,expected:D.array,received:n.parsedType}),B;if(n.data.length<this._def.items.length)return I(n,{code:w.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),B;!this._def.rest&&n.data.length>this._def.items.length&&(I(n,{code:w.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ct(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Ve.mergeArray(r,i)):Ve.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};lr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new lr({items:t,typeName:P.ZodTuple,rest:null,...J(e)})};var ea=class t extends Y{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!==D.object)return I(n,{code:w.invalid_type,expected:D.object,received:n.parsedType}),B;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Ct(n,a,n.path,a)),value:i._parse(new Ct(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ve.mergeObjectAsync(r,o):Ve.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Y?new t({keyType:e,valueType:r,typeName:P.ZodRecord,...J(n)}):new t({keyType:Br.create(),valueType:e,typeName:P.ZodRecord,...J(r)})}},yo=class extends Y{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!==D.map)return I(n,{code:w.invalid_type,expected:D.map,received:n.parsedType}),B;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new Ct(n,a,n.path,[u,"key"])),value:s._parse(new Ct(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return B;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return B;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};yo.create=(t,e,r)=>new yo({valueType:e,keyType:t,typeName:P.ZodMap,...J(r)});var _o=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==D.set)return I(n,{code:w.invalid_type,expected:D.set,received:n.parsedType}),B;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(I(n,{code:w.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(I(n,{code:w.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return B;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Ct(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:z.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:z.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};_o.create=(t,e)=>new _o({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...J(e)});var ta=class t extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==D.function)return I(r,{code:w.invalid_type,expected:D.function,received:r.parsedType}),B;function n(a,c){return xs({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,po(),Er].filter(u=>!!u),issueData:{code:w.invalid_arguments,argumentsError:c}})}function o(a,c){return xs({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,po(),Er].filter(u=>!!u),issueData:{code:w.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Wr){let a=this;return tt(async function(...c){let u=new pt([]),l=await a._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(n(c,h)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw u.addIssue(o(d,h)),u})})}else{let a=this;return tt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new pt([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new pt([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:lr.create(e).rest(Tr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||lr.create([]).rest(Tr.create()),returns:r||Tr.create(),typeName:P.ZodFunction,...J(n)})}},Tn=class extends Y{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})}};Tn.create=(t,e)=>new Tn({getter:t,typeName:P.ZodLazy,...J(e)});var Pn=class extends Y{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return I(r,{received:r.data,code:w.invalid_literal,expected:this._def.value}),B}return{status:"valid",value:e.data}}get value(){return this._def.value}};Pn.create=(t,e)=>new Pn({value:t,typeName:P.ZodLiteral,...J(e)});function xg(t,e){return new Rn({values:t,typeName:P.ZodEnum,...J(e)})}var Rn=class t extends Y{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return I(r,{expected:oe.joinValues(n),received:r.parsedType,code:w.invalid_type}),B}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 I(r,{received:r.data,code:w.invalid_enum_value,options:n}),B}return tt(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})}};Rn.create=xg;var $n=class extends Y{_parse(e){let r=oe.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==D.string&&n.parsedType!==D.number){let o=oe.objectValues(r);return I(n,{expected:oe.joinValues(o),received:n.parsedType,code:w.invalid_type}),B}if(this._cache||(this._cache=new Set(oe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=oe.objectValues(r);return I(n,{received:n.data,code:w.invalid_enum_value,options:o}),B}return tt(e.data)}get enum(){return this._def.values}};$n.create=(t,e)=>new $n({values:t,typeName:P.ZodNativeEnum,...J(e)});var Wr=class extends Y{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==D.promise&&r.common.async===!1)return I(r,{code:w.invalid_type,expected:D.promise,received:r.parsedType}),B;let n=r.parsedType===D.promise?r.data:Promise.resolve(r.data);return tt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Wr.create=(t,e)=>new Wr({type:t,typeName:P.ZodPromise,...J(e)});var Ot=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{I(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return B;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?B:c.status==="dirty"?yn(c.value):r.value==="dirty"?yn(c.value):c});{if(r.value==="aborted")return B;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?B:a.status==="dirty"?yn(a.value):r.value==="dirty"?yn(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?B:(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"?B:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!qr(i))return B;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>qr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):B);oe.assertNever(o)}};Ot.create=(t,e,r)=>new Ot({schema:t,typeName:P.ZodEffects,effect:e,...J(r)});Ot.createWithPreprocess=(t,e,r)=>new Ot({schema:e,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...J(r)});var ft=class extends Y{_parse(e){return this._getType(e)===D.undefined?tt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ft.create=(t,e)=>new ft({innerType:t,typeName:P.ZodOptional,...J(e)});var dr=class extends Y{_parse(e){return this._getType(e)===D.null?tt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};dr.create=(t,e)=>new dr({innerType:t,typeName:P.ZodNullable,...J(e)});var Cn=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===D.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Cn.create=(t,e)=>new Cn({innerType:t,typeName:P.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});var On=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return fo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new pt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new pt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};On.create=(t,e)=>new On({innerType:t,typeName:P.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});var xo=class extends Y{_parse(e){if(this._getType(e)!==D.nan){let n=this._getOrReturnCtx(e);return I(n,{code:w.invalid_type,expected:D.nan,received:n.parsedType}),B}return{status:"valid",value:e.data}}};xo.create=t=>new xo({typeName:P.ZodNaN,...J(t)});var _T=Symbol("zod_brand"),Ss=class extends Y{_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}},vs=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?B:s.status==="dirty"?(r.dirty(),yn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?B:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:P.ZodPipeline})}},In=class extends Y{_parse(e){let r=this._def.innerType._parse(e),n=o=>(qr(o)&&(o.value=Object.freeze(o.value)),o);return fo(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};In.create=(t,e)=>new In({innerType:t,typeName:P.ZodReadonly,...J(e)});function hg(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Sg(t,e={},r){return t?Vr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=hg(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=hg(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Vr.create()}var xT={object:mt.lazycreate},P;(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"})(P||(P={}));var ST=(t,e={message:`Input not instance of ${t.name}`})=>Sg(r=>r instanceof t,e),vg=Br.create,bg=_n.create,vT=xo.create,bT=xn.create,kg=Sn.create,kT=vn.create,ET=ho.create,wT=bn.create,TT=kn.create,PT=Vr.create,RT=Tr.create,$T=Kt.create,CT=go.create,OT=Pr.create,Hu=mt.create,IT=mt.strictCreate,AT=En.create,NT=Qi.create,DT=wn.create,MT=lr.create,jT=ea.create,zT=yo.create,LT=_o.create,HT=ta.create,UT=Tn.create,FT=Pn.create,ZT=Rn.create,qT=$n.create,BT=Wr.create,VT=Ot.create,WT=ft.create,KT=dr.create,GT=Ot.createWithPreprocess,JT=vs.create,XT=()=>vg().optional(),YT=()=>bg().optional(),QT=()=>kg().optional(),eP={string:(t=>Br.create({...t,coerce:!0})),number:(t=>_n.create({...t,coerce:!0})),boolean:(t=>Sn.create({...t,coerce:!0})),bigint:(t=>xn.create({...t,coerce:!0})),date:(t=>vn.create({...t,coerce:!0}))};var tP=B;var rP=Object.freeze({status:"aborted"});function b(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Rr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ra={};function bt(t){return t&&Object.assign(ra,t),ra}var se={};He(se,{BIGINT_FORMAT_RANGES:()=>wg,Class:()=>Fu,NUMBER_FORMAT_RANGES:()=>Gu,aborted:()=>Nn,allowsEval:()=>Vu,assert:()=>aP,assertEqual:()=>nP,assertIs:()=>sP,assertNever:()=>iP,assertNotEqual:()=>oP,assignProp:()=>Bu,cached:()=>Es,captureStackTrace:()=>oa,cleanEnum:()=>SP,cleanRegex:()=>Ts,clone:()=>kt,createTransparentProxy:()=>fP,defineLazy:()=>Se,esc:()=>An,escapeRegex:()=>Kr,extend:()=>gP,finalizeIssue:()=>Gt,floatSafeRemainder:()=>qu,getElementAtPath:()=>cP,getEnumValues:()=>ks,getLengthableOrigin:()=>Ps,getParsedType:()=>pP,getSizableOrigin:()=>Tg,isObject:()=>So,isPlainObject:()=>vo,issue:()=>Ju,joinValues:()=>na,jsonStringifyReplacer:()=>Zu,merge:()=>yP,normalizeParams:()=>V,nullish:()=>ws,numKeys:()=>dP,omit:()=>hP,optionalKeys:()=>Ku,partial:()=>_P,pick:()=>mP,prefixIssues:()=>pr,primitiveTypes:()=>Eg,promiseAllObject:()=>uP,propertyKeyTypes:()=>Wu,randomString:()=>lP,required:()=>xP,stringifyPrimitive:()=>sa,unwrapMessage:()=>bs});function nP(t){return t}function oP(t){return t}function sP(t){}function iP(t){throw new Error}function aP(t){}function ks(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function na(t,e="|"){return t.map(r=>sa(r)).join(e)}function Zu(t,e){return typeof e=="bigint"?e.toString():e}function Es(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ws(t){return t==null}function Ts(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function qu(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Se(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Bu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function cP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function uP(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function lP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function An(t){return JSON.stringify(t)}var oa=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function So(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Vu=Es(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function vo(t){if(So(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(So(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function dP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var pP=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}`)}},Wu=new Set(["string","number","symbol"]),Eg=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Kr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function V(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 fP(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function sa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Ku(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Gu={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]},wg={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function mP(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return kt(t,{...t._zod.def,shape:r,checks:[]})}function hP(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return kt(t,{...t._zod.def,shape:r,checks:[]})}function gP(t,e){if(!vo(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 Bu(this,"shape",n),n},checks:[]};return kt(t,r)}function yP(t,e){return kt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Bu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function _P(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return kt(e,{...e._zod.def,shape:o,checks:[]})}function xP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return kt(e,{...e._zod.def,shape:o,checks:[]})}function Nn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function pr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function bs(t){return typeof t=="string"?t:t?.message}function Gt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=bs(t.inst?._zod.def?.error?.(t))??bs(e?.error?.(t))??bs(r.customError?.(t))??bs(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Tg(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ps(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ju(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function SP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Fu=class{constructor(...e){}};var Pg=(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,Zu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ia=b("$ZodError",Pg),Rs=b("$ZodError",Pg,{Parent:Error});function Xu(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Yu(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var Qu=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Rr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Gt(c,s,bt())));throw oa(a,o?.callee),a}return i.value},el=Qu(Rs),tl=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Gt(c,s,bt())));throw oa(a,o?.callee),a}return i.value},rl=tl(Rs),nl=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Rr;return s.issues.length?{success:!1,error:new(t??ia)(s.issues.map(i=>Gt(i,o,bt())))}:{success:!0,data:s.value}},Dn=nl(Rs),ol=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Gt(i,o,bt())))}:{success:!0,data:s.value}},Mn=ol(Rs);var Rg=/^[cC][^\s-]{8,}$/,$g=/^[0-9a-z]+$/,Cg=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Og=/^[0-9a-vA-V]{20}$/,Ig=/^[A-Za-z0-9]{27}$/,Ag=/^[a-zA-Z0-9_-]{21}$/,Ng=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Dg=/^([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})$/,sl=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)$/;var Mg=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var bP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jg(){return new RegExp(bP,"u")}var zg=/^(?:(?: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])$/,Lg=/^(([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})$/,Hg=/^((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])$/,Ug=/^(([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])$/,Fg=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,il=/^[A-Za-z0-9_-]*$/,Zg=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var qg=/^\+(?:[0-9]){6,14}[0-9]$/,Bg="(?:(?:\\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])))",Vg=new RegExp(`^${Bg}$`);function Wg(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 Kg(t){return new RegExp(`^${Wg(t)}$`)}function Gg(t){let e=Wg({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(`^${Bg}T(?:${n})$`)}var Jg=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Xg=/^\d+$/,Yg=/^-?\d+(?:\.\d+)?/i,Qg=/true|false/i,ey=/null/i;var ty=/^[^A-Z]*$/,ry=/^[^a-z]*$/;var We=b("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),ny={number:"number",bigint:"bigint",object:"date"},al=b("$ZodCheckLessThan",(t,e)=>{We.init(t,e);let r=ny[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),cl=b("$ZodCheckGreaterThan",(t,e)=>{We.init(t,e);let r=ny[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),oy=b("$ZodCheckMultipleOf",(t,e)=>{We.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):qu(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})}}),sy=b("$ZodCheckNumberFormat",(t,e)=>{We.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Gu[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Xg)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}});var iy=b("$ZodCheckMaxLength",(t,e)=>{var r;We.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ws(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Ps(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),ay=b("$ZodCheckMinLength",(t,e)=>{var r;We.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ws(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Ps(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),cy=b("$ZodCheckLengthEquals",(t,e)=>{var r;We.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ws(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Ps(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),$s=b("$ZodCheckStringFormat",(t,e)=>{var r,n;We.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),uy=b("$ZodCheckRegex",(t,e)=>{$s.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})}}),ly=b("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ty),$s.init(t,e)}),dy=b("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=ry),$s.init(t,e)}),py=b("$ZodCheckIncludes",(t,e)=>{We.init(t,e);let r=Kr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),fy=b("$ZodCheckStartsWith",(t,e)=>{We.init(t,e);let r=new RegExp(`^${Kr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),my=b("$ZodCheckEndsWith",(t,e)=>{We.init(t,e);let r=new RegExp(`.*${Kr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var hy=b("$ZodCheckOverwrite",(t,e)=>{We.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var ca=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(`
|
|
191
|
-
`).filter(i=>i),o=Math.min(...
|
|
192
|
-
`))}};var
|
|
193
|
-
if (${
|
|
194
|
-
if (input[${
|
|
195
|
-
if (${
|
|
196
|
-
newResult[${
|
|
194
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.KIMI_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return FL(e,r),r}isExpectedHookEntry(e,n,r){return e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(n.command??"").replace(/\\/g,"/"),o=(hr[e]??"").replace(/\\/g,"/"),s=WL[e]??[];return r.includes(o)||s.some(i=>r.includes(i))}rebuildToml(e,n,r){let o=e.split(/\r?\n/),s=[],i=!1;for(let c of o){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(c)){i=!0;continue}if(i){/^\s*\[/.test(c)&&(i=!1,s.push(c));continue}s.push(c)}for(;s.length>0&&s[s.length-1]==="";)s.pop();s.length>0&&s.push("");let a=[...n,...r];if(a.length>0)for(let c of a)s.push(KL(c)),s.push("");return s.join(`
|
|
195
|
+
`)}}});var rg={};De(rg,{PLATFORM_ENV_VARS:()=>ps,__resetClaudeCodePluginCacheForTests:()=>YL,__seedClaudeCodePluginCacheMissForTests:()=>QL,detectPlatform:()=>vt,foreignIdentificationEnv:()=>r1,foreignWorkspaceEnv:()=>n1,getAdapter:()=>o1,getEnvVarNames:()=>t1,getSessionDirSegments:()=>Vi,workspaceEnvVarsFor:()=>ng});import{existsSync as Be,readFileSync as JL}from"node:fs";import{resolve as Ae}from"node:path";import{homedir as xw}from"node:os";function XL(){if(po!==null)return po!=="miss"&&po.hasCM;try{let t=Ae(xw(),".claude","plugins","installed_plugins.json"),e=JL(t,"utf-8"),n=JSON.parse(e),o=[...Object.keys(n.plugins??{}),...Object.keys(n.enabledPlugins??{})].some(s=>s.includes("context-mode"));return po={hasCM:o},o}catch{return po="miss",!1}}function YL(){po=null}function QL(){po="miss"}function t1(t){return(ps.get(t)??[]).map(e=>e.name)}function ng(t){return(ps.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function n1(t){let e=new Set;for(let[n,r]of ps)if(n!==t)for(let o of r)o.role==="workspace"&&e.add(o.name);return e}function r1(t){let e=new Set;for(let[n,r]of ps)if(n!==t)for(let o of r)o.role==="identification"&&e.add(o.name);return e}function Vi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"antigravity-cli":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"copilot-cli":return[".copilot"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kimi":return[".kimi-code"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function vt(t){if(t?.name){let s=av[t.name];if(s)return{platform:s,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","copilot-cli","cursor","antigravity","antigravity-cli","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[s,i]of ps)if(i.some(a=>a.detect!==!1&&process.env[a.name]))return s==="vscode-copilot"&&XL()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:s,confidence:"high",reason:`${i.filter(a=>a.detect!==!1).map(a=>a.name).join(" or ")} env var set`};let n=xw(),r=(()=>{let s=process.env.COPILOT_HOME;return s&&s.trim()!==""?s.startsWith("~")?Ae(n,s.replace(/^~[/\\]?/,"")):Ae(s):Ae(n,".copilot")})(),o=Be(Ae(r,"mcp-config.json"))||Be(Ae(r,"hooks","context-mode.json"));return process.env.COPILOT_HOME?.trim()&&o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in explicit COPILOT_HOME exists (mcp-config.json or hooks/context-mode.json)"}:Be(Ae(n,".local","bin","agy"))||Be(Ae(n,".gemini","antigravity-cli"))||Be(Ae(n,".gemini","config","mcp_config.json"))?{platform:"antigravity-cli",confidence:"medium",reason:"Antigravity CLI marker exists (~/.local/bin/agy, ~/.gemini/antigravity-cli, or ~/.gemini/config/mcp_config.json)"}:o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in Copilot CLI home exists (mcp-config.json or hooks/context-mode.json; honors COPILOT_HOME)"}:Be(Ae(n,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Be(Ae(n,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Be(Ae(n,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Be(Ae(n,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Be(Ae(n,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Be(Ae(n,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Be(Ae(n,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Be(Ae(n,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:Be(Ae(n,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Be(Ae(n,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Be(Ae(n,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Be(Ae(n,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Be(Ae(n,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Be(Ae(n,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function o1(t){let e=t??vt().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(ah(),ih));return new n}case"gemini-cli":{let{GeminiCLIAdapter:n}=await Promise.resolve().then(()=>(Hv(),Lv));return new n}case"kilo":case"opencode":{let{OpenCodeAdapter:n}=await Promise.resolve().then(()=>(Bv(),Zv));return new n(e)}case"openclaw":{let{OpenClawAdapter:n}=await Promise.resolve().then(()=>(Wv(),Vv));return new n}case"codex":{let{CodexAdapter:n}=await Promise.resolve().then(()=>(Sh(),oE));return new n}case"vscode-copilot":{let{VSCodeCopilotAdapter:n}=await Promise.resolve().then(()=>(lE(),uE));return new n}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:n}=await Promise.resolve().then(()=>(mE(),fE));return new n}case"copilot-cli":{let{CopilotCliAdapter:n}=await Promise.resolve().then(()=>(vE(),bE));return new n}case"cursor":{let{CursorAdapter:n}=await Promise.resolve().then(()=>(IE(),OE));return new n}case"antigravity":{let{AntigravityAdapter:n}=await Promise.resolve().then(()=>(Ah(),NE));return new n}case"antigravity-cli":{let{AntigravityCliAdapter:n}=await Promise.resolve().then(()=>(BE(),ZE));return new n}case"kiro":{let{KiroAdapter:n}=await Promise.resolve().then(()=>(XE(),JE));return new n}case"zed":{let{ZedAdapter:n}=await Promise.resolve().then(()=>(tw(),ew));return new n}case"qwen-code":{let{QwenCodeAdapter:n}=await Promise.resolve().then(()=>(iw(),sw));return new n}case"omp":{let{OMPAdapter:n}=await Promise.resolve().then(()=>(cw(),aw));return new n}case"pi":{let{PiAdapter:n}=await Promise.resolve().then(()=>(lw(),uw));return new n}case"kimi":{let{KimiAdapter:n}=await Promise.resolve().then(()=>(Sw(),_w));return new n}default:{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(ah(),ih));return new n}}}var po,e1,ps,fs=X(()=>{"use strict";cv();po=null;e1=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"},{name:"PI_CODING_AGENT",role:"identification"}]]],ps=new Map(e1)});import{resolve as Wi}from"node:path";import{homedir as og}from"node:os";function Rt(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Wi(og(),e.replace(/^~[/\\]?/,"")):Wi(e):Wi(og(),".claude")}function s1(t=process.env){return Wi(Rt(t),"settings.json")}function sg(t=process.env){let e=[],n=vt();if(n.platform!=="claude-code"){let o=Vi(n.platform);o&&o.length>0&&e.push(Wi(og(),...o,"settings.json"))}let r=s1(t);return e.includes(r)||e.push(r),e}var to=X(()=>{"use strict";fs()});var $={};De($,{BRAND:()=>dP,DIRTY:()=>_r,EMPTY_PATH:()=>ZT,INVALID:()=>B,NEVER:()=>KP,OK:()=>nt,ParseStatus:()=>Ve,Schema:()=>Q,ZodAny:()=>Wn,ZodArray:()=>Cn,ZodBigInt:()=>xr,ZodBoolean:()=>kr,ZodBranded:()=>Es,ZodCatch:()=>Ir,ZodDate:()=>br,ZodDefault:()=>Or,ZodDiscriminatedUnion:()=>sa,ZodEffects:()=>At,ZodEnum:()=>Cr,ZodError:()=>mt,ZodFirstPartyTypeKind:()=>w,ZodFunction:()=>aa,ZodIntersection:()=>Tr,ZodIssueCode:()=>E,ZodLazy:()=>Pr,ZodLiteral:()=>Rr,ZodMap:()=>So,ZodNaN:()=>ko,ZodNativeEnum:()=>$r,ZodNever:()=>Gt,ZodNull:()=>Er,ZodNullable:()=>pn,ZodNumber:()=>Sr,ZodObject:()=>gt,ZodOptional:()=>ht,ZodParsedType:()=>A,ZodPipeline:()=>ws,ZodPromise:()=>Kn,ZodReadonly:()=>Ar,ZodRecord:()=>ia,ZodSchema:()=>Q,ZodSet:()=>xo,ZodString:()=>Vn,ZodSymbol:()=>yo,ZodTransformer:()=>At,ZodTuple:()=>dn,ZodType:()=>Q,ZodUndefined:()=>vr,ZodUnion:()=>wr,ZodUnknown:()=>Rn,ZodVoid:()=>_o,addIssueToContext:()=>C,any:()=>xP,array:()=>EP,bigint:()=>hP,boolean:()=>Kg,coerce:()=>WP,custom:()=>qg,date:()=>gP,datetimeRegex:()=>Zg,defaultErrorMap:()=>Tn,discriminatedUnion:()=>PP,effect:()=>LP,enum:()=>MP,function:()=>AP,getErrorMap:()=>mo,getParsedType:()=>ln,instanceof:()=>fP,intersection:()=>RP,isAborted:()=>ra,isAsync:()=>ho,isDirty:()=>oa,isValid:()=>qn,late:()=>pP,lazy:()=>NP,literal:()=>DP,makeIssue:()=>vs,map:()=>OP,nan:()=>mP,nativeEnum:()=>jP,never:()=>bP,null:()=>SP,nullable:()=>UP,number:()=>Wg,object:()=>nl,objectUtil:()=>Qu,oboolean:()=>VP,onumber:()=>qP,optional:()=>HP,ostring:()=>BP,pipeline:()=>ZP,preprocess:()=>FP,promise:()=>zP,quotelessJson:()=>HT,record:()=>$P,set:()=>IP,setErrorMap:()=>FT,strictObject:()=>wP,string:()=>Vg,symbol:()=>yP,transformer:()=>LP,tuple:()=>CP,undefined:()=>_P,union:()=>TP,unknown:()=>kP,util:()=>oe,void:()=>vP});var oe;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(oe||(oe={}));var Qu;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Qu||(Qu={}));var A=oe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ln=t=>{switch(typeof t){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(t)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(t)?A.array:t===null?A.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?A.promise:typeof Map<"u"&&t instanceof Map?A.map:typeof Set<"u"&&t instanceof Set?A.set:typeof Date<"u"&&t instanceof Date?A.date:A.object;default:return A.unknown}};var E=oe.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"]),HT=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),mt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,oe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};mt.create=t=>new mt(t);var UT=(t,e)=>{let n;switch(t.code){case E.invalid_type:t.received===A.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,oe.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${oe.joinValues(t.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${oe.joinValues(t.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${oe.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:oe.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case E.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case E.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=e.defaultError,oe.assertNever(t)}return{message:n}},Tn=UT;var zg=Tn;function FT(t){zg=t}function mo(){return zg}var vs=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},ZT=[];function C(t,e){let n=mo(),r=vs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Tn?void 0:Tn].filter(o=>!!o)});t.common.issues.push(r)}var Ve=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return B;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return B;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},B=Object.freeze({status:"aborted"}),_r=t=>({status:"dirty",value:t}),nt=t=>({status:"valid",value:t}),ra=t=>t.status==="aborted",oa=t=>t.status==="dirty",qn=t=>t.status==="valid",ho=t=>typeof Promise<"u"&&t instanceof Promise;var z;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}));var It=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Lg=(t,e)=>{if(qn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new mt(t.common.issues);return this._error=n,this._error}}};function J(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}var Q=class{get description(){return this._def.description}_getType(e){return ln(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ln(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ve,ctx:{common:e.parent.common,data:e.data,parsedType:ln(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(ho(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ln(e)},o=this._parseSync({data:e,path:r.path,parent:r});return Lg(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ln(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return qn(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>qn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ln(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(ho(o)?o:Promise.resolve(o));return Lg(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:E.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new At({schema:this,typeName:w.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return ht.create(this,this._def)}nullable(){return pn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Cn.create(this)}promise(){return Kn.create(this,this._def)}or(e){return wr.create([this,e],this._def)}and(e){return Tr.create(this,e,this._def)}transform(e){return new At({...J(this._def),schema:this,typeName:w.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Or({...J(this._def),innerType:this,defaultValue:n,typeName:w.ZodDefault})}brand(){return new Es({typeName:w.ZodBranded,type:this,...J(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Ir({...J(this._def),innerType:this,catchValue:n,typeName:w.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ws.create(this,e)}readonly(){return Ar.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},BT=/^c[^\s-]{8,}$/i,qT=/^[0-9a-z]+$/,VT=/^[0-9A-HJKMNP-TV-Z]{26}$/i,WT=/^[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,KT=/^[a-z0-9_-]{21}$/i,GT=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,JT=/^[-+]?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)?)??$/,XT=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,YT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",el,QT=/^(?:(?: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])$/,eP=/^(?:(?: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])$/,tP=/^(([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]))$/,nP=/^(([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])$/,rP=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,oP=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ug="((\\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])))",sP=new RegExp(`^${Ug}$`);function Fg(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function iP(t){return new RegExp(`^${Fg(t)}$`)}function Zg(t){let e=`${Ug}T${Fg(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function aP(t,e){return!!((e==="v4"||!e)&&QT.test(t)||(e==="v6"||!e)&&tP.test(t))}function cP(t,e){if(!GT.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function uP(t,e){return!!((e==="v4"||!e)&&eP.test(t)||(e==="v6"||!e)&&nP.test(t))}var Vn=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==A.string){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_type,expected:A.string,received:s.parsedType}),B}let r=new Ve,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),C(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),C(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?C(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&C(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")XT.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"email",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")el||(el=new RegExp(YT,"u")),el.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"emoji",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")WT.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"uuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")KT.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"nanoid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")BT.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"cuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")qT.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"cuid2",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")VT.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"ulid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),C(o,{validation:"url",code:E.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"regex",code:E.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Zg(s).test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?sP.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?iP(s).test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?JT.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"duration",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?aP(e.data,s.version)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"ip",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?cP(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"jwt",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?uP(e.data,s.version)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"cidr",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?rP.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"base64",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?oP.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"base64url",code:E.invalid_string,message:s.message}),r.dirty()):oe.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:E.invalid_string,...z.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.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,...z.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,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...z.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...z.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...z.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...z.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...z.errToObj(n)})}nonempty(e){return this.min(1,z.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Vn.create=t=>new Vn({checks:[],typeName:w.ZodString,coerce:t?.coerce??!1,...J(t)});function lP(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var Sr=class t extends Q{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)!==A.number){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_type,expected:A.number,received:s.parsedType}),B}let r,o=new Ve;for(let s of this._def.checks)s.kind==="int"?oe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),C(r,{code:E.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),C(r,{code:E.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),C(r,{code:E.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?lP(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),C(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),C(r,{code:E.not_finite,message:s.message}),o.dirty()):oe.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,z.toString(n))}gt(e,n){return this.setLimit("min",e,!1,z.toString(n))}lte(e,n){return this.setLimit("max",e,!0,z.toString(n))}lt(e,n){return this.setLimit("max",e,!1,z.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:z.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&oe.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Sr.create=t=>new Sr({checks:[],typeName:w.ZodNumber,coerce:t?.coerce||!1,...J(t)});var xr=class t extends Q{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)!==A.bigint)return this._getInvalidInput(e);let r,o=new Ve;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),C(r,{code:E.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),C(r,{code:E.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),C(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):oe.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return C(n,{code:E.invalid_type,expected:A.bigint,received:n.parsedType}),B}gte(e,n){return this.setLimit("min",e,!0,z.toString(n))}gt(e,n){return this.setLimit("min",e,!1,z.toString(n))}lte(e,n){return this.setLimit("max",e,!0,z.toString(n))}lt(e,n){return this.setLimit("max",e,!1,z.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:z.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};xr.create=t=>new xr({checks:[],typeName:w.ZodBigInt,coerce:t?.coerce??!1,...J(t)});var kr=class extends Q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==A.boolean){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.boolean,received:r.parsedType}),B}return nt(e.data)}};kr.create=t=>new kr({typeName:w.ZodBoolean,coerce:t?.coerce||!1,...J(t)});var br=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==A.date){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_type,expected:A.date,received:s.parsedType}),B}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_date}),B}let r=new Ve,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),C(o,{code:E.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),C(o,{code:E.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):oe.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:z.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};br.create=t=>new br({checks:[],coerce:t?.coerce||!1,typeName:w.ZodDate,...J(t)});var yo=class extends Q{_parse(e){if(this._getType(e)!==A.symbol){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.symbol,received:r.parsedType}),B}return nt(e.data)}};yo.create=t=>new yo({typeName:w.ZodSymbol,...J(t)});var vr=class extends Q{_parse(e){if(this._getType(e)!==A.undefined){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.undefined,received:r.parsedType}),B}return nt(e.data)}};vr.create=t=>new vr({typeName:w.ZodUndefined,...J(t)});var Er=class extends Q{_parse(e){if(this._getType(e)!==A.null){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.null,received:r.parsedType}),B}return nt(e.data)}};Er.create=t=>new Er({typeName:w.ZodNull,...J(t)});var Wn=class extends Q{constructor(){super(...arguments),this._any=!0}_parse(e){return nt(e.data)}};Wn.create=t=>new Wn({typeName:w.ZodAny,...J(t)});var Rn=class extends Q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return nt(e.data)}};Rn.create=t=>new Rn({typeName:w.ZodUnknown,...J(t)});var Gt=class extends Q{_parse(e){let n=this._getOrReturnCtx(e);return C(n,{code:E.invalid_type,expected:A.never,received:n.parsedType}),B}};Gt.create=t=>new Gt({typeName:w.ZodNever,...J(t)});var _o=class extends Q{_parse(e){if(this._getType(e)!==A.undefined){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.void,received:r.parsedType}),B}return nt(e.data)}};_o.create=t=>new _o({typeName:w.ZodVoid,...J(t)});var Cn=class t extends Q{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==A.array)return C(n,{code:E.invalid_type,expected:A.array,received:n.parsedType}),B;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(C(n,{code:i?E.too_big:E.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(C(n,{code:E.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(C(n,{code:E.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new It(n,i,n.path,a)))).then(i=>Ve.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new It(n,i,n.path,a)));return Ve.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:z.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:z.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:z.toString(n)}})}nonempty(e){return this.min(1,e)}};Cn.create=(t,e)=>new Cn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:w.ZodArray,...J(e)});function go(t){if(t instanceof gt){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=ht.create(go(r))}return new gt({...t._def,shape:()=>e})}else return t instanceof Cn?new Cn({...t._def,type:go(t.element)}):t instanceof ht?ht.create(go(t.unwrap())):t instanceof pn?pn.create(go(t.unwrap())):t instanceof dn?dn.create(t.items.map(e=>go(e))):t}var gt=class t extends Q{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=oe.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==A.object){let u=this._getOrReturnCtx(e);return C(u,{code:E.invalid_type,expected:A.object,received:u.parsedType}),B}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Gt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new It(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Gt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(C(o,{code:E.unrecognized_keys,keys:a}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new It(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Ve.mergeObjectSync(r,u)):Ve.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:z.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:w.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of oe.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of oe.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return go(this)}partial(e){let n={};for(let r of oe.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of oe.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof ht;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return Bg(oe.objectKeys(this.shape))}};gt.create=(t,e)=>new gt({shape:()=>t,unknownKeys:"strip",catchall:Gt.create(),typeName:w.ZodObject,...J(e)});gt.strictCreate=(t,e)=>new gt({shape:()=>t,unknownKeys:"strict",catchall:Gt.create(),typeName:w.ZodObject,...J(e)});gt.lazycreate=(t,e)=>new gt({shape:t,unknownKeys:"strip",catchall:Gt.create(),typeName:w.ZodObject,...J(e)});var wr=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new mt(a.ctx.common.issues));return C(n,{code:E.invalid_union,unionErrors:i}),B}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new mt(c));return C(n,{code:E.invalid_union,unionErrors:a}),B}}get options(){return this._def.options}};wr.create=(t,e)=>new wr({options:t,typeName:w.ZodUnion,...J(e)});var Pn=t=>t instanceof Pr?Pn(t.schema):t instanceof At?Pn(t.innerType()):t instanceof Rr?[t.value]:t instanceof Cr?t.options:t instanceof $r?oe.objectValues(t.enum):t instanceof Or?Pn(t._def.innerType):t instanceof vr?[void 0]:t instanceof Er?[null]:t instanceof ht?[void 0,...Pn(t.unwrap())]:t instanceof pn?[null,...Pn(t.unwrap())]:t instanceof Es||t instanceof Ar?Pn(t.unwrap()):t instanceof Ir?Pn(t._def.innerType):[],sa=class t extends Q{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==A.object)return C(n,{code:E.invalid_type,expected:A.object,received:n.parsedType}),B;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(C(n,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),B)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=Pn(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:w.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...J(r)})}};function tl(t,e){let n=ln(t),r=ln(e);if(t===e)return{valid:!0,data:t};if(n===A.object&&r===A.object){let o=oe.objectKeys(e),s=oe.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=tl(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===A.array&&r===A.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=tl(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===A.date&&r===A.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Tr=class extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(ra(s)||ra(i))return B;let a=tl(s.value,i.value);return a.valid?((oa(s)||oa(i))&&n.dirty(),{status:n.value,value:a.data}):(C(r,{code:E.invalid_intersection_types}),B)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Tr.create=(t,e,n)=>new Tr({left:t,right:e,typeName:w.ZodIntersection,...J(n)});var dn=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.array)return C(r,{code:E.invalid_type,expected:A.array,received:r.parsedType}),B;if(r.data.length<this._def.items.length)return C(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),B;!this._def.rest&&r.data.length>this._def.items.length&&(C(r,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new It(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>Ve.mergeArray(n,i)):Ve.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};dn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new dn({items:t,typeName:w.ZodTuple,rest:null,...J(e)})};var ia=class t extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.object)return C(r,{code:E.invalid_type,expected:A.object,received:r.parsedType}),B;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new It(r,a,r.path,a)),value:i._parse(new It(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ve.mergeObjectAsync(n,o):Ve.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Q?new t({keyType:e,valueType:n,typeName:w.ZodRecord,...J(r)}):new t({keyType:Vn.create(),valueType:e,typeName:w.ZodRecord,...J(n)})}},So=class extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.map)return C(r,{code:E.invalid_type,expected:A.map,received:r.parsedType}),B;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],u)=>({key:o._parse(new It(r,a,r.path,[u,"key"])),value:s._parse(new It(r,c,r.path,[u,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return B;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return B;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}};So.create=(t,e,n)=>new So({valueType:e,keyType:t,typeName:w.ZodMap,...J(n)});var xo=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.set)return C(r,{code:E.invalid_type,expected:A.set,received:r.parsedType}),B;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(C(r,{code:E.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(C(r,{code:E.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return B;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let a=[...r.data.values()].map((c,u)=>s._parse(new It(r,c,r.path,u)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:z.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:z.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};xo.create=(t,e)=>new xo({valueType:t,minSize:null,maxSize:null,typeName:w.ZodSet,...J(e)});var aa=class t extends Q{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==A.function)return C(n,{code:E.invalid_type,expected:A.function,received:n.parsedType}),B;function r(a,c){return vs({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,mo(),Tn].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function o(a,c){return vs({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,mo(),Tn].filter(u=>!!u),issueData:{code:E.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Kn){let a=this;return nt(async function(...c){let u=new mt([]),l=await a._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(r(c,m)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(o(d,m)),u})})}else{let a=this;return nt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new mt([r(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new mt([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:dn.create(e).rest(Rn.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||dn.create([]).rest(Rn.create()),returns:n||Rn.create(),typeName:w.ZodFunction,...J(r)})}},Pr=class extends Q{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Pr.create=(t,e)=>new Pr({getter:t,typeName:w.ZodLazy,...J(e)});var Rr=class extends Q{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return C(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),B}return{status:"valid",value:e.data}}get value(){return this._def.value}};Rr.create=(t,e)=>new Rr({value:t,typeName:w.ZodLiteral,...J(e)});function Bg(t,e){return new Cr({values:t,typeName:w.ZodEnum,...J(e)})}var Cr=class t extends Q{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return C(n,{expected:oe.joinValues(r),received:n.parsedType,code:E.invalid_type}),B}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return C(n,{received:n.data,code:E.invalid_enum_value,options:r}),B}return nt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Cr.create=Bg;var $r=class extends Q{_parse(e){let n=oe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==A.string&&r.parsedType!==A.number){let o=oe.objectValues(n);return C(r,{expected:oe.joinValues(o),received:r.parsedType,code:E.invalid_type}),B}if(this._cache||(this._cache=new Set(oe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=oe.objectValues(n);return C(r,{received:r.data,code:E.invalid_enum_value,options:o}),B}return nt(e.data)}get enum(){return this._def.values}};$r.create=(t,e)=>new $r({values:t,typeName:w.ZodNativeEnum,...J(e)});var Kn=class extends Q{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==A.promise&&n.common.async===!1)return C(n,{code:E.invalid_type,expected:A.promise,received:n.parsedType}),B;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return nt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Kn.create=(t,e)=>new Kn({type:t,typeName:w.ZodPromise,...J(e)});var At=class extends Q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===w.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{C(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return B;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?B:c.status==="dirty"?_r(c.value):n.value==="dirty"?_r(c.value):c});{if(n.value==="aborted")return B;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?B:a.status==="dirty"?_r(a.value):n.value==="dirty"?_r(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?B:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?B:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!qn(i))return B;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>qn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):B);oe.assertNever(o)}};At.create=(t,e,n)=>new At({schema:t,typeName:w.ZodEffects,effect:e,...J(n)});At.createWithPreprocess=(t,e,n)=>new At({schema:e,effect:{type:"preprocess",transform:t},typeName:w.ZodEffects,...J(n)});var ht=class extends Q{_parse(e){return this._getType(e)===A.undefined?nt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ht.create=(t,e)=>new ht({innerType:t,typeName:w.ZodOptional,...J(e)});var pn=class extends Q{_parse(e){return this._getType(e)===A.null?nt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};pn.create=(t,e)=>new pn({innerType:t,typeName:w.ZodNullable,...J(e)});var Or=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===A.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Or.create=(t,e)=>new Or({innerType:t,typeName:w.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});var Ir=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ho(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new mt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new mt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ir.create=(t,e)=>new Ir({innerType:t,typeName:w.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});var ko=class extends Q{_parse(e){if(this._getType(e)!==A.nan){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.nan,received:r.parsedType}),B}return{status:"valid",value:e.data}}};ko.create=t=>new ko({typeName:w.ZodNaN,...J(t)});var dP=Symbol("zod_brand"),Es=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},ws=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?B:s.status==="dirty"?(n.dirty(),_r(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?B:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:w.ZodPipeline})}},Ar=class extends Q{_parse(e){let n=this._def.innerType._parse(e),r=o=>(qn(o)&&(o.value=Object.freeze(o.value)),o);return ho(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Ar.create=(t,e)=>new Ar({innerType:t,typeName:w.ZodReadonly,...J(e)});function Hg(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function qg(t,e={},n){return t?Wn.create().superRefine((r,o)=>{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Hg(e,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Hg(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Wn.create()}var pP={object:gt.lazycreate},w;(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"})(w||(w={}));var fP=(t,e={message:`Input not instance of ${t.name}`})=>qg(n=>n instanceof t,e),Vg=Vn.create,Wg=Sr.create,mP=ko.create,hP=xr.create,Kg=kr.create,gP=br.create,yP=yo.create,_P=vr.create,SP=Er.create,xP=Wn.create,kP=Rn.create,bP=Gt.create,vP=_o.create,EP=Cn.create,nl=gt.create,wP=gt.strictCreate,TP=wr.create,PP=sa.create,RP=Tr.create,CP=dn.create,$P=ia.create,OP=So.create,IP=xo.create,AP=aa.create,NP=Pr.create,DP=Rr.create,MP=Cr.create,jP=$r.create,zP=Kn.create,LP=At.create,HP=ht.create,UP=pn.create,FP=At.createWithPreprocess,ZP=ws.create,BP=()=>Vg().optional(),qP=()=>Wg().optional(),VP=()=>Kg().optional(),WP={string:(t=>Vn.create({...t,coerce:!0})),number:(t=>Sr.create({...t,coerce:!0})),boolean:(t=>kr.create({...t,coerce:!0})),bigint:(t=>xr.create({...t,coerce:!0})),date:(t=>br.create({...t,coerce:!0}))};var KP=B;var GP=Object.freeze({status:"aborted"});function b(t,e,n){function r(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var $n=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ca={};function wt(t){return t&&Object.assign(ca,t),ca}var se={};De(se,{BIGINT_FORMAT_RANGES:()=>Jg,Class:()=>ol,NUMBER_FORMAT_RANGES:()=>dl,aborted:()=>Dr,allowsEval:()=>cl,assert:()=>eR,assertEqual:()=>JP,assertIs:()=>YP,assertNever:()=>QP,assertNotEqual:()=>XP,assignProp:()=>al,cached:()=>Rs,captureStackTrace:()=>la,cleanEnum:()=>fR,cleanRegex:()=>$s,clone:()=>Tt,createTransparentProxy:()=>iR,defineLazy:()=>Se,esc:()=>Nr,escapeRegex:()=>Gn,extend:()=>uR,finalizeIssue:()=>Jt,floatSafeRemainder:()=>il,getElementAtPath:()=>tR,getEnumValues:()=>Ps,getLengthableOrigin:()=>Os,getParsedType:()=>sR,getSizableOrigin:()=>Xg,isObject:()=>bo,isPlainObject:()=>vo,issue:()=>pl,joinValues:()=>ua,jsonStringifyReplacer:()=>sl,merge:()=>lR,normalizeParams:()=>q,nullish:()=>Cs,numKeys:()=>oR,omit:()=>cR,optionalKeys:()=>ll,partial:()=>dR,pick:()=>aR,prefixIssues:()=>fn,primitiveTypes:()=>Gg,promiseAllObject:()=>nR,propertyKeyTypes:()=>ul,randomString:()=>rR,required:()=>pR,stringifyPrimitive:()=>da,unwrapMessage:()=>Ts});function JP(t){return t}function XP(t){return t}function YP(t){}function QP(t){throw new Error}function eR(t){}function Ps(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function ua(t,e="|"){return t.map(n=>da(n)).join(e)}function sl(t,e){return typeof e=="bigint"?e.toString():e}function Rs(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Cs(t){return t==null}function $s(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function il(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Se(t,e,n){Object.defineProperty(t,e,{get(){{let o=n();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function al(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function tR(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function nR(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function rR(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Nr(t){return JSON.stringify(t)}var la=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function bo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var cl=Rs(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function vo(t){if(bo(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(bo(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function oR(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var sR=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}`)}},ul=new Set(["string","number","symbol"]),Gg=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Gn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tt(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function q(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 iR(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function da(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function ll(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var dl={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]},Jg={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function aR(t,e){let n={},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(n[o]=r.shape[o])}return Tt(t,{...t._zod.def,shape:n,checks:[]})}function cR(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete n[o]}return Tt(t,{...t._zod.def,shape:n,checks:[]})}function uR(t,e){if(!vo(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return al(this,"shape",r),r},checks:[]};return Tt(t,n)}function lR(t,e){return Tt(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return al(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function dR(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=t?new t({type:"optional",innerType:r[s]}):r[s])}else for(let s in r)o[s]=t?new t({type:"optional",innerType:r[s]}):r[s];return Tt(e,{...e._zod.def,shape:o,checks:[]})}function pR(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(let s in r)o[s]=new t({type:"nonoptional",innerType:r[s]});return Tt(e,{...e._zod.def,shape:o,checks:[]})}function Dr(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function fn(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Ts(t){return typeof t=="string"?t:t?.message}function Jt(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let o=Ts(t.inst?._zod.def?.error?.(t))??Ts(e?.error?.(t))??Ts(n.customError?.(t))??Ts(n.localeError?.(t))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function Xg(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Os(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function pl(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function fR(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var ol=class{constructor(...e){}};var Yg=(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,sl,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},pa=b("$ZodError",Yg),Is=b("$ZodError",Yg,{Parent:Error});function fl(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function ml(t,e){let n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),r}var hl=t=>(e,n,r,o)=>{let s=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new $n;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Jt(c,s,wt())));throw la(a,o?.callee),a}return i.value},gl=hl(Is),yl=t=>async(e,n,r,o)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Jt(c,s,wt())));throw la(a,o?.callee),a}return i.value},_l=yl(Is),Sl=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new $n;return s.issues.length?{success:!1,error:new(t??pa)(s.issues.map(i=>Jt(i,o,wt())))}:{success:!0,data:s.value}},Mr=Sl(Is),xl=t=>async(e,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Jt(i,o,wt())))}:{success:!0,data:s.value}},jr=xl(Is);var Qg=/^[cC][^\s-]{8,}$/,ey=/^[0-9a-z]+$/,ty=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ny=/^[0-9a-vA-V]{20}$/,ry=/^[A-Za-z0-9]{27}$/,oy=/^[a-zA-Z0-9_-]{21}$/,sy=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var iy=/^([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})$/,kl=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)$/;var ay=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var hR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function cy(){return new RegExp(hR,"u")}var uy=/^(?:(?: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])$/,ly=/^(([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})$/,dy=/^((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])$/,py=/^(([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])$/,fy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,bl=/^[A-Za-z0-9_-]*$/,my=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var hy=/^\+(?:[0-9]){6,14}[0-9]$/,gy="(?:(?:\\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])))",yy=new RegExp(`^${gy}$`);function _y(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 Sy(t){return new RegExp(`^${_y(t)}$`)}function xy(t){let e=_y({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${gy}T(?:${r})$`)}var ky=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var by=/^\d+$/,vy=/^-?\d+(?:\.\d+)?/i,Ey=/true|false/i,wy=/null/i;var Ty=/^[^A-Z]*$/,Py=/^[^a-z]*$/;var We=b("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Ry={number:"number",bigint:"bigint",object:"date"},vl=b("$ZodCheckLessThan",(t,e)=>{We.init(t,e);let n=Ry[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),El=b("$ZodCheckGreaterThan",(t,e)=>{We.init(t,e);let n=Ry[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Cy=b("$ZodCheckMultipleOf",(t,e)=>{We.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):il(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),$y=b("$ZodCheckNumberFormat",(t,e)=>{We.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=dl[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=by)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}});var Oy=b("$ZodCheckMaxLength",(t,e)=>{var n;We.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Cs(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let i=Os(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Iy=b("$ZodCheckMinLength",(t,e)=>{var n;We.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Cs(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=Os(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ay=b("$ZodCheckLengthEquals",(t,e)=>{var n;We.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Cs(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=Os(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),As=b("$ZodCheckStringFormat",(t,e)=>{var n,r;We.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Ny=b("$ZodCheckRegex",(t,e)=>{As.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Dy=b("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ty),As.init(t,e)}),My=b("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Py),As.init(t,e)}),jy=b("$ZodCheckIncludes",(t,e)=>{We.init(t,e);let n=Gn(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),zy=b("$ZodCheckStartsWith",(t,e)=>{We.init(t,e);let n=new RegExp(`^${Gn(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Ly=b("$ZodCheckEndsWith",(t,e)=>{We.init(t,e);let n=new RegExp(`.*${Gn(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});var Hy=b("$ZodCheckOverwrite",(t,e)=>{We.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var ma=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
|
|
196
|
+
`).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...n,o.join(`
|
|
197
|
+
`))}};var Fy={major:4,minor:0,patch:0};var me=b("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Fy;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Dr(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,f=l._zod.check(s);if(f instanceof Promise&&a?.async===!1)throw new $n;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,s.issues.length!==d&&(c||(c=Dr(s,d)))});else{if(s.issues.length===d)continue;c||(c=Dr(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new $n;return a.then(c=>o(c,r,i))}return o(a,r,i)}}t["~standard"]={validate:o=>{try{let s=Mr(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return jr(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Ns=b("$ZodString",(t,e)=>{me.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??ky(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),xe=b("$ZodStringFormat",(t,e)=>{As.init(t,e),Ns.init(t,e)}),Tl=b("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=iy),xe.init(t,e)}),Pl=b("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=kl(r))}else e.pattern??(e.pattern=kl());xe.init(t,e)}),Rl=b("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=ay),xe.init(t,e)}),Cl=b("$ZodURL",(t,e)=>{xe.init(t,e),t._zod.check=n=>{try{let r=n.value,o=new URL(r),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:my.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),$l=b("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=cy()),xe.init(t,e)}),Ol=b("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=oy),xe.init(t,e)}),Il=b("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Qg),xe.init(t,e)}),Al=b("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ey),xe.init(t,e)}),Nl=b("$ZodULID",(t,e)=>{e.pattern??(e.pattern=ty),xe.init(t,e)}),Dl=b("$ZodXID",(t,e)=>{e.pattern??(e.pattern=ny),xe.init(t,e)}),Ml=b("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=ry),xe.init(t,e)}),Yy=b("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=xy(e)),xe.init(t,e)}),Qy=b("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=yy),xe.init(t,e)}),e_=b("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Sy(e)),xe.init(t,e)}),t_=b("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=sy),xe.init(t,e)}),jl=b("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=uy),xe.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),zl=b("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=ly),xe.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),Ll=b("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=dy),xe.init(t,e)}),Hl=b("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=py),xe.init(t,e),t._zod.check=n=>{let[r,o]=n.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function n_(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Ul=b("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=fy),xe.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{n_(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function gR(t){if(!bl.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return n_(n)}var Fl=b("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=bl),xe.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{gR(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Zl=b("$ZodE164",(t,e)=>{e.pattern??(e.pattern=hy),xe.init(t,e)});function yR(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var Bl=b("$ZodJWT",(t,e)=>{xe.init(t,e),t._zod.check=n=>{yR(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var ga=b("$ZodNumber",(t,e)=>{me.init(t,e),t._zod.pattern=t._zod.bag.pattern??vy,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),n}}),ql=b("$ZodNumber",(t,e)=>{$y.init(t,e),ga.init(t,e)}),Vl=b("$ZodBoolean",(t,e)=>{me.init(t,e),t._zod.pattern=Ey,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}});var Wl=b("$ZodNull",(t,e)=>{me.init(t,e),t._zod.pattern=wy,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}});var Kl=b("$ZodUnknown",(t,e)=>{me.init(t,e),t._zod.parse=n=>n}),Gl=b("$ZodNever",(t,e)=>{me.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function Zy(t,e,n){t.issues.length&&e.issues.push(...fn(n,t.issues)),e.value[n]=t.value}var Jl=b("$ZodArray",(t,e)=>{me.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},r);c instanceof Promise?s.push(c.then(u=>Zy(u,n,i))):Zy(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function ha(t,e,n){t.issues.length&&e.issues.push(...fn(n,t.issues)),e.value[n]=t.value}function By(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...fn(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}var ya=b("$ZodObject",(t,e)=>{me.init(t,e);let n=Rs(()=>{let d=Object.keys(e.shape);for(let m of d)if(!(e.shape[m]instanceof me))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let f=ll(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});Se(t._zod,"propValues",()=>{let d=e.shape,f={};for(let m in d){let p=d[m]._zod;if(p.values){f[m]??(f[m]=new Set);for(let h of p.values)f[m].add(h)}}return f});let r=d=>{let f=new ma(["shape","payload","ctx"]),m=n.value,p=_=>{let S=Nr(_);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),g=0;for(let _ of m.keys)h[_]=`key_${g++}`;f.write("const newResult = {}");for(let _ of m.keys)if(m.optionalKeys.has(_)){let S=h[_];f.write(`const ${S} = ${p(_)};`);let k=Nr(_);f.write(`
|
|
198
|
+
if (${S}.issues.length) {
|
|
199
|
+
if (input[${k}] === undefined) {
|
|
200
|
+
if (${k} in input) {
|
|
201
|
+
newResult[${k}] = undefined;
|
|
197
202
|
}
|
|
198
203
|
} else {
|
|
199
204
|
payload.issues = payload.issues.concat(
|
|
200
|
-
${
|
|
205
|
+
${S}.issues.map((iss) => ({
|
|
201
206
|
...iss,
|
|
202
|
-
path: iss.path ? [${
|
|
207
|
+
path: iss.path ? [${k}, ...iss.path] : [${k}],
|
|
203
208
|
}))
|
|
204
209
|
);
|
|
205
210
|
}
|
|
206
|
-
} else if (${
|
|
207
|
-
if (${
|
|
211
|
+
} else if (${S}.value === undefined) {
|
|
212
|
+
if (${k} in input) newResult[${k}] = undefined;
|
|
208
213
|
} else {
|
|
209
|
-
newResult[${
|
|
214
|
+
newResult[${k}] = ${S}.value;
|
|
210
215
|
}
|
|
211
|
-
`)}else{let
|
|
212
|
-
if (${
|
|
216
|
+
`)}else{let S=h[_];f.write(`const ${S} = ${p(_)};`),f.write(`
|
|
217
|
+
if (${S}.issues.length) payload.issues = payload.issues.concat(${S}.issues.map(iss => ({
|
|
213
218
|
...iss,
|
|
214
|
-
path: iss.path ? [${
|
|
215
|
-
})));`),f.write(`newResult[${An(_)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(_,x)=>y(d,_,x)},o,s=So,i=!ra.jitless,c=i&&Vu.value,u=e.catchall,l;t._zod.parse=(d,f)=>{l??(l=r.value);let h=d.value;if(!s(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d;let p=[];if(i&&c&&f?.async===!1&&f.jitless!==!0)o||(o=n(e.shape)),d=o(d,f);else{d.value={};let x=l.shape;for(let S of l.keys){let k=x[S],R=k._zod.run({value:h[S],issues:[]},f),$=k._zod.optin==="optional"&&k._zod.optout==="optional";R instanceof Promise?p.push(R.then(C=>$?xy(C,d,S,h):ua(C,d,S))):$?xy(R,d,S,h):ua(R,d,S)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;let m=[],g=l.keySet,y=u._zod,_=y.def.type;for(let x of Object.keys(h)){if(g.has(x))continue;if(_==="never"){m.push(x);continue}let S=y.run({value:h[x],issues:[]},f);S instanceof Promise?p.push(S.then(k=>ua(k,d,x))):ua(S,d,x)}return m.length&&d.issues.push({code:"unrecognized_keys",keys:m,input:h,inst:t}),p.length?Promise.all(p).then(()=>d):d}});function Sy(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>Gt(s,n,bt())))}),e}var pa=b("$ZodUnion",(t,e)=>{me.init(t,e),Se(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Se(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Se(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Se(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=>Ts(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Sy(i,r,t,n)):Sy(s,r,t,n)}}),Dl=b("$ZodDiscriminatedUnion",(t,e)=>{pa.init(t,e);let r=t._zod.parse;Se(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Es(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!So(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Ml=b("$ZodIntersection",(t,e)=>{me.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>vy(r,c,u)):vy(r,s,i)}});function ul(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(vo(t)&&vo(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=ul(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=ul(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function vy(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Nn(t))return t;let n=ul(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var jl=b("$ZodRecord",(t,e)=>{me.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!vo(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...pr(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...pr(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>Gt(u,n,bt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...pr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...pr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var zl=b("$ZodEnum",(t,e)=>{me.init(t,e);let r=ks(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Wu.has(typeof n)).map(n=>typeof n=="string"?Kr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Ll=b("$ZodLiteral",(t,e)=>{me.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Kr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var Hl=b("$ZodTransform",(t,e)=>{me.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Rr;return r.value=o,r}}),Ul=b("$ZodOptional",(t,e)=>{me.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Se(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Se(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ts(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)}),Fl=b("$ZodNullable",(t,e)=>{me.init(t,e),Se(t._zod,"optin",()=>e.innerType._zod.optin),Se(t._zod,"optout",()=>e.innerType._zod.optout),Se(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ts(r.source)}|null)$`):void 0}),Se(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)}),Zl=b("$ZodDefault",(t,e)=>{me.init(t,e),t._zod.optin="optional",Se(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>by(s,e)):by(o,e)}});function by(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var ql=b("$ZodPrefault",(t,e)=>{me.init(t,e),t._zod.optin="optional",Se(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))}),Bl=b("$ZodNonOptional",(t,e)=>{me.init(t,e),Se(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>ky(s,t)):ky(o,t)}});function ky(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Vl=b("$ZodCatch",(t,e)=>{me.init(t,e),t._zod.optin="optional",Se(t._zod,"optout",()=>e.innerType._zod.optout),Se(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Gt(i,n,bt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Gt(s,n,bt()))},input:r.value}),r.issues=[]),r)}});var Wl=b("$ZodPipe",(t,e)=>{me.init(t,e),Se(t._zod,"values",()=>e.in._zod.values),Se(t._zod,"optin",()=>e.in._zod.optin),Se(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Ey(s,e,n)):Ey(o,e,n)}});function Ey(t,e,r){return Nn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Kl=b("$ZodReadonly",(t,e)=>{me.init(t,e),Se(t._zod,"propValues",()=>e.innerType._zod.propValues),Se(t._zod,"values",()=>e.innerType._zod.values),Se(t._zod,"optin",()=>e.innerType._zod.optin),Se(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(wy):wy(o)}});function wy(t){return t.value=Object.freeze(t.value),t}var Gl=b("$ZodCustom",(t,e)=>{We.init(t,e),me.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>Ty(s,r,n,t));Ty(o,r,n,t)}});function Ty(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Ju(o))}}var wP=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},TP=()=>{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 ${wP(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${sa(n.values[0])}`:`Invalid option: expected one of ${na(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${na(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"}}};function Iy(){return{localeError:TP()}}var Os=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)}};function Ay(){return new Os}var Gr=Ay();function Jl(t,e){return new t({type:"string",...V(e)})}function Xl(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...V(e)})}function fa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...V(e)})}function Yl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...V(e)})}function Ql(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...V(e)})}function ed(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...V(e)})}function td(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...V(e)})}function rd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...V(e)})}function nd(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...V(e)})}function od(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...V(e)})}function sd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...V(e)})}function id(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...V(e)})}function ad(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...V(e)})}function cd(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...V(e)})}function ud(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...V(e)})}function ld(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...V(e)})}function dd(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...V(e)})}function pd(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...V(e)})}function fd(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...V(e)})}function md(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...V(e)})}function hd(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...V(e)})}function gd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...V(e)})}function yd(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...V(e)})}function Ny(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...V(e)})}function Dy(t,e){return new t({type:"string",format:"date",check:"string_format",...V(e)})}function My(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...V(e)})}function jy(t,e){return new t({type:"string",format:"duration",check:"string_format",...V(e)})}function _d(t,e){return new t({type:"number",checks:[],...V(e)})}function xd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...V(e)})}function Sd(t,e){return new t({type:"boolean",...V(e)})}function vd(t,e){return new t({type:"null",...V(e)})}function bd(t){return new t({type:"unknown"})}function kd(t,e){return new t({type:"never",...V(e)})}function ma(t,e){return new al({check:"less_than",...V(e),value:t,inclusive:!1})}function Is(t,e){return new al({check:"less_than",...V(e),value:t,inclusive:!0})}function ha(t,e){return new cl({check:"greater_than",...V(e),value:t,inclusive:!1})}function As(t,e){return new cl({check:"greater_than",...V(e),value:t,inclusive:!0})}function ga(t,e){return new oy({check:"multiple_of",...V(e),value:t})}function ya(t,e){return new iy({check:"max_length",...V(e),maximum:t})}function bo(t,e){return new ay({check:"min_length",...V(e),minimum:t})}function _a(t,e){return new cy({check:"length_equals",...V(e),length:t})}function Ed(t,e){return new uy({check:"string_format",format:"regex",...V(e),pattern:t})}function wd(t){return new ly({check:"string_format",format:"lowercase",...V(t)})}function Td(t){return new dy({check:"string_format",format:"uppercase",...V(t)})}function Pd(t,e){return new py({check:"string_format",format:"includes",...V(e),includes:t})}function Rd(t,e){return new fy({check:"string_format",format:"starts_with",...V(e),prefix:t})}function $d(t,e){return new my({check:"string_format",format:"ends_with",...V(e),suffix:t})}function jn(t){return new hy({check:"overwrite",tx:t})}function Cd(t){return jn(e=>e.normalize(t))}function Od(){return jn(t=>t.trim())}function Id(){return jn(t=>t.toLowerCase())}function Ad(){return jn(t=>t.toUpperCase())}function zy(t,e,r){return new t({type:"array",element:e,...V(r)})}function Nd(t,e,r){let n=V(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Dd(t,e,r){return new t({type:"custom",check:"custom",fn:e,...V(r)})}var xa=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Gr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},f=e._zod.parent;if(f)a.ref=f,this.process(f,d),this.seen.get(f).isParent=!0;else{let h=a.schema;switch(o.type){case"string":{let p=h;p.type="string";let{minimum:m,maximum:g,format:y,patterns:_,contentEncoding:x}=e._zod.bag;if(typeof m=="number"&&(p.minLength=m),typeof g=="number"&&(p.maxLength=g),y&&(p.format=s[y]??y,p.format===""&&delete p.format),x&&(p.contentEncoding=x),_&&_.size>0){let S=[..._];S.length===1?p.pattern=S[0].source:S.length>1&&(a.schema.allOf=[...S.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{let p=h,{minimum:m,maximum:g,format:y,multipleOf:_,exclusiveMaximum:x,exclusiveMinimum:S}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof S=="number"&&(p.exclusiveMinimum=S),typeof m=="number"&&(p.minimum=m,typeof S=="number"&&(S>=m?delete p.minimum:delete p.exclusiveMinimum)),typeof x=="number"&&(p.exclusiveMaximum=x),typeof g=="number"&&(p.maximum=g,typeof x=="number"&&(x<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);break}case"boolean":{let p=h;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":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=h,{minimum:m,maximum:g}=e._zod.bag;typeof m=="number"&&(p.minItems=m),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let p=h;p.type="object",p.properties={};let m=o.shape;for(let _ in m)p.properties[_]=this.process(m[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(m)),y=new Set([...g].filter(_=>{let x=o.shape[_]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));y.size>0&&(p.required=Array.from(y)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=h;p.anyOf=o.options.map((m,g)=>this.process(m,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let p=h,m=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=x=>"allOf"in x&&Object.keys(x).length===1,_=[...y(m)?m.allOf:[m],...y(g)?g.allOf:[g]];p.allOf=_;break}case"tuple":{let p=h;p.type="array";let m=o.items.map((_,x)=>this.process(_,{...d,path:[...d.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?p.prefixItems=m:p.items=m,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}o.rest&&(p.items=this.process(o.rest,{...d,path:[...d.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=h;p.type="object",p.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=h,m=ks(o.entries);m.every(g=>typeof g=="number")&&(p.type="number"),m.every(g=>typeof g=="string")&&(p.type="string"),p.enum=m;break}case"literal":{let p=h,m=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");m.push(Number(g))}else m.push(g);if(m.length!==0)if(m.length===1){let g=m[0];p.type=g===null?"null":typeof g,p.const=g}else m.every(g=>typeof g=="number")&&(p.type="number"),m.every(g=>typeof g=="string")&&(p.type="string"),m.every(g=>typeof g=="boolean")&&(p.type="string"),m.every(g=>g===null)&&(p.type="null"),p.enum=m;break}case"file":{let p=h,m={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(m.minLength=g),y!==void 0&&(m.maxLength=y),_?_.length===1?(m.contentMediaType=_[0],Object.assign(p,m)):p.anyOf=_.map(x=>({...m,contentMediaType:x})):Object.assign(p,m);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(o.innerType,d);h.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let p=h;p.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.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=h,m=e._zod.pattern;if(!m)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=m.source;break}case"pipe":{let p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,d),a.ref=p;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,d),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"&&Ue(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let m=n.external.registry.get(l[0])?.id,g=n.external.uri??(_=>_);if(m)return{ref:g(m)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===o)return{ref:"#"};let h=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:h+p}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:f,defId:h}=s(l);d.def={...d.schema},h&&(d.defId=h);let p=d.schema;for(let m in p)delete p[m];p.$ref=f};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
216
|
-
|
|
217
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let h=n.external.registry.get(l[0])?.id;if(e!==l[0]&&h){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let f=this.seen.get(l),h=f.def??f.schema,p={...h};if(f.ref===null)return;let m=f.ref;if(f.ref=null,m){a(m,d);let g=this.seen.get(m).schema;g.$ref&&d.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(g)):(Object.assign(h,g),Object.assign(h,p))}f.isParent||this.override({zodSchema:l,jsonSchema:h,path:f.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function Md(t,e){if(t instanceof Os){let n=new xa(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new xa(e);return r.process(t),r.emit(t,e)}function Ue(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ue(o.element,r);case"object":{for(let s in o.shape)if(Ue(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ue(s,r))return!0;return!1}case"intersection":return Ue(o.left,r)||Ue(o.right,r);case"tuple":{for(let s of o.items)if(Ue(s,r))return!0;return!!(o.rest&&Ue(o.rest,r))}case"record":return Ue(o.keyType,r)||Ue(o.valueType,r);case"map":return Ue(o.keyType,r)||Ue(o.valueType,r);case"set":return Ue(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ue(o.innerType,r);case"lazy":return Ue(o.getter(),r);case"default":return Ue(o.innerType,r);case"prefault":return Ue(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ue(o.in,r)||Ue(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var aR=b("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");me.init(t,e),t.def=e,t.parse=(r,n)=>el(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Dn(t,r,n),t.parseAsync=async(r,n)=>rl(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Mn(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)=>kt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var cR=b("ZodMiniObject",(t,e)=>{da.init(t,e),aR.init(t,e),se.defineLazy(t,"shape",()=>e.shape)});function jd(t,e){let r={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new cR(r)}function It(t){return!!t._zod}function Ln(t){let e=Object.values(t);if(e.length===0)return jd({});let r=e.every(It),n=e.every(o=>!It(o));if(r)return jd(t);if(n)return Hu(t);throw new Error("Mixed Zod versions detected in object shape.")}function Jr(t,e){return It(t)?Dn(t,e):t.safeParse(e)}async function Sa(t,e){return It(t)?await Mn(t,e):await t.safeParseAsync(e)}function Xr(t){if(!t)return;let e;if(It(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function ko(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Ln(t)}}if(It(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 va(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 Hy(t){return t.description}function Uy(t){if(It(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function ba(t){if(It(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Ns={};He(Ns,{ZodISODate:()=>Zy,ZodISODateTime:()=>Fy,ZodISODuration:()=>By,ZodISOTime:()=>qy,date:()=>Ld,datetime:()=>zd,duration:()=>Ud,time:()=>Hd});var Fy=b("ZodISODateTime",(t,e)=>{Py.init(t,e),Re.init(t,e)});function zd(t){return Ny(Fy,t)}var Zy=b("ZodISODate",(t,e)=>{Ry.init(t,e),Re.init(t,e)});function Ld(t){return Dy(Zy,t)}var qy=b("ZodISOTime",(t,e)=>{$y.init(t,e),Re.init(t,e)});function Hd(t){return My(qy,t)}var By=b("ZodISODuration",(t,e)=>{Cy.init(t,e),Re.init(t,e)});function Ud(t){return jy(By,t)}var Vy=(t,e)=>{ia.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Yu(t,r)},flatten:{value:r=>Xu(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},_U=b("ZodError",Vy),Ds=b("ZodError",Vy,{Parent:Error});var Wy=Qu(Ds),Ky=tl(Ds),Gy=nl(Ds),Jy=ol(Ds);var Ie=b("ZodType",(t,e)=>(me.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)=>kt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Wy(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Gy(t,r,n),t.parseAsync=async(r,n)=>Ky(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Jy(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(s0(r,n)),t.superRefine=r=>t.check(i0(r)),t.overwrite=r=>t.check(jn(r)),t.optional=()=>Ce(t),t.nullable=()=>Qy(t),t.nullish=()=>Ce(Qy(t)),t.nonoptional=r=>YR(t,r),t.array=()=>ie(t),t.or=r=>Ee([t,r]),t.and=r=>Ea(t,r),t.transform=r=>Zd(t,s_(r)),t.default=r=>GR(t,r),t.prefault=r=>XR(t,r),t.catch=r=>e0(t,r),t.pipe=r=>Zd(t,r),t.readonly=()=>n0(t),t.describe=r=>{let n=t.clone();return Gr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Gr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Gr.get(t);let n=t.clone();return Gr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),e_=b("_ZodString",(t,e)=>{Cs.init(t,e),Ie.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(Ed(...n)),t.includes=(...n)=>t.check(Pd(...n)),t.startsWith=(...n)=>t.check(Rd(...n)),t.endsWith=(...n)=>t.check($d(...n)),t.min=(...n)=>t.check(bo(...n)),t.max=(...n)=>t.check(ya(...n)),t.length=(...n)=>t.check(_a(...n)),t.nonempty=(...n)=>t.check(bo(1,...n)),t.lowercase=n=>t.check(wd(n)),t.uppercase=n=>t.check(Td(n)),t.trim=()=>t.check(Od()),t.normalize=(...n)=>t.check(Cd(...n)),t.toLowerCase=()=>t.check(Id()),t.toUpperCase=()=>t.check(Ad())}),yR=b("ZodString",(t,e)=>{Cs.init(t,e),e_.init(t,e),t.email=r=>t.check(Xl(_R,r)),t.url=r=>t.check(rd(xR,r)),t.jwt=r=>t.check(yd(NR,r)),t.emoji=r=>t.check(nd(SR,r)),t.guid=r=>t.check(fa(Xy,r)),t.uuid=r=>t.check(Yl(ka,r)),t.uuidv4=r=>t.check(Ql(ka,r)),t.uuidv6=r=>t.check(ed(ka,r)),t.uuidv7=r=>t.check(td(ka,r)),t.nanoid=r=>t.check(od(vR,r)),t.guid=r=>t.check(fa(Xy,r)),t.cuid=r=>t.check(sd(bR,r)),t.cuid2=r=>t.check(id(kR,r)),t.ulid=r=>t.check(ad(ER,r)),t.base64=r=>t.check(md(OR,r)),t.base64url=r=>t.check(hd(IR,r)),t.xid=r=>t.check(cd(wR,r)),t.ksuid=r=>t.check(ud(TR,r)),t.ipv4=r=>t.check(ld(PR,r)),t.ipv6=r=>t.check(dd(RR,r)),t.cidrv4=r=>t.check(pd($R,r)),t.cidrv6=r=>t.check(fd(CR,r)),t.e164=r=>t.check(gd(AR,r)),t.datetime=r=>t.check(zd(r)),t.date=r=>t.check(Ld(r)),t.time=r=>t.check(Hd(r)),t.duration=r=>t.check(Ud(r))});function v(t){return Jl(yR,t)}var Re=b("ZodStringFormat",(t,e)=>{ve.init(t,e),e_.init(t,e)}),_R=b("ZodEmail",(t,e)=>{pl.init(t,e),Re.init(t,e)});var Xy=b("ZodGUID",(t,e)=>{ll.init(t,e),Re.init(t,e)});var ka=b("ZodUUID",(t,e)=>{dl.init(t,e),Re.init(t,e)});var xR=b("ZodURL",(t,e)=>{fl.init(t,e),Re.init(t,e)});var SR=b("ZodEmoji",(t,e)=>{ml.init(t,e),Re.init(t,e)});var vR=b("ZodNanoID",(t,e)=>{hl.init(t,e),Re.init(t,e)});var bR=b("ZodCUID",(t,e)=>{gl.init(t,e),Re.init(t,e)});var kR=b("ZodCUID2",(t,e)=>{yl.init(t,e),Re.init(t,e)});var ER=b("ZodULID",(t,e)=>{_l.init(t,e),Re.init(t,e)});var wR=b("ZodXID",(t,e)=>{xl.init(t,e),Re.init(t,e)});var TR=b("ZodKSUID",(t,e)=>{Sl.init(t,e),Re.init(t,e)});var PR=b("ZodIPv4",(t,e)=>{vl.init(t,e),Re.init(t,e)});var RR=b("ZodIPv6",(t,e)=>{bl.init(t,e),Re.init(t,e)});var $R=b("ZodCIDRv4",(t,e)=>{kl.init(t,e),Re.init(t,e)});var CR=b("ZodCIDRv6",(t,e)=>{El.init(t,e),Re.init(t,e)});var OR=b("ZodBase64",(t,e)=>{wl.init(t,e),Re.init(t,e)});var IR=b("ZodBase64URL",(t,e)=>{Tl.init(t,e),Re.init(t,e)});var AR=b("ZodE164",(t,e)=>{Pl.init(t,e),Re.init(t,e)});var NR=b("ZodJWT",(t,e)=>{Rl.init(t,e),Re.init(t,e)});var t_=b("ZodNumber",(t,e)=>{la.init(t,e),Ie.init(t,e),t.gt=(n,o)=>t.check(ha(n,o)),t.gte=(n,o)=>t.check(As(n,o)),t.min=(n,o)=>t.check(As(n,o)),t.lt=(n,o)=>t.check(ma(n,o)),t.lte=(n,o)=>t.check(Is(n,o)),t.max=(n,o)=>t.check(Is(n,o)),t.int=n=>t.check(Yy(n)),t.safe=n=>t.check(Yy(n)),t.positive=n=>t.check(ha(0,n)),t.nonnegative=n=>t.check(As(0,n)),t.negative=n=>t.check(ma(0,n)),t.nonpositive=n=>t.check(Is(0,n)),t.multipleOf=(n,o)=>t.check(ga(n,o)),t.step=(n,o)=>t.check(ga(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function fe(t){return _d(t_,t)}var DR=b("ZodNumberFormat",(t,e)=>{$l.init(t,e),t_.init(t,e)});function Yy(t){return xd(DR,t)}var MR=b("ZodBoolean",(t,e)=>{Cl.init(t,e),Ie.init(t,e)});function qe(t){return Sd(MR,t)}var jR=b("ZodNull",(t,e)=>{Ol.init(t,e),Ie.init(t,e)});function r_(t){return vd(jR,t)}var zR=b("ZodUnknown",(t,e)=>{Il.init(t,e),Ie.init(t,e)});function $e(){return bd(zR)}var LR=b("ZodNever",(t,e)=>{Al.init(t,e),Ie.init(t,e)});function HR(t){return kd(LR,t)}var UR=b("ZodArray",(t,e)=>{Nl.init(t,e),Ie.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(bo(r,n)),t.nonempty=r=>t.check(bo(1,r)),t.max=(r,n)=>t.check(ya(r,n)),t.length=(r,n)=>t.check(_a(r,n)),t.unwrap=()=>t.element});function ie(t,e){return zy(UR,t,e)}var n_=b("ZodObject",(t,e)=>{da.init(t,e),Ie.init(t,e),se.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>ht(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:$e()}),t.loose=()=>t.clone({...t._zod.def,catchall:$e()}),t.strict=()=>t.clone({...t._zod.def,catchall:HR()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>se.extend(t,r),t.merge=r=>se.merge(t,r),t.pick=r=>se.pick(t,r),t.omit=r=>se.omit(t,r),t.partial=(...r)=>se.partial(i_,t,r[0]),t.required=(...r)=>se.required(a_,t,r[0])});function M(t,e){let r={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new n_(r)}function it(t,e){return new n_({type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},catchall:$e(),...se.normalizeParams(e)})}var o_=b("ZodUnion",(t,e)=>{pa.init(t,e),Ie.init(t,e),t.options=e.options});function Ee(t,e){return new o_({type:"union",options:t,...se.normalizeParams(e)})}var FR=b("ZodDiscriminatedUnion",(t,e)=>{o_.init(t,e),Dl.init(t,e)});function qd(t,e,r){return new FR({type:"union",options:e,discriminator:t,...se.normalizeParams(r)})}var ZR=b("ZodIntersection",(t,e)=>{Ml.init(t,e),Ie.init(t,e)});function Ea(t,e){return new ZR({type:"intersection",left:t,right:e})}var qR=b("ZodRecord",(t,e)=>{jl.init(t,e),Ie.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new qR({type:"record",keyType:t,valueType:e,...se.normalizeParams(r)})}var Fd=b("ZodEnum",(t,e)=>{zl.init(t,e),Ie.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Fd({...e,checks:[],...se.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Fd({...e,checks:[],...se.normalizeParams(o),entries:s})}});function ht(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Fd({type:"enum",entries:r,...se.normalizeParams(e)})}var BR=b("ZodLiteral",(t,e)=>{Ll.init(t,e),Ie.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]}})});function U(t,e){return new BR({type:"literal",values:Array.isArray(t)?t:[t],...se.normalizeParams(e)})}var VR=b("ZodTransform",(t,e)=>{Hl.init(t,e),Ie.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(se.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(se.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function s_(t){return new VR({type:"transform",transform:t})}var i_=b("ZodOptional",(t,e)=>{Ul.init(t,e),Ie.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ce(t){return new i_({type:"optional",innerType:t})}var WR=b("ZodNullable",(t,e)=>{Fl.init(t,e),Ie.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Qy(t){return new WR({type:"nullable",innerType:t})}var KR=b("ZodDefault",(t,e)=>{Zl.init(t,e),Ie.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function GR(t,e){return new KR({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var JR=b("ZodPrefault",(t,e)=>{ql.init(t,e),Ie.init(t,e),t.unwrap=()=>t._zod.def.innerType});function XR(t,e){return new JR({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var a_=b("ZodNonOptional",(t,e)=>{Bl.init(t,e),Ie.init(t,e),t.unwrap=()=>t._zod.def.innerType});function YR(t,e){return new a_({type:"nonoptional",innerType:t,...se.normalizeParams(e)})}var QR=b("ZodCatch",(t,e)=>{Vl.init(t,e),Ie.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function e0(t,e){return new QR({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var t0=b("ZodPipe",(t,e)=>{Wl.init(t,e),Ie.init(t,e),t.in=e.in,t.out=e.out});function Zd(t,e){return new t0({type:"pipe",in:t,out:e})}var r0=b("ZodReadonly",(t,e)=>{Kl.init(t,e),Ie.init(t,e)});function n0(t){return new r0({type:"readonly",innerType:t})}var c_=b("ZodCustom",(t,e)=>{Gl.init(t,e),Ie.init(t,e)});function o0(t){let e=new We({check:"custom"});return e._zod.check=t,e}function u_(t,e){return Nd(c_,t??(()=>!0),e)}function s0(t,e={}){return Dd(c_,t,e)}function i0(t){let e=o0(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(se.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(se.issue(o))}},t(r.value,r)));return e}function Bd(t,e){return Zd(s_(t),e)}bt(Iy());var Wd="2025-11-25";var l_=[Wd,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Yr="io.modelcontextprotocol/related-task",Ta="2.0",Fe=u_(t=>t!==null&&(typeof t=="object"||typeof t=="function")),d_=Ee([v(),fe().int()]),p_=v(),IU=it({ttl:fe().optional(),pollInterval:fe().optional()}),a0=M({ttl:fe().optional()}),c0=M({taskId:v()}),Kd=it({progressToken:d_.optional(),[Yr]:c0.optional()}),Et=M({_meta:Kd.optional()}),Ms=Et.extend({task:a0.optional()}),f_=t=>Ms.safeParse(t).success,Ke=M({method:v(),params:Et.loose().optional()}),At=M({_meta:Kd.optional()}),Nt=M({method:v(),params:At.loose().optional()}),Ge=it({_meta:Kd.optional()}),Pa=Ee([v(),fe().int()]),m_=M({jsonrpc:U(Ta),id:Pa,...Ke.shape}).strict(),Gd=t=>m_.safeParse(t).success,h_=M({jsonrpc:U(Ta),...Nt.shape}).strict(),g_=t=>h_.safeParse(t).success,Jd=M({jsonrpc:U(Ta),id:Pa,result:Ge}).strict(),js=t=>Jd.safeParse(t).success;var q;(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={}));var Xd=M({jsonrpc:U(Ta),id:Pa.optional(),error:M({code:fe().int(),message:v(),data:$e().optional()})}).strict();var y_=t=>Xd.safeParse(t).success;var __=Ee([m_,h_,Jd,Xd]),AU=Ee([Jd,Xd]),Ra=Ge.strict(),u0=At.extend({requestId:Pa.optional(),reason:v().optional()}),$a=Nt.extend({method:U("notifications/cancelled"),params:u0}),l0=M({src:v(),mimeType:v().optional(),sizes:ie(v()).optional(),theme:ht(["light","dark"]).optional()}),zs=M({icons:ie(l0).optional()}),Eo=M({name:v(),title:v().optional()}),x_=Eo.extend({...Eo.shape,...zs.shape,version:v(),websiteUrl:v().optional(),description:v().optional()}),d0=Ea(M({applyDefaults:qe().optional()}),be(v(),$e())),p0=Bd(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ea(M({form:d0.optional(),url:Fe.optional()}),be(v(),$e()).optional())),f0=it({list:Fe.optional(),cancel:Fe.optional(),requests:it({sampling:it({createMessage:Fe.optional()}).optional(),elicitation:it({create:Fe.optional()}).optional()}).optional()}),m0=it({list:Fe.optional(),cancel:Fe.optional(),requests:it({tools:it({call:Fe.optional()}).optional()}).optional()}),h0=M({experimental:be(v(),Fe).optional(),sampling:M({context:Fe.optional(),tools:Fe.optional()}).optional(),elicitation:p0.optional(),roots:M({listChanged:qe().optional()}).optional(),tasks:f0.optional(),extensions:be(v(),Fe).optional()}),g0=Et.extend({protocolVersion:v(),capabilities:h0,clientInfo:x_}),Yd=Ke.extend({method:U("initialize"),params:g0});var y0=M({experimental:be(v(),Fe).optional(),logging:Fe.optional(),completions:Fe.optional(),prompts:M({listChanged:qe().optional()}).optional(),resources:M({subscribe:qe().optional(),listChanged:qe().optional()}).optional(),tools:M({listChanged:qe().optional()}).optional(),tasks:m0.optional(),extensions:be(v(),Fe).optional()}),_0=Ge.extend({protocolVersion:v(),capabilities:y0,serverInfo:x_,instructions:v().optional()}),Qd=Nt.extend({method:U("notifications/initialized"),params:At.optional()});var Ca=Ke.extend({method:U("ping"),params:Et.optional()}),x0=M({progress:fe(),total:Ce(fe()),message:Ce(v())}),S0=M({...At.shape,...x0.shape,progressToken:d_}),Oa=Nt.extend({method:U("notifications/progress"),params:S0}),v0=Et.extend({cursor:p_.optional()}),Ls=Ke.extend({params:v0.optional()}),Hs=Ge.extend({nextCursor:p_.optional()}),b0=ht(["working","input_required","completed","failed","cancelled"]),Us=M({taskId:v(),status:b0,ttl:Ee([fe(),r_()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:Ce(fe()),statusMessage:Ce(v())}),wo=Ge.extend({task:Us}),k0=At.merge(Us),Fs=Nt.extend({method:U("notifications/tasks/status"),params:k0}),Ia=Ke.extend({method:U("tasks/get"),params:Et.extend({taskId:v()})}),Aa=Ge.merge(Us),Na=Ke.extend({method:U("tasks/result"),params:Et.extend({taskId:v()})}),NU=Ge.loose(),Da=Ls.extend({method:U("tasks/list")}),Ma=Hs.extend({tasks:ie(Us)}),ja=Ke.extend({method:U("tasks/cancel"),params:Et.extend({taskId:v()})}),S_=Ge.merge(Us),v_=M({uri:v(),mimeType:Ce(v()),_meta:be(v(),$e()).optional()}),b_=v_.extend({text:v()}),ep=v().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),k_=v_.extend({blob:ep}),Zs=ht(["user","assistant"]),To=M({audience:ie(Zs).optional(),priority:fe().min(0).max(1).optional(),lastModified:Ns.datetime({offset:!0}).optional()}),E_=M({...Eo.shape,...zs.shape,uri:v(),description:Ce(v()),mimeType:Ce(v()),size:Ce(fe()),annotations:To.optional(),_meta:Ce(it({}))}),E0=M({...Eo.shape,...zs.shape,uriTemplate:v(),description:Ce(v()),mimeType:Ce(v()),annotations:To.optional(),_meta:Ce(it({}))}),Po=Ls.extend({method:U("resources/list")}),w0=Hs.extend({resources:ie(E_)}),Ro=Ls.extend({method:U("resources/templates/list")}),T0=Hs.extend({resourceTemplates:ie(E0)}),tp=Et.extend({uri:v()}),P0=tp,za=Ke.extend({method:U("resources/read"),params:P0}),R0=Ge.extend({contents:ie(Ee([b_,k_]))}),$0=Nt.extend({method:U("notifications/resources/list_changed"),params:At.optional()}),C0=tp,O0=Ke.extend({method:U("resources/subscribe"),params:C0}),I0=tp,A0=Ke.extend({method:U("resources/unsubscribe"),params:I0}),N0=At.extend({uri:v()}),D0=Nt.extend({method:U("notifications/resources/updated"),params:N0}),M0=M({name:v(),description:Ce(v()),required:Ce(qe())}),j0=M({...Eo.shape,...zs.shape,description:Ce(v()),arguments:Ce(ie(M0)),_meta:Ce(it({}))}),$o=Ls.extend({method:U("prompts/list")}),z0=Hs.extend({prompts:ie(j0)}),L0=Et.extend({name:v(),arguments:be(v(),v()).optional()}),La=Ke.extend({method:U("prompts/get"),params:L0}),rp=M({type:U("text"),text:v(),annotations:To.optional(),_meta:be(v(),$e()).optional()}),np=M({type:U("image"),data:ep,mimeType:v(),annotations:To.optional(),_meta:be(v(),$e()).optional()}),op=M({type:U("audio"),data:ep,mimeType:v(),annotations:To.optional(),_meta:be(v(),$e()).optional()}),H0=M({type:U("tool_use"),name:v(),id:v(),input:be(v(),$e()),_meta:be(v(),$e()).optional()}),U0=M({type:U("resource"),resource:Ee([b_,k_]),annotations:To.optional(),_meta:be(v(),$e()).optional()}),F0=E_.extend({type:U("resource_link")}),sp=Ee([rp,np,op,F0,U0]),Z0=M({role:Zs,content:sp}),q0=Ge.extend({description:v().optional(),messages:ie(Z0)}),B0=Nt.extend({method:U("notifications/prompts/list_changed"),params:At.optional()}),V0=M({title:v().optional(),readOnlyHint:qe().optional(),destructiveHint:qe().optional(),idempotentHint:qe().optional(),openWorldHint:qe().optional()}),W0=M({taskSupport:ht(["required","optional","forbidden"]).optional()}),w_=M({...Eo.shape,...zs.shape,description:v().optional(),inputSchema:M({type:U("object"),properties:be(v(),Fe).optional(),required:ie(v()).optional()}).catchall($e()),outputSchema:M({type:U("object"),properties:be(v(),Fe).optional(),required:ie(v()).optional()}).catchall($e()).optional(),annotations:V0.optional(),execution:W0.optional(),_meta:be(v(),$e()).optional()}),Co=Ls.extend({method:U("tools/list")}),K0=Hs.extend({tools:ie(w_)}),Ha=Ge.extend({content:ie(sp).default([]),structuredContent:be(v(),$e()).optional(),isError:qe().optional()}),DU=Ha.or(Ge.extend({toolResult:$e()})),G0=Ms.extend({name:v(),arguments:be(v(),$e()).optional()}),Oo=Ke.extend({method:U("tools/call"),params:G0}),J0=Nt.extend({method:U("notifications/tools/list_changed"),params:At.optional()}),MU=M({autoRefresh:qe().default(!0),debounceMs:fe().int().nonnegative().default(300)}),qs=ht(["debug","info","notice","warning","error","critical","alert","emergency"]),X0=Et.extend({level:qs}),ip=Ke.extend({method:U("logging/setLevel"),params:X0}),Y0=At.extend({level:qs,logger:v().optional(),data:$e()}),Q0=Nt.extend({method:U("notifications/message"),params:Y0}),e$=M({name:v().optional()}),t$=M({hints:ie(e$).optional(),costPriority:fe().min(0).max(1).optional(),speedPriority:fe().min(0).max(1).optional(),intelligencePriority:fe().min(0).max(1).optional()}),r$=M({mode:ht(["auto","required","none"]).optional()}),n$=M({type:U("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:ie(sp).default([]),structuredContent:M({}).loose().optional(),isError:qe().optional(),_meta:be(v(),$e()).optional()}),o$=qd("type",[rp,np,op]),wa=qd("type",[rp,np,op,H0,n$]),s$=M({role:Zs,content:Ee([wa,ie(wa)]),_meta:be(v(),$e()).optional()}),i$=Ms.extend({messages:ie(s$),modelPreferences:t$.optional(),systemPrompt:v().optional(),includeContext:ht(["none","thisServer","allServers"]).optional(),temperature:fe().optional(),maxTokens:fe().int(),stopSequences:ie(v()).optional(),metadata:Fe.optional(),tools:ie(w_).optional(),toolChoice:r$.optional()}),a$=Ke.extend({method:U("sampling/createMessage"),params:i$}),Bs=Ge.extend({model:v(),stopReason:Ce(ht(["endTurn","stopSequence","maxTokens"]).or(v())),role:Zs,content:o$}),ap=Ge.extend({model:v(),stopReason:Ce(ht(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:Zs,content:Ee([wa,ie(wa)])}),c$=M({type:U("boolean"),title:v().optional(),description:v().optional(),default:qe().optional()}),u$=M({type:U("string"),title:v().optional(),description:v().optional(),minLength:fe().optional(),maxLength:fe().optional(),format:ht(["email","uri","date","date-time"]).optional(),default:v().optional()}),l$=M({type:ht(["number","integer"]),title:v().optional(),description:v().optional(),minimum:fe().optional(),maximum:fe().optional(),default:fe().optional()}),d$=M({type:U("string"),title:v().optional(),description:v().optional(),enum:ie(v()),default:v().optional()}),p$=M({type:U("string"),title:v().optional(),description:v().optional(),oneOf:ie(M({const:v(),title:v()})),default:v().optional()}),f$=M({type:U("string"),title:v().optional(),description:v().optional(),enum:ie(v()),enumNames:ie(v()).optional(),default:v().optional()}),m$=Ee([d$,p$]),h$=M({type:U("array"),title:v().optional(),description:v().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:M({type:U("string"),enum:ie(v())}),default:ie(v()).optional()}),g$=M({type:U("array"),title:v().optional(),description:v().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:M({anyOf:ie(M({const:v(),title:v()}))}),default:ie(v()).optional()}),y$=Ee([h$,g$]),_$=Ee([f$,m$,y$]),x$=Ee([_$,c$,u$,l$]),S$=Ms.extend({mode:U("form").optional(),message:v(),requestedSchema:M({type:U("object"),properties:be(v(),x$),required:ie(v()).optional()})}),v$=Ms.extend({mode:U("url"),message:v(),elicitationId:v(),url:v().url()}),b$=Ee([S$,v$]),k$=Ke.extend({method:U("elicitation/create"),params:b$}),E$=At.extend({elicitationId:v()}),w$=Nt.extend({method:U("notifications/elicitation/complete"),params:E$}),Io=Ge.extend({action:ht(["accept","decline","cancel"]),content:Bd(t=>t===null?void 0:t,be(v(),Ee([v(),fe(),qe(),ie(v())])).optional())}),T$=M({type:U("ref/resource"),uri:v()});var P$=M({type:U("ref/prompt"),name:v()}),R$=Et.extend({ref:Ee([P$,T$]),argument:M({name:v(),value:v()}),context:M({arguments:be(v(),v()).optional()}).optional()}),Ua=Ke.extend({method:U("completion/complete"),params:R$});function T_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function P_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var $$=Ge.extend({completion:it({values:ie(v()).max(100),total:Ce(fe().int()),hasMore:Ce(qe())})}),C$=M({uri:v().startsWith("file://"),name:v().optional(),_meta:be(v(),$e()).optional()}),O$=Ke.extend({method:U("roots/list"),params:Et.optional()}),cp=Ge.extend({roots:ie(C$)}),I$=Nt.extend({method:U("notifications/roots/list_changed"),params:At.optional()}),jU=Ee([Ca,Yd,Ua,ip,La,$o,Po,Ro,za,O0,A0,Oo,Co,Ia,Na,Da,ja]),zU=Ee([$a,Oa,Qd,I$,Fs]),LU=Ee([Ra,Bs,ap,Io,cp,Aa,Ma,wo]),HU=Ee([Ca,a$,k$,O$,Ia,Na,Da,ja]),UU=Ee([$a,Oa,Q0,D0,$0,J0,B0,Fs,w$]),FU=Ee([Ra,_0,$$,q0,z0,w0,T0,R0,Ha,K0,Aa,Ma,wo]),L=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 o=n;if(o.elicitations)return new Vd(o.elicitations,r)}return new t(e,r,n)}},Vd=class extends L{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(q.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Qr(t){return t==="completed"||t==="failed"||t==="cancelled"}var $_=Symbol("Let zodToJsonSchema decide on which parser to use");var R_={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"},C_=t=>typeof t=="string"?{...R_,name:t}:{...R_,...t};var O_=t=>{let e=C_(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function up(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ae(t,e,r,n,o){t[e]=r,up(t,e,n,o)}var Fa=(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 Oe(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Fa(e,t.currentPath):e.join("/")}}function I_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==P.ZodAny&&(r.items=K(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ae(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ae(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ae(r,"minItems",t.exactLength.value,t.exactLength.message,e),ae(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function A_(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?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function N_(){return{type:"boolean"}}function Za(t,e){return K(t.type._def,e)}var D_=(t,e)=>K(t.innerType._def,e);function lp(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>lp(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return A$(t,e)}}var A$=(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":ae(r,"minimum",n.value,n.message,e);break;case"max":ae(r,"maximum",n.value,n.message,e);break}return r};function M_(t,e){return{...K(t.innerType._def,e),default:t.defaultValue()}}function j_(t,e){return e.effectStrategy==="input"?K(t.schema._def,e):Oe(e)}function z_(t){return{type:"string",enum:Array.from(t.values)}}var N$=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function L_(t,e){let r=[K(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),K(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(N$(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function H_(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 dp,Jt={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:()=>(dp===void 0&&(dp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),dp),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function qa(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ae(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ae(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":Xt(r,"email",n.message,e);break;case"format:idn-email":Xt(r,"idn-email",n.message,e);break;case"pattern:zod":at(r,Jt.email,n.message,e);break}break;case"url":Xt(r,"uri",n.message,e);break;case"uuid":Xt(r,"uuid",n.message,e);break;case"regex":at(r,n.regex,n.message,e);break;case"cuid":at(r,Jt.cuid,n.message,e);break;case"cuid2":at(r,Jt.cuid2,n.message,e);break;case"startsWith":at(r,RegExp(`^${pp(n.value,e)}`),n.message,e);break;case"endsWith":at(r,RegExp(`${pp(n.value,e)}$`),n.message,e);break;case"datetime":Xt(r,"date-time",n.message,e);break;case"date":Xt(r,"date",n.message,e);break;case"time":Xt(r,"time",n.message,e);break;case"duration":Xt(r,"duration",n.message,e);break;case"length":ae(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ae(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{at(r,RegExp(pp(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Xt(r,"ipv4",n.message,e),n.version!=="v4"&&Xt(r,"ipv6",n.message,e);break}case"base64url":at(r,Jt.base64url,n.message,e);break;case"jwt":at(r,Jt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&at(r,Jt.ipv4Cidr,n.message,e),n.version!=="v4"&&at(r,Jt.ipv6Cidr,n.message,e);break}case"emoji":at(r,Jt.emoji(),n.message,e);break;case"ulid":{at(r,Jt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Xt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ae(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{at(r,Jt.base64,n.message,e);break}}break}case"nanoid":at(r,Jt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function pp(t,e){return e.patternStrategy==="escape"?M$(t):t}var D$=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function M$(t){let e="";for(let r=0;r<t.length;r++)D$.has(t[r])||(e+="\\"),e+=t[r];return e}function Xt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ae(t,"format",e,r,n)}function at(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:U_(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ae(t,"pattern",U_(e,n),r,n)}function U_(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
218
|
-
]))`;continue}else if(
|
|
219
|
-
]))`;continue}}if(
|
|
220
|
-
`:`[${
|
|
221
|
-
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function Ba(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===P.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Oe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===P.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=qa(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===P.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===P.ZodBranded&&t.keyType._def.type._def.typeName===P.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Za(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function F_(t,e){if(e.mapStrategy==="record")return Ba(t,e);let r=K(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Oe(e),n=K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Oe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Z_(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function q_(t){return t.target==="openAi"?void 0:{not:Oe({...t,currentPath:[...t.currentPath,"not"]})}}function B_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Vs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function W_(t,e){if(e.target==="openApi3")return V_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Vs&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Vs[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return V_(t,e)}var V_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>K(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function K_(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:Vs[t.innerType._def.typeName],nullable:!0}:{type:[Vs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=K(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function G_(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",up(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function J_(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=z$(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=K(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=j$(t,e);return i!==void 0&&(n.additionalProperties=i),n}function j$(t,e){if(t.catchall._def.typeName!=="ZodNever")return K(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 z$(t){try{return t.isOptional()}catch{return!0}}var X_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return K(t.innerType._def,e);let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Oe(e)},r]}:Oe(e)};var Y_=(t,e)=>{if(e.pipeStrategy==="input")return K(t.in._def,e);if(e.pipeStrategy==="output")return K(t.out._def,e);let r=K(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=K(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Q_(t,e){return K(t.type._def,e)}function ex(t,e){let n={type:"array",uniqueItems:!0,items:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function tx(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>K(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:K(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>K(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function rx(t){return{not:Oe(t)}}function nx(t){return Oe(t)}var ox=(t,e)=>K(t.innerType._def,e);var sx=(t,e,r)=>{switch(e){case P.ZodString:return qa(t,r);case P.ZodNumber:return G_(t,r);case P.ZodObject:return J_(t,r);case P.ZodBigInt:return A_(t,r);case P.ZodBoolean:return N_();case P.ZodDate:return lp(t,r);case P.ZodUndefined:return rx(r);case P.ZodNull:return B_(r);case P.ZodArray:return I_(t,r);case P.ZodUnion:case P.ZodDiscriminatedUnion:return W_(t,r);case P.ZodIntersection:return L_(t,r);case P.ZodTuple:return tx(t,r);case P.ZodRecord:return Ba(t,r);case P.ZodLiteral:return H_(t,r);case P.ZodEnum:return z_(t);case P.ZodNativeEnum:return Z_(t);case P.ZodNullable:return K_(t,r);case P.ZodOptional:return X_(t,r);case P.ZodMap:return F_(t,r);case P.ZodSet:return ex(t,r);case P.ZodLazy:return()=>t.getter()._def;case P.ZodPromise:return Q_(t,r);case P.ZodNaN:case P.ZodNever:return q_(r);case P.ZodEffects:return j_(t,r);case P.ZodAny:return Oe(r);case P.ZodUnknown:return nx(r);case P.ZodDefault:return M_(t,r);case P.ZodBranded:return Za(t,r);case P.ZodReadonly:return ox(t,r);case P.ZodCatch:return D_(t,r);case P.ZodPipeline:return Y_(t,r);case P.ZodFunction:case P.ZodVoid:case P.ZodSymbol:return;default:return(n=>{})(e)}};function K(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==$_)return a}if(n&&!r){let a=L$(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=sx(t,t.typeName,e),i=typeof s=="function"?K(s(),e):s;if(i&&H$(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var L$=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Fa(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`),Oe(e)):e.$refStrategy==="seen"?Oe(e):void 0}},H$=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var fp=(t,e)=>{let r=O_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:K(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Oe(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=K(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Oe(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function U$(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function mp(t,e){return It(t)?Md(t,{target:U$(e?.target),io:e?.pipeStrategy??"input"}):fp(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function hp(t){let r=Xr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ba(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function gp(t,e){let r=Jr(t,e);if(!r.success)throw r.error;return r.data}var F$=6e4,Va=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($a,r=>{this._oncancel(r)}),this.setNotificationHandler(Oa,r=>{this._onprogress(r)}),this.setRequestHandler(Ca,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ia,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new L(q.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Na,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,f=new L(d.error.code,d.error.message,d.error.data);l(f)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new L(q.InvalidParams,`Task not found: ${s}`);if(!Qr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Qr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Yr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Da,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new L(q.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ja,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new L(q.InvalidParams,`Task not found: ${r.params.taskId}`);if(Qr(o.status))throw new L(q.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new L(q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof L?o:new L(q.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),L.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=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),js(s)||y_(s)?this._onresponse(s):Gd(s)?this._onrequest(s,i):g_(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=L.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,o=this._transport,s=e.params?._meta?.[Yr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:q.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=f_(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(i.signal.aborted)throw new L(q.ConnectionClosed,"Request was cancelled");let h={...f,relatedRequestId:e.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});let p=h.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,h)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:q.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),js(e))n(e);else{let i=new L(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(js(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),js(e))o(e);else{let i=L.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof L?i:new L(q.InternalError,String(i))}}return}let s;try{let i=await this.request(e,wo,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new L(q.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Qr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new L(q.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new L(q.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof L?i:new L(q.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=_=>{l(_)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(_){d(_);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Yr]:c}});let p=_=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let x=_ instanceof L?_:new L(q.RequestTimeout,String(_));l(x)};this._responseHandlers.set(f,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return l(_);try{let x=Jr(r,_.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let m=n?.timeout??F$,g=()=>p(L.fromError(q.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(f,m,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=x=>{let S=this._responseHandlers.get(f);S?S(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,_),this._enqueueTaskMessage(y,{type:"request",message:h,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),l(x)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(f),l(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Aa,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},Ma,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},S_,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||{},[Yr]: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||{},[Yr]: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||{},[Yr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=hp(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=gp(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=hp(e);this._notificationHandlers.set(n,o=>{let s=gp(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Gd(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new L(q.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new L(q.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new L(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 o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new L(q.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Fs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Qr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new L(q.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Qr(a.status))throw new L(q.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=Fs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Qr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function ix(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ax(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];ix(i)&&ix(s)?r[o]={...i,...s}:r[o]=s}return r}var Wv=pg(rm(),1),Kv=pg(Vv(),1);function AD(){let t=new Wv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Kv.default)(t),t}var Rc=class{constructor(e){this._ajv=e??AD()}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 $c=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(s.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==d.size||![...l].every(f=>d.has(f)))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},Bs,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Io,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 Gv(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 Jv(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 Cc=class extends Va{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(qs.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Rc,this.setRequestHandler(Yd,n=>this._oninitialize(n)),this.setNotificationHandler(Qd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ip,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=qs.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new $c(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ax(this._capabilities,e)}setRequestHandler(e,r){let o=Xr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(It(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Jr(Oo,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new L(q.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let p=Jr(wo,f);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new L(q.InvalidParams,`Invalid task creation result: ${m}`)}return p.data}let h=Jr(Ha,f);if(!h.success){let p=h.error instanceof Error?h.error.message:String(h.error);throw new L(q.InvalidParams,`Invalid tools/call result: ${p}`)}return h.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Jv(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Gv(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:l_.includes(r)?r:Wd,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"},Ra)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},ap,r):this.request({method:"sampling/createMessage",params:e},Bs,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Io,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Io,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new L(q.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof L?i:new L(q.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},cp,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"})}};var Yv=Symbol.for("mcp.completable");function lm(t){return!!t&&typeof t=="object"&&Yv in t}function Qv(t){return t[Yv]?.complete}var Xv;(function(t){t.Completable="McpCompletable"})(Xv||(Xv={}));var ND=/^[A-Za-z0-9._-]{1,128}$/;function DD(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"),!ND.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function MD(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 dm(t){let e=DD(t);return MD(t,e.warnings),e.isValid}var Oc=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var Ic=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 Cc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Oc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(un(Co)),this.server.assertCanSetRequestHandler(un(Oo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Co,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=ko(r.inputSchema);return o?mp(o,{strictUnions:!0,pipeStrategy:"input"}):jD})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=ko(r.outputSchema);o&&(n.outputSchema=mp(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Oo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new L(q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new L(q.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new L(q.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new L(q.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof L&&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 s=ko(e.inputSchema)??e.inputSchema,i=await Sa(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=va(a);throw new L(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 L(q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=ko(e.outputSchema),s=await Sa(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=va(i);throw new L(q.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(f=>setTimeout(f,l));let d=await n.taskStore.getTask(c);if(!d)throw new L(q.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(un(Ua)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ua,async e=>{switch(e.params.ref.type){case"ref/prompt":return T_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return P_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new L(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 L(q.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new L(q.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return bi;let s=Xr(n.argsSchema)?.[e.params.argument.name];if(!lm(s))return bi;let i=Qv(s);if(!i)return bi;let a=await i(e.params.argument.value,e.params.context);return tb(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 bi;throw new L(q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return bi;let s=await o(e.params.argument.value,e.params.context);return tb(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(un(Po)),this.server.assertCanSetRequestHandler(un(Ro)),this.server.assertCanSetRequestHandler(un(za)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Po,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Ro,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(za,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new L(q.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new L(q.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(un($o)),this.server.assertCanSetRequestHandler(un(La)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler($o,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?zD(r.argsSchema):void 0}))})),this.server.setRequestHandler(La,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new L(q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new L(q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=ko(n.argsSchema),s=await Sa(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=va(c);throw new L(q.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Ln(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Ln(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof ft?c._def?.innerType:c;return lm(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){dm(e);let l={title:r,description:n,inputSchema:eb(o),outputSchema:eb(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&dm(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Ln(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Ln(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(pm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!pm(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var jD={type:"object",properties:{}};function rb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function nb(t){return"_def"in t||"_zod"in t||rb(t)}function pm(t){return typeof t!="object"||t===null||nb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(rb)}function eb(t){if(t){if(pm(t))return Ln(t);if(!nb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function zD(t){let e=Xr(t);return e?Object.entries(e).map(([r,n])=>{let o=Hy(n),s=Uy(n);return{name:r,description:o,required:!s}}):[]}function un(t){let r=Xr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ba(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function tb(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var bi={completion:{values:[],hasMore:!1}};import sb from"node:process";var Ac=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
222
|
-
`);if(e===-1)return null;let
|
|
223
|
-
`}var
|
|
224
|
-
${t}`}
|
|
219
|
+
path: iss.path ? [${Nr(_)}, ...iss.path] : [${Nr(_)}]
|
|
220
|
+
})));`),f.write(`newResult[${Nr(_)}] = ${S}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(_,S)=>y(d,_,S)},o,s=bo,i=!ca.jitless,c=i&&cl.value,u=e.catchall,l;t._zod.parse=(d,f)=>{l??(l=n.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let p=[];if(i&&c&&f?.async===!1&&f.jitless!==!0)o||(o=r(e.shape)),d=o(d,f);else{d.value={};let S=l.shape;for(let k of l.keys){let v=S[k],O=v._zod.run({value:m[k],issues:[]},f),R=v._zod.optin==="optional"&&v._zod.optout==="optional";O instanceof Promise?p.push(O.then(M=>R?By(M,d,k,m):ha(M,d,k))):R?By(O,d,k,m):ha(O,d,k)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;let h=[],g=l.keySet,y=u._zod,_=y.def.type;for(let S of Object.keys(m)){if(g.has(S))continue;if(_==="never"){h.push(S);continue}let k=y.run({value:m[S],issues:[]},f);k instanceof Promise?p.push(k.then(v=>ha(v,d,S))):ha(k,d,S)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),p.length?Promise.all(p).then(()=>d):d}});function qy(t,e,n,r){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(o=>o.issues.map(s=>Jt(s,r,wt())))}),e}var _a=b("$ZodUnion",(t,e)=>{me.init(t,e),Se(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Se(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Se(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Se(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>$s(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:n.value,issues:[]},r);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>qy(i,n,t,r)):qy(s,n,t,r)}}),Xl=b("$ZodDiscriminatedUnion",(t,e)=>{_a.init(t,e);let n=t._zod.parse;Se(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let r=Rs(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!bo(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Yl=b("$ZodIntersection",(t,e)=>{me.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Vy(n,c,u)):Vy(n,s,i)}});function wl(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(vo(t)&&vo(e)){let n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=wl(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<t.length;r++){let o=t[r],s=e[r],i=wl(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Vy(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),Dr(t))return t;let r=wl(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}var Ql=b("$ZodRecord",(t,e)=>{me.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!vo(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;n.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},r);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&n.issues.push(...fn(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...fn(c,u.issues)),n.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{n.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>Jt(u,r,wt())),input:i,path:[i],inst:t}),n.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},r);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&n.issues.push(...fn(i,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(...fn(i,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}});var ed=b("$ZodEnum",(t,e)=>{me.init(t,e);let n=Ps(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>ul.has(typeof r)).map(r=>typeof r=="string"?Gn(r):r.toString()).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),td=b("$ZodLiteral",(t,e)=>{me.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Gn(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}});var nd=b("$ZodTransform",(t,e)=>{me.init(t,e),t._zod.parse=(n,r)=>{let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new $n;return n.value=o,n}}),rd=b("$ZodOptional",(t,e)=>{me.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Se(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Se(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${$s(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),od=b("$ZodNullable",(t,e)=>{me.init(t,e),Se(t._zod,"optin",()=>e.innerType._zod.optin),Se(t._zod,"optout",()=>e.innerType._zod.optout),Se(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${$s(n.source)}|null)$`):void 0}),Se(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),sd=b("$ZodDefault",(t,e)=>{me.init(t,e),t._zod.optin="optional",Se(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Wy(s,e)):Wy(o,e)}});function Wy(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var id=b("$ZodPrefault",(t,e)=>{me.init(t,e),t._zod.optin="optional",Se(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),ad=b("$ZodNonOptional",(t,e)=>{me.init(t,e),Se(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Ky(s,t)):Ky(o,t)}});function Ky(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var cd=b("$ZodCatch",(t,e)=>{me.init(t,e),t._zod.optin="optional",Se(t._zod,"optout",()=>e.innerType._zod.optout),Se(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>Jt(i,r,wt()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>Jt(s,r,wt()))},input:n.value}),n.issues=[]),n)}});var ud=b("$ZodPipe",(t,e)=>{me.init(t,e),Se(t._zod,"values",()=>e.in._zod.values),Se(t._zod,"optin",()=>e.in._zod.optin),Se(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Gy(s,e,r)):Gy(o,e,r)}});function Gy(t,e,n){return Dr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}var ld=b("$ZodReadonly",(t,e)=>{me.init(t,e),Se(t._zod,"propValues",()=>e.innerType._zod.propValues),Se(t._zod,"values",()=>e.innerType._zod.values),Se(t._zod,"optin",()=>e.innerType._zod.optin),Se(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(Jy):Jy(o)}});function Jy(t){return t.value=Object.freeze(t.value),t}var dd=b("$ZodCustom",(t,e)=>{We.init(t,e),me.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>Xy(s,n,r,t));Xy(o,n,r,t)}});function Xy(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(pl(o))}}var _R=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},SR=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${_R(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${da(r.values[0])}`:`Invalid option: expected one of ${ua(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${ua(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function r_(){return{localeError:SR()}}var Ds=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){let r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function o_(){return new Ds}var Jn=o_();function pd(t,e){return new t({type:"string",...q(e)})}function fd(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...q(e)})}function Sa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...q(e)})}function md(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...q(e)})}function hd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(e)})}function gd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(e)})}function yd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(e)})}function _d(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...q(e)})}function Sd(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...q(e)})}function xd(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(e)})}function kd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...q(e)})}function bd(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(e)})}function vd(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...q(e)})}function Ed(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...q(e)})}function wd(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(e)})}function Td(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(e)})}function Pd(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(e)})}function Rd(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(e)})}function Cd(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(e)})}function $d(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...q(e)})}function Od(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...q(e)})}function Id(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...q(e)})}function Ad(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...q(e)})}function s_(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(e)})}function i_(t,e){return new t({type:"string",format:"date",check:"string_format",...q(e)})}function a_(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...q(e)})}function c_(t,e){return new t({type:"string",format:"duration",check:"string_format",...q(e)})}function Nd(t,e){return new t({type:"number",checks:[],...q(e)})}function Dd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...q(e)})}function Md(t,e){return new t({type:"boolean",...q(e)})}function jd(t,e){return new t({type:"null",...q(e)})}function zd(t){return new t({type:"unknown"})}function Ld(t,e){return new t({type:"never",...q(e)})}function xa(t,e){return new vl({check:"less_than",...q(e),value:t,inclusive:!1})}function Ms(t,e){return new vl({check:"less_than",...q(e),value:t,inclusive:!0})}function ka(t,e){return new El({check:"greater_than",...q(e),value:t,inclusive:!1})}function js(t,e){return new El({check:"greater_than",...q(e),value:t,inclusive:!0})}function ba(t,e){return new Cy({check:"multiple_of",...q(e),value:t})}function va(t,e){return new Oy({check:"max_length",...q(e),maximum:t})}function Eo(t,e){return new Iy({check:"min_length",...q(e),minimum:t})}function Ea(t,e){return new Ay({check:"length_equals",...q(e),length:t})}function Hd(t,e){return new Ny({check:"string_format",format:"regex",...q(e),pattern:t})}function Ud(t){return new Dy({check:"string_format",format:"lowercase",...q(t)})}function Fd(t){return new My({check:"string_format",format:"uppercase",...q(t)})}function Zd(t,e){return new jy({check:"string_format",format:"includes",...q(e),includes:t})}function Bd(t,e){return new zy({check:"string_format",format:"starts_with",...q(e),prefix:t})}function qd(t,e){return new Ly({check:"string_format",format:"ends_with",...q(e),suffix:t})}function zr(t){return new Hy({check:"overwrite",tx:t})}function Vd(t){return zr(e=>e.normalize(t))}function Wd(){return zr(t=>t.trim())}function Kd(){return zr(t=>t.toLowerCase())}function Gd(){return zr(t=>t.toUpperCase())}function u_(t,e,n){return new t({type:"array",element:e,...q(n)})}function Jd(t,e,n){let r=q(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function Xd(t,e,n){return new t({type:"custom",check:"custom",fn:e,...q(n)})}var wa=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Jn,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path},f=e._zod.parent;if(f)a.ref=f,this.process(f,d),this.seen.get(f).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let p=m;p.type="string";let{minimum:h,maximum:g,format:y,patterns:_,contentEncoding:S}=e._zod.bag;if(typeof h=="number"&&(p.minLength=h),typeof g=="number"&&(p.maxLength=g),y&&(p.format=s[y]??y,p.format===""&&delete p.format),S&&(p.contentEncoding=S),_&&_.size>0){let k=[..._];k.length===1?p.pattern=k[0].source:k.length>1&&(a.schema.allOf=[...k.map(v=>({...this.target==="draft-7"?{type:"string"}:{},pattern:v.source}))])}break}case"number":{let p=m,{minimum:h,maximum:g,format:y,multipleOf:_,exclusiveMaximum:S,exclusiveMinimum:k}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof k=="number"&&(p.exclusiveMinimum=k),typeof h=="number"&&(p.minimum=h,typeof k=="number"&&(k>=h?delete p.minimum:delete p.exclusiveMinimum)),typeof S=="number"&&(p.exclusiveMaximum=S),typeof g=="number"&&(p.maximum=g,typeof S=="number"&&(S<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);break}case"boolean":{let p=m;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":{m.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":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=m,{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(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let p=m;p.type="object",p.properties={};let h=o.shape;for(let _ in h)p.properties[_]=this.process(h[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(_=>{let S=o.shape[_]._zod;return this.io==="input"?S.optin===void 0:S.optout===void 0}));y.size>0&&(p.required=Array.from(y)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=m;p.anyOf=o.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let p=m,h=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=S=>"allOf"in S&&Object.keys(S).length===1,_=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];p.allOf=_;break}case"tuple":{let p=m;p.type="array";let h=o.items.map((_,S)=>this.process(_,{...d,path:[...d.path,"prefixItems",S]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}o.rest&&(p.items=this.process(o.rest,{...d,path:[...d.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=m;p.type="object",p.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=m,h=Ps(o.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=m,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");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=m,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),_?_.length===1?(h.contentMediaType=_[0],Object.assign(p,h)):p.anyOf=_.map(S=>({...h,contentMediaType:S})):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(o.innerType,d);m.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let p=m;p.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.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=m,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"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,d),a.ref=p;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,d),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"&&Fe(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,n){let r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){let h=r.external.registry.get(l[0])?.id,g=r.external.uri??(_=>_);if(h)return{ref:g(h)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===o)return{ref:"#"};let m=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:m+p}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:f,defId:m}=s(l);d.def={...d.schema},m&&(d.defId=m);let p=d.schema;for(let h in p)delete p[h];p.$ref=f};if(r.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
221
|
+
|
|
222
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(r.external){let m=r.external.registry.get(l[0])?.id;if(e!==l[0]&&m){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&r.reused==="ref"){i(l);continue}}let a=(l,d)=>{let f=this.seen.get(l),m=f.def??f.schema,p={...m};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(g)):(Object.assign(m,g),Object.assign(m,p))}f.isParent||this.override({zodSchema:l,jsonSchema:m,path:f.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){let l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(l)}Object.assign(c,o.def);let u=r.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}r.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function Yd(t,e){if(t instanceof Ds){let r=new wa(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;r.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=r.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let n=new wa(e);return n.process(t),n.emit(t,e)}function Fe(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Fe(o.element,n);case"object":{for(let s in o.shape)if(Fe(o.shape[s],n))return!0;return!1}case"union":{for(let s of o.options)if(Fe(s,n))return!0;return!1}case"intersection":return Fe(o.left,n)||Fe(o.right,n);case"tuple":{for(let s of o.items)if(Fe(s,n))return!0;return!!(o.rest&&Fe(o.rest,n))}case"record":return Fe(o.keyType,n)||Fe(o.valueType,n);case"map":return Fe(o.keyType,n)||Fe(o.valueType,n);case"set":return Fe(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Fe(o.innerType,n);case"lazy":return Fe(o.getter(),n);case"default":return Fe(o.innerType,n);case"prefault":return Fe(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Fe(o.in,n)||Fe(o.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var e0=b("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");me.init(t,e),t.def=e,t.parse=(n,r)=>gl(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Mr(t,n,r),t.parseAsync=async(n,r)=>_l(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>jr(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Tt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))});var t0=b("ZodMiniObject",(t,e)=>{ya.init(t,e),e0.init(t,e),se.defineLazy(t,"shape",()=>e.shape)});function Qd(t,e){let n={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new t0(n)}function Nt(t){return!!t._zod}function Hr(t){let e=Object.values(t);if(e.length===0)return Qd({});let n=e.every(Nt),r=e.every(o=>!Nt(o));if(n)return Qd(t);if(r)return nl(t);throw new Error("Mixed Zod versions detected in object shape.")}function Xn(t,e){return Nt(t)?Mr(t,e):t.safeParse(e)}async function Ta(t,e){return Nt(t)?await jr(t,e):await t.safeParseAsync(e)}function Yn(t){if(!t)return;let e;if(Nt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function wo(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Hr(t)}}if(Nt(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function Pa(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 d_(t){return t.description}function p_(t){if(Nt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Ra(t){if(Nt(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var zs={};De(zs,{ZodISODate:()=>m_,ZodISODateTime:()=>f_,ZodISODuration:()=>g_,ZodISOTime:()=>h_,date:()=>tp,datetime:()=>ep,duration:()=>rp,time:()=>np});var f_=b("ZodISODateTime",(t,e)=>{Yy.init(t,e),Pe.init(t,e)});function ep(t){return s_(f_,t)}var m_=b("ZodISODate",(t,e)=>{Qy.init(t,e),Pe.init(t,e)});function tp(t){return i_(m_,t)}var h_=b("ZodISOTime",(t,e)=>{e_.init(t,e),Pe.init(t,e)});function np(t){return a_(h_,t)}var g_=b("ZodISODuration",(t,e)=>{t_.init(t,e),Pe.init(t,e)});function rp(t){return c_(g_,t)}var y_=(t,e)=>{pa.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ml(t,n)},flatten:{value:n=>fl(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},ZF=b("ZodError",y_),Ls=b("ZodError",y_,{Parent:Error});var __=hl(Ls),S_=yl(Ls),x_=Sl(Ls),k_=xl(Ls);var Oe=b("ZodType",(t,e)=>(me.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Tt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>__(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>x_(t,n,r),t.parseAsync=async(n,r)=>S_(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>k_(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(Y0(n,r)),t.superRefine=n=>t.check(Q0(n)),t.overwrite=n=>t.check(zr(n)),t.optional=()=>Ce(t),t.nullable=()=>E_(t),t.nullish=()=>Ce(E_(t)),t.nonoptional=n=>q0(t,n),t.array=()=>ie(t),t.or=n=>be([t,n]),t.and=n=>$a(t,n),t.transform=n=>sp(t,$_(n)),t.default=n=>F0(t,n),t.prefault=n=>B0(t,n),t.catch=n=>W0(t,n),t.pipe=n=>sp(t,n),t.readonly=()=>J0(t),t.describe=n=>{let r=t.clone();return Jn.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Jn.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Jn.get(t);let r=t.clone();return Jn.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),w_=b("_ZodString",(t,e)=>{Ns.init(t,e),Oe.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(Hd(...r)),t.includes=(...r)=>t.check(Zd(...r)),t.startsWith=(...r)=>t.check(Bd(...r)),t.endsWith=(...r)=>t.check(qd(...r)),t.min=(...r)=>t.check(Eo(...r)),t.max=(...r)=>t.check(va(...r)),t.length=(...r)=>t.check(Ea(...r)),t.nonempty=(...r)=>t.check(Eo(1,...r)),t.lowercase=r=>t.check(Ud(r)),t.uppercase=r=>t.check(Fd(r)),t.trim=()=>t.check(Wd()),t.normalize=(...r)=>t.check(Vd(...r)),t.toLowerCase=()=>t.check(Kd()),t.toUpperCase=()=>t.check(Gd())}),l0=b("ZodString",(t,e)=>{Ns.init(t,e),w_.init(t,e),t.email=n=>t.check(fd(d0,n)),t.url=n=>t.check(_d(p0,n)),t.jwt=n=>t.check(Ad(P0,n)),t.emoji=n=>t.check(Sd(f0,n)),t.guid=n=>t.check(Sa(b_,n)),t.uuid=n=>t.check(md(Ca,n)),t.uuidv4=n=>t.check(hd(Ca,n)),t.uuidv6=n=>t.check(gd(Ca,n)),t.uuidv7=n=>t.check(yd(Ca,n)),t.nanoid=n=>t.check(xd(m0,n)),t.guid=n=>t.check(Sa(b_,n)),t.cuid=n=>t.check(kd(h0,n)),t.cuid2=n=>t.check(bd(g0,n)),t.ulid=n=>t.check(vd(y0,n)),t.base64=n=>t.check($d(E0,n)),t.base64url=n=>t.check(Od(w0,n)),t.xid=n=>t.check(Ed(_0,n)),t.ksuid=n=>t.check(wd(S0,n)),t.ipv4=n=>t.check(Td(x0,n)),t.ipv6=n=>t.check(Pd(k0,n)),t.cidrv4=n=>t.check(Rd(b0,n)),t.cidrv6=n=>t.check(Cd(v0,n)),t.e164=n=>t.check(Id(T0,n)),t.datetime=n=>t.check(ep(n)),t.date=n=>t.check(tp(n)),t.time=n=>t.check(np(n)),t.duration=n=>t.check(rp(n))});function x(t){return pd(l0,t)}var Pe=b("ZodStringFormat",(t,e)=>{xe.init(t,e),w_.init(t,e)}),d0=b("ZodEmail",(t,e)=>{Rl.init(t,e),Pe.init(t,e)});var b_=b("ZodGUID",(t,e)=>{Tl.init(t,e),Pe.init(t,e)});var Ca=b("ZodUUID",(t,e)=>{Pl.init(t,e),Pe.init(t,e)});var p0=b("ZodURL",(t,e)=>{Cl.init(t,e),Pe.init(t,e)});var f0=b("ZodEmoji",(t,e)=>{$l.init(t,e),Pe.init(t,e)});var m0=b("ZodNanoID",(t,e)=>{Ol.init(t,e),Pe.init(t,e)});var h0=b("ZodCUID",(t,e)=>{Il.init(t,e),Pe.init(t,e)});var g0=b("ZodCUID2",(t,e)=>{Al.init(t,e),Pe.init(t,e)});var y0=b("ZodULID",(t,e)=>{Nl.init(t,e),Pe.init(t,e)});var _0=b("ZodXID",(t,e)=>{Dl.init(t,e),Pe.init(t,e)});var S0=b("ZodKSUID",(t,e)=>{Ml.init(t,e),Pe.init(t,e)});var x0=b("ZodIPv4",(t,e)=>{jl.init(t,e),Pe.init(t,e)});var k0=b("ZodIPv6",(t,e)=>{zl.init(t,e),Pe.init(t,e)});var b0=b("ZodCIDRv4",(t,e)=>{Ll.init(t,e),Pe.init(t,e)});var v0=b("ZodCIDRv6",(t,e)=>{Hl.init(t,e),Pe.init(t,e)});var E0=b("ZodBase64",(t,e)=>{Ul.init(t,e),Pe.init(t,e)});var w0=b("ZodBase64URL",(t,e)=>{Fl.init(t,e),Pe.init(t,e)});var T0=b("ZodE164",(t,e)=>{Zl.init(t,e),Pe.init(t,e)});var P0=b("ZodJWT",(t,e)=>{Bl.init(t,e),Pe.init(t,e)});var T_=b("ZodNumber",(t,e)=>{ga.init(t,e),Oe.init(t,e),t.gt=(r,o)=>t.check(ka(r,o)),t.gte=(r,o)=>t.check(js(r,o)),t.min=(r,o)=>t.check(js(r,o)),t.lt=(r,o)=>t.check(xa(r,o)),t.lte=(r,o)=>t.check(Ms(r,o)),t.max=(r,o)=>t.check(Ms(r,o)),t.int=r=>t.check(v_(r)),t.safe=r=>t.check(v_(r)),t.positive=r=>t.check(ka(0,r)),t.nonnegative=r=>t.check(js(0,r)),t.negative=r=>t.check(xa(0,r)),t.nonpositive=r=>t.check(Ms(0,r)),t.multipleOf=(r,o)=>t.check(ba(r,o)),t.step=(r,o)=>t.check(ba(r,o)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function fe(t){return Nd(T_,t)}var R0=b("ZodNumberFormat",(t,e)=>{ql.init(t,e),T_.init(t,e)});function v_(t){return Dd(R0,t)}var C0=b("ZodBoolean",(t,e)=>{Vl.init(t,e),Oe.init(t,e)});function qe(t){return Md(C0,t)}var $0=b("ZodNull",(t,e)=>{Wl.init(t,e),Oe.init(t,e)});function P_(t){return jd($0,t)}var O0=b("ZodUnknown",(t,e)=>{Kl.init(t,e),Oe.init(t,e)});function Re(){return zd(O0)}var I0=b("ZodNever",(t,e)=>{Gl.init(t,e),Oe.init(t,e)});function A0(t){return Ld(I0,t)}var N0=b("ZodArray",(t,e)=>{Jl.init(t,e),Oe.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Eo(n,r)),t.nonempty=n=>t.check(Eo(1,n)),t.max=(n,r)=>t.check(va(n,r)),t.length=(n,r)=>t.check(Ea(n,r)),t.unwrap=()=>t.element});function ie(t,e){return u_(N0,t,e)}var R_=b("ZodObject",(t,e)=>{ya.init(t,e),Oe.init(t,e),se.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>yt(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Re()}),t.loose=()=>t.clone({...t._zod.def,catchall:Re()}),t.strict=()=>t.clone({...t._zod.def,catchall:A0()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>se.extend(t,n),t.merge=n=>se.merge(t,n),t.pick=n=>se.pick(t,n),t.omit=n=>se.omit(t,n),t.partial=(...n)=>se.partial(O_,t,n[0]),t.required=(...n)=>se.required(I_,t,n[0])});function N(t,e){let n={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new R_(n)}function at(t,e){return new R_({type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},catchall:Re(),...se.normalizeParams(e)})}var C_=b("ZodUnion",(t,e)=>{_a.init(t,e),Oe.init(t,e),t.options=e.options});function be(t,e){return new C_({type:"union",options:t,...se.normalizeParams(e)})}var D0=b("ZodDiscriminatedUnion",(t,e)=>{C_.init(t,e),Xl.init(t,e)});function ip(t,e,n){return new D0({type:"union",options:e,discriminator:t,...se.normalizeParams(n)})}var M0=b("ZodIntersection",(t,e)=>{Yl.init(t,e),Oe.init(t,e)});function $a(t,e){return new M0({type:"intersection",left:t,right:e})}var j0=b("ZodRecord",(t,e)=>{Ql.init(t,e),Oe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function ke(t,e,n){return new j0({type:"record",keyType:t,valueType:e,...se.normalizeParams(n)})}var op=b("ZodEnum",(t,e)=>{ed.init(t,e),Oe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new op({...e,checks:[],...se.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new op({...e,checks:[],...se.normalizeParams(o),entries:s})}});function yt(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new op({type:"enum",entries:n,...se.normalizeParams(e)})}var z0=b("ZodLiteral",(t,e)=>{td.init(t,e),Oe.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]}})});function U(t,e){return new z0({type:"literal",values:Array.isArray(t)?t:[t],...se.normalizeParams(e)})}var L0=b("ZodTransform",(t,e)=>{nd.init(t,e),Oe.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(se.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(se.issue(i))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function $_(t){return new L0({type:"transform",transform:t})}var O_=b("ZodOptional",(t,e)=>{rd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ce(t){return new O_({type:"optional",innerType:t})}var H0=b("ZodNullable",(t,e)=>{od.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function E_(t){return new H0({type:"nullable",innerType:t})}var U0=b("ZodDefault",(t,e)=>{sd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function F0(t,e){return new U0({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Z0=b("ZodPrefault",(t,e)=>{id.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function B0(t,e){return new Z0({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var I_=b("ZodNonOptional",(t,e)=>{ad.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function q0(t,e){return new I_({type:"nonoptional",innerType:t,...se.normalizeParams(e)})}var V0=b("ZodCatch",(t,e)=>{cd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function W0(t,e){return new V0({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var K0=b("ZodPipe",(t,e)=>{ud.init(t,e),Oe.init(t,e),t.in=e.in,t.out=e.out});function sp(t,e){return new K0({type:"pipe",in:t,out:e})}var G0=b("ZodReadonly",(t,e)=>{ld.init(t,e),Oe.init(t,e)});function J0(t){return new G0({type:"readonly",innerType:t})}var A_=b("ZodCustom",(t,e)=>{dd.init(t,e),Oe.init(t,e)});function X0(t){let e=new We({check:"custom"});return e._zod.check=t,e}function N_(t,e){return Jd(A_,t??(()=>!0),e)}function Y0(t,e={}){return Xd(A_,t,e)}function Q0(t){let e=X0(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(se.issue(r,n.value,e._zod.def));else{let o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),n.issues.push(se.issue(o))}},t(n.value,n)));return e}function ap(t,e){return sp($_(t),e)}wt(r_());var up="2025-11-25";var D_=[up,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Qn="io.modelcontextprotocol/related-task",Ia="2.0",Ze=N_(t=>t!==null&&(typeof t=="object"||typeof t=="function")),M_=be([x(),fe().int()]),j_=x(),rZ=at({ttl:fe().optional(),pollInterval:fe().optional()}),eC=N({ttl:fe().optional()}),tC=N({taskId:x()}),lp=at({progressToken:M_.optional(),[Qn]:tC.optional()}),Pt=N({_meta:lp.optional()}),Hs=Pt.extend({task:eC.optional()}),z_=t=>Hs.safeParse(t).success,Ke=N({method:x(),params:Pt.loose().optional()}),Dt=N({_meta:lp.optional()}),Mt=N({method:x(),params:Dt.loose().optional()}),Ge=at({_meta:lp.optional()}),Aa=be([x(),fe().int()]),L_=N({jsonrpc:U(Ia),id:Aa,...Ke.shape}).strict(),dp=t=>L_.safeParse(t).success,H_=N({jsonrpc:U(Ia),...Mt.shape}).strict(),U_=t=>H_.safeParse(t).success,pp=N({jsonrpc:U(Ia),id:Aa,result:Ge}).strict(),Us=t=>pp.safeParse(t).success;var Z;(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"})(Z||(Z={}));var fp=N({jsonrpc:U(Ia),id:Aa.optional(),error:N({code:fe().int(),message:x(),data:Re().optional()})}).strict();var F_=t=>fp.safeParse(t).success;var Z_=be([L_,H_,pp,fp]),oZ=be([pp,fp]),Na=Ge.strict(),nC=Dt.extend({requestId:Aa.optional(),reason:x().optional()}),Da=Mt.extend({method:U("notifications/cancelled"),params:nC}),rC=N({src:x(),mimeType:x().optional(),sizes:ie(x()).optional(),theme:yt(["light","dark"]).optional()}),Fs=N({icons:ie(rC).optional()}),To=N({name:x(),title:x().optional()}),B_=To.extend({...To.shape,...Fs.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),oC=$a(N({applyDefaults:qe().optional()}),ke(x(),Re())),sC=ap(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,$a(N({form:oC.optional(),url:Ze.optional()}),ke(x(),Re()).optional())),iC=at({list:Ze.optional(),cancel:Ze.optional(),requests:at({sampling:at({createMessage:Ze.optional()}).optional(),elicitation:at({create:Ze.optional()}).optional()}).optional()}),aC=at({list:Ze.optional(),cancel:Ze.optional(),requests:at({tools:at({call:Ze.optional()}).optional()}).optional()}),cC=N({experimental:ke(x(),Ze).optional(),sampling:N({context:Ze.optional(),tools:Ze.optional()}).optional(),elicitation:sC.optional(),roots:N({listChanged:qe().optional()}).optional(),tasks:iC.optional(),extensions:ke(x(),Ze).optional()}),uC=Pt.extend({protocolVersion:x(),capabilities:cC,clientInfo:B_}),mp=Ke.extend({method:U("initialize"),params:uC});var lC=N({experimental:ke(x(),Ze).optional(),logging:Ze.optional(),completions:Ze.optional(),prompts:N({listChanged:qe().optional()}).optional(),resources:N({subscribe:qe().optional(),listChanged:qe().optional()}).optional(),tools:N({listChanged:qe().optional()}).optional(),tasks:aC.optional(),extensions:ke(x(),Ze).optional()}),dC=Ge.extend({protocolVersion:x(),capabilities:lC,serverInfo:B_,instructions:x().optional()}),hp=Mt.extend({method:U("notifications/initialized"),params:Dt.optional()});var Ma=Ke.extend({method:U("ping"),params:Pt.optional()}),pC=N({progress:fe(),total:Ce(fe()),message:Ce(x())}),fC=N({...Dt.shape,...pC.shape,progressToken:M_}),ja=Mt.extend({method:U("notifications/progress"),params:fC}),mC=Pt.extend({cursor:j_.optional()}),Zs=Ke.extend({params:mC.optional()}),Bs=Ge.extend({nextCursor:j_.optional()}),hC=yt(["working","input_required","completed","failed","cancelled"]),qs=N({taskId:x(),status:hC,ttl:be([fe(),P_()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:Ce(fe()),statusMessage:Ce(x())}),Po=Ge.extend({task:qs}),gC=Dt.merge(qs),Vs=Mt.extend({method:U("notifications/tasks/status"),params:gC}),za=Ke.extend({method:U("tasks/get"),params:Pt.extend({taskId:x()})}),La=Ge.merge(qs),Ha=Ke.extend({method:U("tasks/result"),params:Pt.extend({taskId:x()})}),sZ=Ge.loose(),Ua=Zs.extend({method:U("tasks/list")}),Fa=Bs.extend({tasks:ie(qs)}),Za=Ke.extend({method:U("tasks/cancel"),params:Pt.extend({taskId:x()})}),q_=Ge.merge(qs),V_=N({uri:x(),mimeType:Ce(x()),_meta:ke(x(),Re()).optional()}),W_=V_.extend({text:x()}),gp=x().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),K_=V_.extend({blob:gp}),Ws=yt(["user","assistant"]),Ro=N({audience:ie(Ws).optional(),priority:fe().min(0).max(1).optional(),lastModified:zs.datetime({offset:!0}).optional()}),G_=N({...To.shape,...Fs.shape,uri:x(),description:Ce(x()),mimeType:Ce(x()),size:Ce(fe()),annotations:Ro.optional(),_meta:Ce(at({}))}),yC=N({...To.shape,...Fs.shape,uriTemplate:x(),description:Ce(x()),mimeType:Ce(x()),annotations:Ro.optional(),_meta:Ce(at({}))}),Co=Zs.extend({method:U("resources/list")}),_C=Bs.extend({resources:ie(G_)}),$o=Zs.extend({method:U("resources/templates/list")}),SC=Bs.extend({resourceTemplates:ie(yC)}),yp=Pt.extend({uri:x()}),xC=yp,Ba=Ke.extend({method:U("resources/read"),params:xC}),kC=Ge.extend({contents:ie(be([W_,K_]))}),bC=Mt.extend({method:U("notifications/resources/list_changed"),params:Dt.optional()}),vC=yp,EC=Ke.extend({method:U("resources/subscribe"),params:vC}),wC=yp,TC=Ke.extend({method:U("resources/unsubscribe"),params:wC}),PC=Dt.extend({uri:x()}),RC=Mt.extend({method:U("notifications/resources/updated"),params:PC}),CC=N({name:x(),description:Ce(x()),required:Ce(qe())}),$C=N({...To.shape,...Fs.shape,description:Ce(x()),arguments:Ce(ie(CC)),_meta:Ce(at({}))}),Oo=Zs.extend({method:U("prompts/list")}),OC=Bs.extend({prompts:ie($C)}),IC=Pt.extend({name:x(),arguments:ke(x(),x()).optional()}),qa=Ke.extend({method:U("prompts/get"),params:IC}),_p=N({type:U("text"),text:x(),annotations:Ro.optional(),_meta:ke(x(),Re()).optional()}),Sp=N({type:U("image"),data:gp,mimeType:x(),annotations:Ro.optional(),_meta:ke(x(),Re()).optional()}),xp=N({type:U("audio"),data:gp,mimeType:x(),annotations:Ro.optional(),_meta:ke(x(),Re()).optional()}),AC=N({type:U("tool_use"),name:x(),id:x(),input:ke(x(),Re()),_meta:ke(x(),Re()).optional()}),NC=N({type:U("resource"),resource:be([W_,K_]),annotations:Ro.optional(),_meta:ke(x(),Re()).optional()}),DC=G_.extend({type:U("resource_link")}),kp=be([_p,Sp,xp,DC,NC]),MC=N({role:Ws,content:kp}),jC=Ge.extend({description:x().optional(),messages:ie(MC)}),zC=Mt.extend({method:U("notifications/prompts/list_changed"),params:Dt.optional()}),LC=N({title:x().optional(),readOnlyHint:qe().optional(),destructiveHint:qe().optional(),idempotentHint:qe().optional(),openWorldHint:qe().optional()}),HC=N({taskSupport:yt(["required","optional","forbidden"]).optional()}),J_=N({...To.shape,...Fs.shape,description:x().optional(),inputSchema:N({type:U("object"),properties:ke(x(),Ze).optional(),required:ie(x()).optional()}).catchall(Re()),outputSchema:N({type:U("object"),properties:ke(x(),Ze).optional(),required:ie(x()).optional()}).catchall(Re()).optional(),annotations:LC.optional(),execution:HC.optional(),_meta:ke(x(),Re()).optional()}),Ur=Zs.extend({method:U("tools/list")}),UC=Bs.extend({tools:ie(J_)}),Va=Ge.extend({content:ie(kp).default([]),structuredContent:ke(x(),Re()).optional(),isError:qe().optional()}),iZ=Va.or(Ge.extend({toolResult:Re()})),FC=Hs.extend({name:x(),arguments:ke(x(),Re()).optional()}),Io=Ke.extend({method:U("tools/call"),params:FC}),ZC=Mt.extend({method:U("notifications/tools/list_changed"),params:Dt.optional()}),aZ=N({autoRefresh:qe().default(!0),debounceMs:fe().int().nonnegative().default(300)}),Ks=yt(["debug","info","notice","warning","error","critical","alert","emergency"]),BC=Pt.extend({level:Ks}),bp=Ke.extend({method:U("logging/setLevel"),params:BC}),qC=Dt.extend({level:Ks,logger:x().optional(),data:Re()}),VC=Mt.extend({method:U("notifications/message"),params:qC}),WC=N({name:x().optional()}),KC=N({hints:ie(WC).optional(),costPriority:fe().min(0).max(1).optional(),speedPriority:fe().min(0).max(1).optional(),intelligencePriority:fe().min(0).max(1).optional()}),GC=N({mode:yt(["auto","required","none"]).optional()}),JC=N({type:U("tool_result"),toolUseId:x().describe("The unique identifier for the corresponding tool call."),content:ie(kp).default([]),structuredContent:N({}).loose().optional(),isError:qe().optional(),_meta:ke(x(),Re()).optional()}),XC=ip("type",[_p,Sp,xp]),Oa=ip("type",[_p,Sp,xp,AC,JC]),YC=N({role:Ws,content:be([Oa,ie(Oa)]),_meta:ke(x(),Re()).optional()}),QC=Hs.extend({messages:ie(YC),modelPreferences:KC.optional(),systemPrompt:x().optional(),includeContext:yt(["none","thisServer","allServers"]).optional(),temperature:fe().optional(),maxTokens:fe().int(),stopSequences:ie(x()).optional(),metadata:Ze.optional(),tools:ie(J_).optional(),toolChoice:GC.optional()}),e$=Ke.extend({method:U("sampling/createMessage"),params:QC}),Gs=Ge.extend({model:x(),stopReason:Ce(yt(["endTurn","stopSequence","maxTokens"]).or(x())),role:Ws,content:XC}),vp=Ge.extend({model:x(),stopReason:Ce(yt(["endTurn","stopSequence","maxTokens","toolUse"]).or(x())),role:Ws,content:be([Oa,ie(Oa)])}),t$=N({type:U("boolean"),title:x().optional(),description:x().optional(),default:qe().optional()}),n$=N({type:U("string"),title:x().optional(),description:x().optional(),minLength:fe().optional(),maxLength:fe().optional(),format:yt(["email","uri","date","date-time"]).optional(),default:x().optional()}),r$=N({type:yt(["number","integer"]),title:x().optional(),description:x().optional(),minimum:fe().optional(),maximum:fe().optional(),default:fe().optional()}),o$=N({type:U("string"),title:x().optional(),description:x().optional(),enum:ie(x()),default:x().optional()}),s$=N({type:U("string"),title:x().optional(),description:x().optional(),oneOf:ie(N({const:x(),title:x()})),default:x().optional()}),i$=N({type:U("string"),title:x().optional(),description:x().optional(),enum:ie(x()),enumNames:ie(x()).optional(),default:x().optional()}),a$=be([o$,s$]),c$=N({type:U("array"),title:x().optional(),description:x().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:N({type:U("string"),enum:ie(x())}),default:ie(x()).optional()}),u$=N({type:U("array"),title:x().optional(),description:x().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:N({anyOf:ie(N({const:x(),title:x()}))}),default:ie(x()).optional()}),l$=be([c$,u$]),d$=be([i$,a$,l$]),p$=be([d$,t$,n$,r$]),f$=Hs.extend({mode:U("form").optional(),message:x(),requestedSchema:N({type:U("object"),properties:ke(x(),p$),required:ie(x()).optional()})}),m$=Hs.extend({mode:U("url"),message:x(),elicitationId:x(),url:x().url()}),h$=be([f$,m$]),g$=Ke.extend({method:U("elicitation/create"),params:h$}),y$=Dt.extend({elicitationId:x()}),_$=Mt.extend({method:U("notifications/elicitation/complete"),params:y$}),Ao=Ge.extend({action:yt(["accept","decline","cancel"]),content:ap(t=>t===null?void 0:t,ke(x(),be([x(),fe(),qe(),ie(x())])).optional())}),S$=N({type:U("ref/resource"),uri:x()});var x$=N({type:U("ref/prompt"),name:x()}),k$=Pt.extend({ref:be([x$,S$]),argument:N({name:x(),value:x()}),context:N({arguments:ke(x(),x()).optional()}).optional()}),Wa=Ke.extend({method:U("completion/complete"),params:k$});function X_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Y_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var b$=Ge.extend({completion:at({values:ie(x()).max(100),total:Ce(fe().int()),hasMore:Ce(qe())})}),v$=N({uri:x().startsWith("file://"),name:x().optional(),_meta:ke(x(),Re()).optional()}),E$=Ke.extend({method:U("roots/list"),params:Pt.optional()}),Ep=Ge.extend({roots:ie(v$)}),w$=Mt.extend({method:U("notifications/roots/list_changed"),params:Dt.optional()}),cZ=be([Ma,mp,Wa,bp,qa,Oo,Co,$o,Ba,EC,TC,Io,Ur,za,Ha,Ua,Za]),uZ=be([Da,ja,hp,w$,Vs]),lZ=be([Na,Gs,vp,Ao,Ep,La,Fa,Po]),dZ=be([Ma,e$,g$,E$,za,Ha,Ua,Za]),pZ=be([Da,ja,VC,RC,bC,ZC,zC,Vs,_$]),fZ=be([Na,dC,b$,jC,OC,_C,SC,kC,Va,UC,La,Fa,Po]),L=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===Z.UrlElicitationRequired&&r){let o=r;if(o.elicitations)return new cp(o.elicitations,n)}return new t(e,n,r)}},cp=class extends L{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(Z.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function er(t){return t==="completed"||t==="failed"||t==="cancelled"}var eS=Symbol("Let zodToJsonSchema decide on which parser to use");var Q_={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"},tS=t=>typeof t=="string"?{...Q_,name:t}:{...Q_,...t};var nS=t=>{let e=tS(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function wp(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ae(t,e,n,r,o){t[e]=n,wp(t,e,r,o)}var Ka=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")};function $e(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Ka(e,t.currentPath):e.join("/")}}function rS(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==w.ZodAny&&(n.items=W(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ae(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ae(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ae(n,"minItems",t.exactLength.value,t.exactLength.message,e),ae(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function oS(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?ae(n,"minimum",r.value,r.message,e):ae(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,e):ae(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,e));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,e);break}return n}function sS(){return{type:"boolean"}}function Ga(t,e){return W(t.type._def,e)}var iS=(t,e)=>W(t.innerType._def,e);function Tp(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>Tp(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return T$(t,e)}}var T$=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":ae(n,"minimum",r.value,r.message,e);break;case"max":ae(n,"maximum",r.value,r.message,e);break}return n};function aS(t,e){return{...W(t.innerType._def,e),default:t.defaultValue()}}function cS(t,e){return e.effectStrategy==="input"?W(t.schema._def,e):$e(e)}function uS(t){return{type:"string",enum:Array.from(t.values)}}var P$=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function lS(t,e){let n=[W(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),W(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(s=>{if(P$(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else r=void 0;o.push(i)}}),o.length?{allOf:o,...r}:void 0}function dS(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var Pp,Xt={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:()=>(Pp===void 0&&(Pp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Pp),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ja(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":ae(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Yt(n,"email",r.message,e);break;case"format:idn-email":Yt(n,"idn-email",r.message,e);break;case"pattern:zod":ct(n,Xt.email,r.message,e);break}break;case"url":Yt(n,"uri",r.message,e);break;case"uuid":Yt(n,"uuid",r.message,e);break;case"regex":ct(n,r.regex,r.message,e);break;case"cuid":ct(n,Xt.cuid,r.message,e);break;case"cuid2":ct(n,Xt.cuid2,r.message,e);break;case"startsWith":ct(n,RegExp(`^${Rp(r.value,e)}`),r.message,e);break;case"endsWith":ct(n,RegExp(`${Rp(r.value,e)}$`),r.message,e);break;case"datetime":Yt(n,"date-time",r.message,e);break;case"date":Yt(n,"date",r.message,e);break;case"time":Yt(n,"time",r.message,e);break;case"duration":Yt(n,"duration",r.message,e);break;case"length":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),ae(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{ct(n,RegExp(Rp(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&Yt(n,"ipv4",r.message,e),r.version!=="v4"&&Yt(n,"ipv6",r.message,e);break}case"base64url":ct(n,Xt.base64url,r.message,e);break;case"jwt":ct(n,Xt.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&ct(n,Xt.ipv4Cidr,r.message,e),r.version!=="v4"&&ct(n,Xt.ipv6Cidr,r.message,e);break}case"emoji":ct(n,Xt.emoji(),r.message,e);break;case"ulid":{ct(n,Xt.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Yt(n,"binary",r.message,e);break}case"contentEncoding:base64":{ae(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{ct(n,Xt.base64,r.message,e);break}}break}case"nanoid":ct(n,Xt.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Rp(t,e){return e.patternStrategy==="escape"?C$(t):t}var R$=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function C$(t){let e="";for(let n=0;n<t.length;n++)R$.has(t[n])||(e+="\\"),e+=t[n];return e}function Yt(t,e,n,r){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):ae(t,"format",e,n,r)}function ct(t,e,n,r){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:pS(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ae(t,"pattern",pS(e,r),n,r)}function pS(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<r.length;c++){if(s){o+=r[c],s=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){a?(o+=r[c],o+=`${r[c-2]}-${r[c]}`.toUpperCase(),a=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(o+=r[c],a=!0):o+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){o+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){o+=`(^|(?<=[\r
|
|
223
|
+
]))`;continue}else if(r[c]==="$"){o+=`($|(?=[\r
|
|
224
|
+
]))`;continue}}if(n.s&&r[c]==="."){o+=i?`${r[c]}\r
|
|
225
|
+
`:`[${r[c]}\r
|
|
226
|
+
]`;continue}o+=r[c],r[c]==="\\"?s=!0:i&&r[c]==="]"?i=!1:!i&&r[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function Xa(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===w.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??$e(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===w.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=Ja(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===w.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===w.ZodBranded&&t.keyType._def.type._def.typeName===w.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=Ga(t.keyType._def,e);return{...n,propertyNames:o}}}return n}function fS(t,e){if(e.mapStrategy==="record")return Xa(t,e);let n=W(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||$e(e),r=W(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||$e(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function mS(t){let e=t.values,r=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}function hS(t){return t.target==="openAi"?void 0:{not:$e({...t,currentPath:[...t.currentPath,"not"]})}}function gS(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Js={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function _S(t,e){if(e.target==="openApi3")return yS(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Js&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,s)=>{let i=Js[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(r.length===n.length){let o=r.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:n.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return yS(t,e)}var yS=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>W(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function SS(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:Js[t.innerType._def.typeName],nullable:!0}:{type:[Js[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=W(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=W(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function xS(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",wp(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ae(n,"minimum",r.value,r.message,e):ae(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,e):ae(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,e));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,e);break}return n}function kS(t,e){let n=e.target==="openAi",r={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=O$(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=W(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(r.properties[a]=l,u||o.push(a))}o.length&&(r.required=o);let i=$$(t,e);return i!==void 0&&(r.additionalProperties=i),r}function $$(t,e){if(t.catchall._def.typeName!=="ZodNever")return W(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 O$(t){try{return t.isOptional()}catch{return!0}}var bS=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return W(t.innerType._def,e);let n=W(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:$e(e)},n]}:$e(e)};var vS=(t,e)=>{if(e.pipeStrategy==="input")return W(t.in._def,e);if(e.pipeStrategy==="output")return W(t.out._def,e);let n=W(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=W(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function ES(t,e){return W(t.type._def,e)}function wS(t,e){let r={type:"array",uniqueItems:!0,items:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}function TS(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>W(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:W(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>W(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function PS(t){return{not:$e(t)}}function RS(t){return $e(t)}var CS=(t,e)=>W(t.innerType._def,e);var $S=(t,e,n)=>{switch(e){case w.ZodString:return Ja(t,n);case w.ZodNumber:return xS(t,n);case w.ZodObject:return kS(t,n);case w.ZodBigInt:return oS(t,n);case w.ZodBoolean:return sS();case w.ZodDate:return Tp(t,n);case w.ZodUndefined:return PS(n);case w.ZodNull:return gS(n);case w.ZodArray:return rS(t,n);case w.ZodUnion:case w.ZodDiscriminatedUnion:return _S(t,n);case w.ZodIntersection:return lS(t,n);case w.ZodTuple:return TS(t,n);case w.ZodRecord:return Xa(t,n);case w.ZodLiteral:return dS(t,n);case w.ZodEnum:return uS(t);case w.ZodNativeEnum:return mS(t);case w.ZodNullable:return SS(t,n);case w.ZodOptional:return bS(t,n);case w.ZodMap:return fS(t,n);case w.ZodSet:return wS(t,n);case w.ZodLazy:return()=>t.getter()._def;case w.ZodPromise:return ES(t,n);case w.ZodNaN:case w.ZodNever:return hS(n);case w.ZodEffects:return cS(t,n);case w.ZodAny:return $e(n);case w.ZodUnknown:return RS(n);case w.ZodDefault:return aS(t,n);case w.ZodBranded:return Ga(t,n);case w.ZodReadonly:return CS(t,n);case w.ZodCatch:return iS(t,n);case w.ZodPipeline:return vS(t,n);case w.ZodFunction:case w.ZodVoid:case w.ZodSymbol:return;default:return(r=>{})(e)}};function W(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==eS)return a}if(r&&!n){let a=I$(r,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=$S(t,t.typeName,e),i=typeof s=="function"?W(s(),e):s;if(i&&A$(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var I$=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ka(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),$e(e)):e.$refStrategy==="seen"?$e(e):void 0}},A$=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n);var Cp=(t,e)=>{let n=nS(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:W(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??$e(n)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=W(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??$e(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=o===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:s}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function N$(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function $p(t,e){return Nt(t)?Yd(t,{target:N$(e?.target),io:e?.pipeStrategy??"input"}):Cp(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Op(t){let n=Yn(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Ra(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function Ip(t,e){let n=Xn(t,e);if(!n.success)throw n.error;return n.data}var D$=6e4,Ya=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(Da,n=>{this._oncancel(n)}),this.setNotificationHandler(ja,n=>{this._onprogress(n)}),this.setRequestHandler(Ma,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(za,async(n,r)=>{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new L(Z.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ha,async(n,r)=>{let o=async()=>{let s=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,r.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,f=new L(d.error.code,d.error.message,d.error.data);l(f)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(s,r.sessionId);if(!i)throw new L(Z.InvalidParams,`Task not found: ${s}`);if(!er(i.status))return await this._waitForTaskUpdate(s,r.signal),await o();if(er(i.status)){let a=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Qn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ua,async(n,r)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new L(Z.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Za,async(n,r)=>{try{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new L(Z.InvalidParams,`Task not found: ${n.params.taskId}`);if(er(o.status))throw new L(Z.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new L(Z.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof L?o:new L(Z.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,r,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),L.fromError(Z.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Us(s)||F_(s)?this._onresponse(s):dp(s)?this._onrequest(s,i):U_(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=L.fromError(Z.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Qn]?.taskId;if(r===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Z.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=z_(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(i.signal.aborted)throw new L(Z.ConnectionClosed,"Request was cancelled");let m={...f,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let p=m.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,m)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Z.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...r}=e.params,o=Number(n),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Us(e))r(e);else{let i=new L(e.error.code,e.error.message,e.error.data);r(i)}return}let o=this._responseHandlers.get(n);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let s=!1;if(Us(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,n))}}if(s||this._progressHandlers.delete(n),Us(e))o(e);else{let i=L.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof L?i:new L(Z.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Po,r);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new L(Z.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:a},er(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)}:a.status==="failed"?yield{type:"error",error:new L(Z.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new L(Z.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof L?i:new L(Z.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=r??{};return new Promise((u,l)=>{let d=_=>{l(_)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(_){d(_);return}r?.signal?.throwIfAborted();let f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};r?.onprogress&&(this._progressHandlers.set(f,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Qn]:c}});let p=_=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let S=_ instanceof L?_:new L(Z.RequestTimeout,String(_));l(S)};this._responseHandlers.set(f,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return l(_);try{let S=Xn(n,_.result);S.success?u(S.data):l(S.error)}catch(S){l(S)}}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});let h=r?.timeout??D$,g=()=>p(L.fromError(Z.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=S=>{let k=this._responseHandlers.get(f);k?k(S):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,_),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(S=>{this._cleanupTimeout(f),l(S)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(f),l(_)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},La,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Fa,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},q_,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Qn]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Qn]:n.relatedTask}}}),this._transport?.send(a,n).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Qn]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=Op(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{let i=Ip(e,o);return Promise.resolve(n(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let r=Op(e);this._notificationHandlers.set(r,o=>{let s=Ip(e,o);return Promise.resolve(n(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,r,o)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let o of r)if(o.type==="request"&&dp(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new L(Z.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,s)=>{if(n.aborted){s(new L(Z.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(i),s(new L(Z.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},n)},getTask:async o=>{let s=await r.getTask(o,n);if(!s)throw new L(Z.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await r.storeTaskResult(o,s,i,n);let a=await r.getTask(o,n);if(a){let c=Vs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),er(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>r.getTaskResult(o,n),updateTaskStatus:async(o,s,i)=>{let a=await r.getTask(o,n);if(!a)throw new L(Z.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(er(a.status))throw new L(Z.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,s,i,n);let c=await r.getTask(o,n);if(c){let u=Vs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),er(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}};function OS(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function IS(t,e){let n={...t};for(let r in e){let o=r,s=e[o];if(s===void 0)continue;let i=n[o];OS(i)&&OS(s)?n[o]={...i,...s}:n[o]=s}return n}var _b=jg(_m(),1),Sb=jg(yb(),1);function TM(){let t=new _b.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Sb.default)(t),t}var Nc=class{constructor(e){this._ajv=e??TM()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var Dc=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(s.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==d.size||![...l].every(f=>d.has(f)))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},Gs,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Ao,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}};function xb(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function kb(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Mc=class extends Ya{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ks.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new Nc,this.setRequestHandler(mp,r=>this._oninitialize(r)),this.setNotificationHandler(hp,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(bp,async(r,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=Ks.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Dc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=IS(this._capabilities,e)}setRequestHandler(e,n){let o=Yn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Nt(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Xn(Io,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new L(Z.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,f=await Promise.resolve(n(c,u));if(d.task){let p=Xn(Po,f);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new L(Z.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let m=Xn(Va,f);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new L(Z.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){kb(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&xb(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:D_.includes(n)?n:up,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"},Na)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},vp,n):this.request({method:"sampling/createMessage",params:e},Gs,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Ao,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Ao,n);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new L(Z.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof L?i:new L(Z.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},Ep,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var vb=Symbol.for("mcp.completable");function Tm(t){return!!t&&typeof t=="object"&&vb in t}function Eb(t){return t[vb]?.complete}var bb;(function(t){t.Completable="McpCompletable"})(bb||(bb={}));var PM=/^[A-Za-z0-9._-]{1,128}$/;function RM(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"),!PM.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,s)=>s.indexOf(r)===o);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function CM(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Pm(t){let e=RM(t);return CM(t,e.warnings),e.isValid}var jc=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let o={taskSupport:"required",...n.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,o,n._meta,r)}};var zc=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Mc(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new jc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(ur(Ur)),this.server.assertCanSetRequestHandler(ur(Io)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ur,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let o=wo(n.inputSchema);return o?$p(o,{strictUnions:!0,pipeStrategy:"input"}):$M})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let o=wo(n.outputSchema);o&&(r.outputSchema=$p(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Io,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new L(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new L(Z.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=r.execution?.taskSupport,i="createTask"in r.handler;if((s==="required"||s==="optional")&&!i)throw new L(Z.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new L(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,a,n);return o||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof L&&r.code===Z.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let s=wo(e.inputSchema)??e.inputSchema,i=await Ta(s,n);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Pa(a);throw new L(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new L(Z.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=wo(e.outputSchema),s=await Ta(o,n.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Pa(i);throw new L(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(n,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(n,r))}else{let i=o;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,n.params.arguments,n.params.name),s=e.handler,i={...r,taskStore:r.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(f=>setTimeout(f,l));let d=await r.taskStore.getTask(c);if(!d)throw new L(Z.InternalError,`Task ${c} not found during polling`);u=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ur(Wa)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Wa,async e=>{switch(e.params.ref.type){case"ref/prompt":return X_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Y_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new L(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new L(Z.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new L(Z.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return Ti;let s=Yn(r.argsSchema)?.[e.params.argument.name];if(!Tm(s))return Ti;let i=Eb(s);if(!i)return Ti;let a=await i(e.params.argument.value,e.params.context);return Tb(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return Ti;throw new L(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Ti;let s=await o(e.params.argument.value,e.params.context);return Tb(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ur(Co)),this.server.assertCanSetRequestHandler(ur($o)),this.server.assertCanSetRequestHandler(ur(Ba)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Co,async(e,n)=>{let r=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(n);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...r,...o]}}),this.server.setRequestHandler($o,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Ba,async(e,n)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new L(Z.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,n)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(r.toString());if(i)return s.readCallback(r,i,n)}throw new L(Z.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ur(Oo)),this.server.assertCanSetRequestHandler(ur(qa)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Oo,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?OM(n.argsSchema):void 0}))})),this.server.setRequestHandler(qa,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new L(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new L(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=wo(r.argsSchema),s=await Ta(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Pa(c);throw new L(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let o=r.callback;return await Promise.resolve(o(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let o;typeof r[0]=="object"&&(o=r.shift());let s=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,o){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let s=this._createRegisteredResource(e,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,n,r,o,s){let i={name:e,title:n,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==r&&(delete this._registeredResources[r],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,n,r,o,s){let i={resourceTemplate:r,title:n,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,o,s){let i={title:n,description:r,argsSchema:o===void 0?void 0:Hr(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Hr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof ht?c._def?.innerType:c;return Tm(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,o,s,i,a,c,u){Pm(e);let l={title:n,description:r,inputSchema:wb(o),outputSchema:wb(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&Pm(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Hr(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Hr(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,o,s,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let c=n[0];if(Rm(c))o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!Rm(n[0])&&(i=n.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=n;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let o;n.length>1&&(o=n.shift());let s=n[0],i=this._createRegisteredPrompt(e,void 0,r,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=n,a=this._createRegisteredPrompt(e,o,s,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var $M={type:"object",properties:{}};function Pb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Rb(t){return"_def"in t||"_zod"in t||Pb(t)}function Rm(t){return typeof t!="object"||t===null||Rb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Pb)}function wb(t){if(t){if(Rm(t))return Hr(t);if(!Rb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function OM(t){let e=Yn(t);return e?Object.entries(e).map(([n,r])=>{let o=d_(r),s=p_(r);return{name:n,description:o,required:!s}}):[]}function ur(t){let n=Yn(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Ra(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function Tb(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Ti={completion:{values:[],hasMore:!1}};import $b from"node:process";var Lc=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
227
|
+
`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),IM(n)}clear(){this._buffer=void 0}};function IM(t){return Z_.parse(JSON.parse(t))}function Cb(t){return JSON.stringify(t)+`
|
|
228
|
+
`}var Hc=class{constructor(e=$b.stdin,n=$b.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Lc,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{this.onerror?.(r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(n=>{let r=Cb(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}};import{createRequire as pT}from"node:module";import{existsSync as ze,unlinkSync as xs,readdirSync as fT,readFileSync as ta,writeFileSync as Uu,writeSync as J1,renameSync as X1,rmSync as mT,mkdirSync as Y1,statSync as hT,symlinkSync as Q1,lstatSync as gT,realpathSync as yT}from"node:fs";import{spawnSync as Fu}from"node:child_process";import{join as Et,dirname as bs,resolve as pt,sep as eH,isAbsolute as tH}from"node:path";import{fileURLToPath as nH}from"node:url";import{homedir as ks,tmpdir as Eg,cpus as rH}from"node:os";import{request as oH}from"node:https";import{AsyncLocalStorage as sH}from"node:async_hooks";Zc();import{spawn as Lb,execSync as ZM,execFileSync as Zb}from"node:child_process";import{mkdtempSync as BM,writeFileSync as Hb,rmSync as qM,existsSync as Ub}from"node:fs";import{join as Vc,resolve as Bb}from"node:path";import{tmpdir as VM}from"node:os";var bt=process.platform==="win32",WM={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};function KM(t,e,n){if(e==="win32"&&t==="shell"){let r=n?.toLowerCase()??"";if(r.includes("powershell")||r.includes("pwsh"))return"script.ps1";let o=r.split(/[\\/]/).pop()??r;return o==="cmd"||o==="cmd.exe"?"script.cmd":"script"}return`script.${WM[t]}`}function GM(t){return{windowsHide:t==="win32"}}function JM(t){return`'${t.replace(/'/g,"'\\''")}'`}function XM(t,e,n){return n==="win32"||!e?t:`export PATH=${JM(e)}
|
|
229
|
+
${t}`}function YM(t){let e=t?.toLowerCase()??"";return e.includes("powershell")||e.includes("pwsh")}function QM(t){return["\uFEFF[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()","[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()","$OutputEncoding = [System.Text.UTF8Encoding]::new()",t].join(`
|
|
230
|
+
`)}var ej=(()=>{if(bt)return process.env.TEMP??process.env.TMP??VM();try{let t=Zb(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:Bb(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();function tj(t,e){if(e!=="win32")return t;let n=new Set([";","&","|","(",`
|
|
231
|
+
`]),r="",o=!0,s=0;for(;s<t.length;){let i=t[s];if(o&&(i===" "||i===" ")){r+=i,s++;continue}if(o&&t.startsWith("mvn",s)){let a=t[s+3];if(a===void 0||a===" "||a===" "||a===`
|
|
232
|
+
`){r+="mvn.cmd",s+=3,o=!1;continue}}r+=i,o=n.has(i),s++}return r}function Fb(t){try{qM(t,{recursive:!0,force:!0,maxRetries:bt?8:2,retryDelay:100})}catch{}}function Nm(t){if(bt&&t.pid)try{ZM(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var Ci=class{#e;#t;#n;#o=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let n=e?.projectRoot;typeof n=="function"?this.#t=n:typeof n=="string"?this.#t=()=>n:this.#t=()=>process.cwd(),this.#n=e?.runtimes??Bc()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(bt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:n,code:r,timeout:o,background:s=!1,cwd:i}=e,a=BM(Vc(ej,".ctx-mode-"));try{let c=this.#a(a,r,n),u=zb(this.#n,n,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,o);let l=i??this.#s,d=await this.#i(u,l,a,o,s);return d.backgrounded||Fb(a),d}catch(c){throw Fb(a),c}}async executeFile(e){let{path:n,language:r,code:o,timeout:s}=e,i=Bb(this.#s,n),a=this.#l(i,r,o);return this.execute({language:r,code:a,timeout:s})}#a(e,n,r){r==="go"&&!n.includes("package ")&&(n=`package main
|
|
225
233
|
|
|
226
234
|
import "fmt"
|
|
227
235
|
|
|
228
236
|
func main() {
|
|
229
|
-
${
|
|
237
|
+
${n}
|
|
230
238
|
}
|
|
231
|
-
`),
|
|
232
|
-
${
|
|
239
|
+
`),r==="php"&&!n.trimStart().startsWith("<?")&&(n=`<?php
|
|
240
|
+
${n}`),r==="elixir"&&Ub(Vc(this.#s,"mix.exs"))&&(n=`Path.wildcard(Path.join(${JSON.stringify(Vc(this.#s,"_build/dev/lib"))}, "*/ebin"))
|
|
233
241
|
|> Enum.each(&Code.prepend_path/1)
|
|
234
242
|
|
|
235
|
-
${
|
|
236
|
-
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],
|
|
237
|
-
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:
|
|
243
|
+
${n}`);let o=Vc(e,KM(r,process.platform,r==="shell"?this.#n.shell:null));if(r==="shell"){let s=this.#n.shell,i=tj(n,process.platform),a=bt&&YM(s)?QM(i):i;Hb(o,XM(a,process.env.PATH,process.platform),{encoding:"utf-8",mode:448})}else Hb(o,n,"utf-8");return o}async#c(e,n,r){let o=bt?".exe":"",s=e.replace(/\.rs$/,"")+o;try{Zb("rustc",[e,"-o",s],{cwd:n,timeout:r===void 0?6e4:Math.min(r,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
|
|
244
|
+
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],n,n,r)}async#i(e,n,r,o,s=!1){return new Promise(i=>{let a=bt&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;bt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=bt?e.slice(1).map(S=>S.replace(/\\/g,"/")):e.slice(1);let l={cwd:n,stdio:["ignore","pipe","pipe"],env:this.#u(r),detached:!bt,...GM(process.platform)},d;if(a){let S=[c,...u].map(k=>/\s/.test(k)?JSON.stringify(k):k).join(" ");d=Lb(S,[],{...l,shell:!0})}else d=Lb(c,u,{...l,shell:!1});let f=!1,m=!1,p=o===void 0?void 0:setTimeout(()=>{if(f=!0,s){m=!0,d.pid&&this.#o.add(d.pid),d.unref(),d.stdout&&(d.stdout.removeAllListeners("data"),d.stdout.on("data",()=>{})),d.stderr&&(d.stderr.removeAllListeners("data"),d.stderr.on("data",()=>{}));let S=Buffer.concat(h).toString("utf-8"),k=Buffer.concat(g).toString("utf-8");i({stdout:S,stderr:k,exitCode:0,timedOut:!0,backgrounded:!0})}else Nm(d)},o),h=[],g=[],y=0,_=!1;d.stdout.on("data",S=>{y+=S.length,y<=this.#e?h.push(S):_||(_=!0,Nm(d))}),d.stderr.on("data",S=>{y+=S.length,y<=this.#e?g.push(S):_||(_=!0,Nm(d))}),d.on("close",S=>{if(clearTimeout(p),m)return;let k=Buffer.concat(h).toString("utf-8"),v=Buffer.concat(g).toString("utf-8");_&&(v+=`
|
|
245
|
+
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:k,stderr:v,exitCode:f?1:S??1,timedOut:f})}),d.on("error",S=>{clearTimeout(p),!m&&i({stdout:"",stderr:S.message,exitCode:1,timedOut:!1})})})}#u(e){let n=process.env.HOME??process.env.USERPROFILE??e,r=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","DOTNET_STARTUP_HOOKS","DOTNET_ADDITIONAL_DEPS","DOTNET_SHARED_STORE","DOTNET_ROOT","DOTNET_ROOT(x86)","DOTNET_HOST_PATH","CORECLR_PROFILER","CORECLR_PROFILER_PATH","CORECLR_PROFILER_PATH_32","CORECLR_PROFILER_PATH_64","CORECLR_PROFILER_PATH_ARM32","CORECLR_PROFILER_PATH_ARM64","CORECLR_ENABLE_PROFILING","DOTNET_PROFILER_PATH","DOTNET_PROFILER_PATH_32","DOTNET_PROFILER_PATH_64","DOTNET_PROFILER_PATH_ARM32","DOTNET_PROFILER_PATH_ARM64","DOTNET_DiagnosticPorts","DOTNET_BUNDLE_EXTRACT_BASE_DIR","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),o={};for(let[s,i]of Object.entries(process.env))i!==void 0&&!r.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=n,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",bt&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=bt?"":"/usr/local/bin:/usr/bin:/bin"),bt){for(let a of Object.keys(o)){let c=a.toUpperCase();(c==="MSYS_NO_PATHCONV"||c==="MSYS2_ARG_CONV_EXCL")&&delete o[a]}let s="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";o.PATH.includes(s)||(o.PATH=`${s};${i};${o.PATH}`)}if(!o.SSL_CERT_FILE){let s=bt?[]:["/etc/ssl/cert.pem","/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"];for(let i of s)if(Ub(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,n,r){let o=JSON.stringify(e);switch(n){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
|
|
238
246
|
const file_path = FILE_CONTENT_PATH;
|
|
239
247
|
const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
|
|
240
|
-
${
|
|
248
|
+
${r}`;case"python":return`FILE_CONTENT_PATH = ${o}
|
|
241
249
|
file_path = FILE_CONTENT_PATH
|
|
242
250
|
with open(FILE_CONTENT_PATH, "r", encoding="utf-8") as _f:
|
|
243
251
|
FILE_CONTENT = _f.read()
|
|
244
|
-
${
|
|
252
|
+
${r}`;case"shell":{let s="'"+e.replace(/'/g,"'\\''")+"'";return`FILE_CONTENT_PATH=${s}
|
|
245
253
|
file_path=${s}
|
|
246
254
|
FILE_CONTENT=$(cat ${s})
|
|
247
|
-
${
|
|
255
|
+
${r}`}case"ruby":return`FILE_CONTENT_PATH = ${o}
|
|
248
256
|
file_path = FILE_CONTENT_PATH
|
|
249
257
|
FILE_CONTENT = File.read(FILE_CONTENT_PATH, encoding: "utf-8")
|
|
250
|
-
${
|
|
258
|
+
${r}`;case"go":return`package main
|
|
251
259
|
|
|
252
260
|
import (
|
|
253
261
|
"fmt"
|
|
@@ -262,7 +270,7 @@ func main() {
|
|
|
262
270
|
FILE_CONTENT := string(b)
|
|
263
271
|
_ = FILE_CONTENT
|
|
264
272
|
_ = fmt.Sprint()
|
|
265
|
-
${
|
|
273
|
+
${r}
|
|
266
274
|
}
|
|
267
275
|
`;case"rust":return`#![allow(unused_variables)]
|
|
268
276
|
use std::fs;
|
|
@@ -271,28 +279,28 @@ fn main() {
|
|
|
271
279
|
let file_content_path = ${o};
|
|
272
280
|
let file_path = file_content_path;
|
|
273
281
|
let file_content = fs::read_to_string(file_content_path).unwrap();
|
|
274
|
-
${
|
|
282
|
+
${r}
|
|
275
283
|
}
|
|
276
284
|
`;case"php":return`<?php
|
|
277
285
|
$FILE_CONTENT_PATH = ${o};
|
|
278
286
|
$file_path = $FILE_CONTENT_PATH;
|
|
279
287
|
$FILE_CONTENT = file_get_contents($FILE_CONTENT_PATH);
|
|
280
|
-
${
|
|
288
|
+
${r}`;case"perl":return`my $FILE_CONTENT_PATH = ${o};
|
|
281
289
|
my $file_path = $FILE_CONTENT_PATH;
|
|
282
290
|
open(my $fh, '<:encoding(UTF-8)', $FILE_CONTENT_PATH) or die "Cannot open: $!";
|
|
283
291
|
my $FILE_CONTENT = do { local $/; <$fh> };
|
|
284
292
|
close($fh);
|
|
285
|
-
${
|
|
293
|
+
${r}`;case"r":return`FILE_CONTENT_PATH <- ${o}
|
|
286
294
|
file_path <- FILE_CONTENT_PATH
|
|
287
295
|
FILE_CONTENT <- readLines(FILE_CONTENT_PATH, warn=FALSE, encoding="UTF-8")
|
|
288
296
|
FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
|
|
289
|
-
${
|
|
297
|
+
${r}`;case"elixir":return`file_content_path = ${o}
|
|
290
298
|
file_path = file_content_path
|
|
291
299
|
file_content = File.read!(file_content_path)
|
|
292
|
-
${
|
|
300
|
+
${r}`;case"csharp":return`var FILE_CONTENT_PATH = ${o};
|
|
293
301
|
var file_path = FILE_CONTENT_PATH;
|
|
294
302
|
var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
|
|
295
|
-
${
|
|
303
|
+
${r}`}}};import{cpus as nj}from"node:os";async function Dm(t,e){let{concurrency:n,capByCpuCount:r=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,n),i=r?Math.max(1,nj().length):s,a=Math.min(s,i,t.length),c=a<s,u=new Array(t.length),l=0;async function d(){for(;;){let m=l++;if(m>=t.length)return;try{let p=await t[m].run();u[m]={status:"fulfilled",value:p}}catch(p){u[m]={status:"rejected",reason:p}}o?.(m,u[m])}}let f=[];for(let m=0;m<a;m++)f.push(d());return await Promise.allSettled(f),{settled:u,effectiveConcurrency:a,capped:c}}es();import{readFileSync as Yb,readdirSync as ov,unlinkSync as Fm,existsSync as Um,statSync as Gc,openSync as Qb,fstatSync as ev,closeSync as tv}from"node:fs";import{createHash as nv}from"node:crypto";import{tmpdir as sv}from"node:os";import{join as Zm}from"node:path";import{readdirSync as dj,statSync as pj,lstatSync as fj,realpathSync as Wb,existsSync as mj,readFileSync as hj}from"node:fs";import{join as Gb,extname as gj,relative as Jb,sep as yj,resolve as _j}from"node:path";var Sj=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],xj=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],kj=5,bj=200;function vj(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];r==="*"?t[n+1]==="*"?(e+=".*",n++):e+="[^/]*":r==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(r)?e+="\\"+r:e+=r}return new RegExp(`^${e}$`)}function Kb(t,e){if(e.length===0)return!1;let n=t.split("/").pop()??t;for(let r of e){if(!r.includes("/")&&!r.includes("*")){if(n===r||t.split("/").includes(r))return!0;continue}let o=vj(r);if(o.test(t)||o.test(n))return!0}return!1}function Ej(t){let e=Gb(t,".gitignore");if(!mj(e))return[];try{return hj(e,"utf-8").split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#")&&!r.startsWith("!")).map(r=>r.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function wj(t,e){return Jb(t,e).split(yj).join("/")}function Xb(t,e={}){let{include:n,exclude:r,maxDepth:o=kj,maxFiles:s=bj,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=Wb(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:xj).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...Sj,...r??[],...a?Ej(u):[]],f=n??[],m=[],p=new Set([u]),h=0,g=!1;function y(_,S){if(g||S>o)return;let k;try{k=dj(_,{withFileTypes:!0})}catch{return}for(let v of k){if(g)return;let O=Gb(_,v.name),R=wj(u,O);if(Kb(R,d))continue;let M=v.isDirectory(),D=v.isFile(),V=!1;try{V=fj(O).isSymbolicLink()}catch{continue}if(V){if(!c)continue;let T;try{T=Wb(O)}catch{continue}let H=Jb(u,T);if((H.startsWith("..")||_j(H)===T)&&H.startsWith("..")||p.has(T))continue;p.add(T);try{let pe=pj(T);M=pe.isDirectory(),D=pe.isFile()}catch{continue}}if(M){y(O,S+1);continue}if(!D)continue;let P=gj(O).toLowerCase();if(l.includes(P)&&!(f.length>0&&!Kb(R,f))){if(h++,m.length>=s){g=!0;return}m.push(O)}}}return y(u,0),{files:m,capped:g,totalSeen:h}}var ts=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"]);function iv(t){let e=new Set,n=[];for(let r of t){let o=r.toLowerCase();e.has(o)||(e.add(o),n.push(r))}return n}function Tj(t,e="AND"){let n=iv(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(n.length===0)return'""';let r=n.filter(s=>!ts.has(s.toLowerCase()));return(r.length>0?r:n).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function Pj(t,e="AND"){let n=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(n.length<3)return"";let r=iv(n.split(/\s+/).filter(i=>i.length>=3));if(r.length===0)return"";let o=r.filter(i=>!ts.has(i.toLowerCase()));return(o.length>0?o:r).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function Rj(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let n=Array.from({length:e.length+1},(r,o)=>o);for(let r=1;r<=t.length;r++){let o=[r];for(let s=1;s<=e.length;s++)o[s]=t[r-1]===e[s-1]?n[s-1]:1+Math.min(n[s],o[s-1],n[s-1]);n=o}return n[e.length]}function Cj(t){return t<=4?1:t<=12?2:3}var Kc=4096,$j=3,Oj=200,Ij=5e3,rv=80,Aj=.5;function Bm(){let t=sv(),e=0;try{let n=ov(t);for(let r of n){let o=r.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=Zm(t,r);for(let a of["","-wal","-shm"])try{Fm(i+a)}catch{}e++}}}catch{}return e}function qm(t,e){let n=0;try{if(!Um(t))return 0;let r=Date.now()-e*24*60*60*1e3,o=ov(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=Zm(t,s),c=Gc(i).mtimeMs<r;if(!c){let u=i+"-wal";if(Um(u))try{let l=Gc(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Fm(i+u)}catch{}n++}}catch{}}catch{}return n}function Nj(t,e){let n=[],r=t.indexOf(e);for(;r!==-1;)n.push(r),r=t.indexOf(e,r+1);return n}function Dj(t,e,n=30){if(t.length<2||e.length<2)return 0;let r=0,o=Math.min(t.length,e.length)-1;for(let s=0;s<o;s++){let i=t[s],a=t[s+1],c=e[s].length,u=0;for(let l of i){let d=l+c,f=d+n;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=f&&(r++,u++)}}return r}function Mj(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t,n=new Array(e.length).fill(0),r=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][n[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<r&&(r=a),n[i]++,n[i]>=e[i].length)break}return r}var Jc=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#m;#h;#g;#y;#_;#S;#x;#k;#b;#v;#E;#w;#T;#P;#R;#C;#$;#O;#I;#A;#N;#D;#M;#j=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let n=Ye();this.#t=e??Zm(sv(),`context-mode-${process.pid}.db`),Ii(this.#t);let r;try{r=new n(this.#t,{timeout:3e4}),Oi(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(Hm(s)){Lm(this.#t),Ii(this.#t);try{r=new n(this.#t,{timeout:3e4}),Oi(r)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=r,this.#Z(),this.#B()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{Fm(this.#t+e)}catch{}}#Z(){this.#e.exec(`
|
|
296
304
|
CREATE TABLE IF NOT EXISTS sources (
|
|
297
305
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
298
306
|
label TEXT NOT NULL,
|
|
@@ -332,7 +340,7 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
332
340
|
);
|
|
333
341
|
|
|
334
342
|
CREATE INDEX IF NOT EXISTS idx_sources_label ON sources(label);
|
|
335
|
-
`);try{let e=this.#e.prepare("SELECT name FROM pragma_table_xinfo('chunks')").all(),
|
|
343
|
+
`);try{let e=this.#e.prepare("SELECT name FROM pragma_table_xinfo('chunks')").all(),n=new Set(e.map(r=>r.name));e.length>0&&!n.has("source_category")&&(this.#e.exec("DROP TABLE IF EXISTS chunks"),this.#e.exec("DROP TABLE IF EXISTS chunks_trigram"),this.#e.exec(`
|
|
336
344
|
CREATE VIRTUAL TABLE chunks USING fts5(
|
|
337
345
|
title,
|
|
338
346
|
content,
|
|
@@ -355,7 +363,7 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
355
363
|
timestamp UNINDEXED,
|
|
356
364
|
tokenize='trigram'
|
|
357
365
|
);
|
|
358
|
-
`))}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN file_path TEXT")}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN content_hash TEXT")}catch{}}#
|
|
366
|
+
`))}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN file_path TEXT")}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN content_hash TEXT")}catch{}}#B(){this.#o=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, 0, 0, ?, ?)"),this.#s=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, ?, ?, ?, ?)"),this.#a=this.#e.prepare("INSERT INTO chunks (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#c=this.#e.prepare("INSERT INTO chunks_trigram (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#i=this.#e.prepare("INSERT OR IGNORE INTO vocabulary (word) VALUES (?)"),this.#u=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#l=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#m=this.#e.prepare("DELETE FROM sources WHERE label = ?"),this.#h=this.#e.prepare(`
|
|
359
367
|
SELECT
|
|
360
368
|
chunks.title,
|
|
361
369
|
chunks.content,
|
|
@@ -370,7 +378,7 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
370
378
|
WHERE chunks MATCH ?
|
|
371
379
|
ORDER BY rank
|
|
372
380
|
LIMIT ?
|
|
373
|
-
`),this.#
|
|
381
|
+
`),this.#g=this.#e.prepare(`
|
|
374
382
|
SELECT
|
|
375
383
|
chunks.title,
|
|
376
384
|
chunks.content,
|
|
@@ -385,7 +393,7 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
385
393
|
WHERE chunks MATCH ? AND sources.label LIKE ? ESCAPE '\\'
|
|
386
394
|
ORDER BY rank
|
|
387
395
|
LIMIT ?
|
|
388
|
-
`),this.#
|
|
396
|
+
`),this.#y=this.#e.prepare(`
|
|
389
397
|
SELECT
|
|
390
398
|
chunks.title,
|
|
391
399
|
chunks.content,
|
|
@@ -400,7 +408,7 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
400
408
|
WHERE chunks MATCH ? AND sources.label = ?
|
|
401
409
|
ORDER BY rank
|
|
402
410
|
LIMIT ?
|
|
403
|
-
`),this.#
|
|
411
|
+
`),this.#_=this.#e.prepare(`
|
|
404
412
|
SELECT
|
|
405
413
|
chunks_trigram.title,
|
|
406
414
|
chunks_trigram.content,
|
|
@@ -415,7 +423,7 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
415
423
|
WHERE chunks_trigram MATCH ?
|
|
416
424
|
ORDER BY rank
|
|
417
425
|
LIMIT ?
|
|
418
|
-
`),this.#
|
|
426
|
+
`),this.#S=this.#e.prepare(`
|
|
419
427
|
SELECT
|
|
420
428
|
chunks_trigram.title,
|
|
421
429
|
chunks_trigram.content,
|
|
@@ -445,7 +453,7 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
445
453
|
WHERE chunks_trigram MATCH ? AND sources.label = ?
|
|
446
454
|
ORDER BY rank
|
|
447
455
|
LIMIT ?
|
|
448
|
-
`),this.#
|
|
456
|
+
`),this.#b=this.#e.prepare(`
|
|
449
457
|
SELECT
|
|
450
458
|
chunks.title,
|
|
451
459
|
chunks.content,
|
|
@@ -460,7 +468,7 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
460
468
|
WHERE chunks MATCH ? AND chunks.content_type = ?
|
|
461
469
|
ORDER BY rank
|
|
462
470
|
LIMIT ?
|
|
463
|
-
`),this.#
|
|
471
|
+
`),this.#v=this.#e.prepare(`
|
|
464
472
|
SELECT
|
|
465
473
|
chunks.title,
|
|
466
474
|
chunks.content,
|
|
@@ -475,7 +483,7 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
475
483
|
WHERE chunks MATCH ? AND sources.label LIKE ? ESCAPE '\\' AND chunks.content_type = ?
|
|
476
484
|
ORDER BY rank
|
|
477
485
|
LIMIT ?
|
|
478
|
-
`),this.#
|
|
486
|
+
`),this.#E=this.#e.prepare(`
|
|
479
487
|
SELECT
|
|
480
488
|
chunks.title,
|
|
481
489
|
chunks.content,
|
|
@@ -490,7 +498,7 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
490
498
|
WHERE chunks MATCH ? AND sources.label = ? AND chunks.content_type = ?
|
|
491
499
|
ORDER BY rank
|
|
492
500
|
LIMIT ?
|
|
493
|
-
`),this.#
|
|
501
|
+
`),this.#w=this.#e.prepare(`
|
|
494
502
|
SELECT
|
|
495
503
|
chunks_trigram.title,
|
|
496
504
|
chunks_trigram.content,
|
|
@@ -505,7 +513,7 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
505
513
|
WHERE chunks_trigram MATCH ? AND chunks_trigram.content_type = ?
|
|
506
514
|
ORDER BY rank
|
|
507
515
|
LIMIT ?
|
|
508
|
-
`),this.#
|
|
516
|
+
`),this.#T=this.#e.prepare(`
|
|
509
517
|
SELECT
|
|
510
518
|
chunks_trigram.title,
|
|
511
519
|
chunks_trigram.content,
|
|
@@ -520,7 +528,7 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
520
528
|
WHERE chunks_trigram MATCH ? AND sources.label LIKE ? ESCAPE '\\' AND chunks_trigram.content_type = ?
|
|
521
529
|
ORDER BY rank
|
|
522
530
|
LIMIT ?
|
|
523
|
-
`),this.#
|
|
531
|
+
`),this.#P=this.#e.prepare(`
|
|
524
532
|
SELECT
|
|
525
533
|
chunks_trigram.title,
|
|
526
534
|
chunks_trigram.content,
|
|
@@ -535,105 +543,109 @@ ${n}`}}};import{cpus as rM}from"node:os";async function xm(t,e){let{concurrency:
|
|
|
535
543
|
WHERE chunks_trigram MATCH ? AND sources.label = ? AND chunks_trigram.content_type = ?
|
|
536
544
|
ORDER BY rank
|
|
537
545
|
LIMIT ?
|
|
538
|
-
`),this.#
|
|
546
|
+
`),this.#k=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#R=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#C=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label
|
|
539
547
|
FROM chunks c
|
|
540
548
|
JOIN sources s ON s.id = c.source_id
|
|
541
549
|
WHERE c.source_id = ?
|
|
542
|
-
ORDER BY c.rowid`),this.#$=this.#e.prepare("SELECT chunk_count FROM sources WHERE id = ?"),this.#
|
|
550
|
+
ORDER BY c.rowid`),this.#$=this.#e.prepare("SELECT chunk_count FROM sources WHERE id = ?"),this.#O=this.#e.prepare("SELECT content FROM chunks WHERE source_id = ?"),this.#A=this.#e.prepare("SELECT label, chunk_count, code_chunk_count, indexed_at, file_path, content_hash FROM sources WHERE label = ?"),this.#I=this.#e.prepare(`
|
|
543
551
|
SELECT
|
|
544
552
|
(SELECT COUNT(*) FROM sources) AS sources,
|
|
545
553
|
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
546
554
|
(SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
|
|
547
|
-
`),this.#
|
|
555
|
+
`),this.#N=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#M=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:n,path:r,source:o,attribution:s}=e,i=typeof n=="string"&&n.length>0;if(!i&&!r)throw new Error("Either content or path must be provided");let a;if(i)a=n;else{let f=Qb(r,"r");try{if(!ev(f).isFile())throw new Error(`refusing to index ${r}: not a regular file`);a=Yb(f,"utf-8")}finally{tv(f)}}let c=o??r??"untitled",u=this.#K(a),l=r??void 0,d=l?nv("sha256").update(a).digest("hex"):void 0;return Yr(()=>this.#d(u,c,a,l,d,s))}indexDirectory(e){let{path:n,source:r,attribution:o,perFileDeny:s,...i}=e,a=Xb(n,i),c=0,u=0,l=0,d=0;for(let f of a.files){if(s&&s(f)){l++;continue}try{let m=r?`${r}:${f}`:f,p=this.index({path:f,source:m,attribution:o});c++,u+=p.totalChunks}catch{d++}}return{filesIndexed:c,totalChunks:u,capped:a.capped,totalSeen:a.totalSeen,denied:l,failed:d,label:r??n}}indexPlainText(e,n,r=20,o,s=Kc){if(!e||e.trim().length===0)return this.#d([],n,"",void 0,void 0,o);let i=this.#J(e,r,s);return Yr(()=>this.#d(i.map(a=>({...a,hasCode:!1})),n,e,void 0,void 0,o))}indexJSON(e,n,r=Kc,o){if(!e||e.trim().length===0)return this.indexPlainText("",n,void 0,o,r);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,n,void 0,o,r)}let i=[];return this.#F(s,[],i,r),i.length===0?this.indexPlainText(e,n,void 0,o,r):Yr(()=>this.#d(i,n,e,void 0,void 0,o))}#d(e,n,r,o,s,i){let a=e.filter(f=>f.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",d=this.#e.transaction(()=>{if(this.#u.run(n),this.#l.run(n),this.#m.run(n),e.length===0){let h=this.#o.run(n,o??null,s??null);return Number(h.lastInsertRowid)}let f=this.#s.run(n,e.length,a,o??null,s??null),m=Number(f.lastInsertRowid),p=new Date().toISOString();for(let h of e){let g=h.hasCode?"code":"prose";this.#a.run(h.title,h.content,m,g,null,c,u,p),this.#c.run(h.title,h.content,m,g,null,c,u,p)}return m})();return r&&this.#W(r),this.#j++,this.#j%t.OPTIMIZE_EVERY===0&&this.#U(),{sourceId:d,label:n,totalChunks:e.length,codeChunks:a}}#z(e){return e.map(n=>({title:n.title,content:n.content,source:n.label,rank:n.rank,contentType:n.content_type,highlighted:n.highlighted,timestamp:n.timestamp??void 0,sessionId:n.session_id??""}))}#p(e,n){return n==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,n=3,r,o="AND",s,i="like"){let a=Tj(e,o),c,u;return r&&s?(c=i==="exact"?this.#E:this.#v,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#y:this.#g,u=[a,this.#p(r,i),n]):s?(c=this.#b,u=[a,s,n]):(c=this.#h,u=[a,n]),Yr(()=>this.#z(c.all(...u)))}searchTrigram(e,n=3,r,o="AND",s,i="like"){let a=Pj(e,o);if(!a)return[];let c,u;return r&&s?(c=i==="exact"?this.#P:this.#T,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#x:this.#S,u=[a,this.#p(r,i),n]):s?(c=this.#w,u=[a,s,n]):(c=this.#_,u=[a,n]),Yr(()=>this.#z(c.all(...u)))}fuzzyCorrect(e){let n=e.toLowerCase().trim();if(n.length<3)return null;if(this.#r.has(n)){let u=this.#r.get(n)??null;return this.#r.delete(n),this.#r.set(n,u),u}let r=Cj(n.length),o=this.#k.all(n.length-r,n.length+r),s=null,i=r+1,a=!1;for(let{word:u}of o){if(u===n){a=!0;break}let l=Rj(n,u);l<i&&(i=l,s=u)}let c=a?null:i<=r?s:null;if(this.#r.size>=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(n,c),c}#L(e,n,r,o,s="like"){let a=Math.max(n*2,10),c=this.search(e,a,r,"OR",o,s),u=this.searchTrigram(e,a,r,"OR",o,s),l=new Map,d=f=>`${f.source}::${f.title}`;for(let[f,m]of c.entries()){let p=d(m),h=l.get(p);h?h.score+=1/(60+f+1):l.set(p,{result:m,score:1/(60+f+1)})}for(let[f,m]of u.entries()){let p=d(m),h=l.get(p);h?h.score+=1/(60+f+1):l.set(p,{result:m,score:1/(60+f+1)})}return Array.from(l.values()).sort((f,m)=>m.score-f.score).slice(0,n).map(({result:f,score:m})=>({...f,rank:-m}))}#H(e,n){let r=n.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=r.filter(i=>!ts.has(i)),s=o.length>0?o:r;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(m=>a.includes(m)).length,u=i.contentType==="code"?.6:.3,l=c>0?u*(c/s.length):0,d=0,f=0;if(s.length>=2){let m=i.content.toLowerCase(),p=s.map(h=>Nj(m,h));if(!p.some(h=>h.length===0)){d=1/(1+Mj(p)/Math.max(m.length,1));let g=Dj(p,s);f=.5*Math.min(1,g/4)}}return{result:i,boost:l+d+f}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,n=3,r,o,s="like",i){this.#V();let a=i?Math.max(n*8,40):n,c=this.#q(i),u=this.#L(e,a,r,o,s),l=c?u.filter(c):u;if(l.length>0)return this.#H(l.slice(0,n),e).map(g=>({...g,matchLayer:"rrf"}));let d=e.toLowerCase().trim().split(/\s+/).filter(h=>h.length>=3&&!ts.has(h)),f=d.join(" "),p=d.map(h=>this.fuzzyCorrect(h)??h).join(" ");if(p!==f){let h=this.#L(p,a,r,o,s),g=c?h.filter(c):h;if(g.length>0)return this.#H(g.slice(0,n),p).map(_=>({..._,matchLayer:"rrf-fuzzy"}))}return[]}#q(e){return e?n=>{let r=n.sessionId??"";return r===""||e.has(r)}:null}lastRefreshCount=0;#V(){this.lastRefreshCount=0;let e=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let n of e)try{if(!Um(n.file_path)||this.#n&&this.#n(n.file_path))continue;let r=Gc(n.file_path).mtime,o=new Date(n.indexed_at+"Z");if(r<=o)continue;let s=Qb(n.file_path,"r"),i;try{if(!ev(s).isFile())continue;i=Yb(s,"utf-8")}finally{tv(s)}if(nv("sha256").update(i).digest("hex")===n.content_hash)continue;this.index({content:i,path:n.file_path,source:n.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let n=this.#A.get(e);return n?{label:n.label,chunkCount:n.chunk_count,codeChunkCount:n.code_chunk_count,indexedAt:n.indexed_at,filePath:n.file_path??null,contentHash:n.content_hash??null}:null}listSources(){return this.#R.all()}getIndexState(){let e=this.#e.prepare("SELECT COALESCE(SUM(chunk_count), 0) AS total_chunks, COUNT(*) AS total_sources, MAX(indexed_at) AS last_indexed_at FROM sources").get();return{totalChunks:e.total_chunks??0,totalSources:e.total_sources??0,lastIndexedAt:e.last_indexed_at??void 0}}getChunksBySource(e){return this.#C.all(e).map(r=>({title:r.title,content:r.content,source:r.label,rank:0,contentType:r.content_type}))}getDistinctiveTerms(e,n=40){let r=this.#$.get(e);if(!r||r.chunk_count<3)return[];let o=r.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#O.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(f=>f.length>=3&&!ts.has(f)));for(let f of d)a.set(f,(a.get(f)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let f=Math.log(o/d),m=Math.min(l.length/20,.5),p=/[_]/.test(l),h=l.length>=12,g=p?1.5:h?.8:0;return{word:l,score:f+m+g}}).sort((l,d)=>d.score-l.score).slice(0,n).map(l=>l.word)}getStats(){let e=this.#I.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#N.run(o),this.#D.run(o),this.#M.run(o)))(e).changes}getDBSizeBytes(){try{return Gc(this.#t).size}catch{return 0}}#U(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#U(),Ai(this.#e)}#W(e){let n=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!ts.has(s)),r=[...new Set(n)],o=0;this.#e.transaction(()=>{for(let s of r){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#K(e,n=Kc){let r=[],o=e.split(`
|
|
548
556
|
`),s=[],i=[],a="",c=()=>{let l=i.join(`
|
|
549
|
-
`).trim();if(l.length===0)return;let d=this.#
|
|
557
|
+
`).trim();if(l.length===0)return;let d=this.#ee(s,a),f=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(l)<=n){r.push({title:d,content:l,hasCode:f}),i=[];return}let m=l.split(/\n\n+/),p=[],h=1,g=()=>{if(p.length===0)return;let y=p.join(`
|
|
550
558
|
|
|
551
|
-
`).trim();if(y.length===0)return;let _=
|
|
559
|
+
`).trim();if(y.length===0)return;let _=m.length>1?`${d} (${h})`:d;h++,r.push({title:_,content:y,hasCode:y.includes("```")}),p=[]};for(let y of m){p.push(y);let _=p.join(`
|
|
552
560
|
|
|
553
|
-
`);Buffer.byteLength(_)>
|
|
554
|
-
`)
|
|
555
|
-
`)
|
|
556
|
-
`)
|
|
561
|
+
`);Buffer.byteLength(_)>n&&p.length>1&&(p.pop(),g(),p=[y])}g(),i=[]},u=0;for(;u<o.length;){let l=o[u];if(/^[-_*]{3,}\s*$/.test(l)){c(),u++;continue}let d=l.match(/^(#{1,4})\s+(.+)$/);if(d){c();let m=d[1].length,p=d[2].trim();for(;s.length>0&&s[s.length-1].level>=m;)s.pop();s.push({level:m,text:p}),a=p,i.push(l),u++;continue}let f=l.match(/^(`{3,})(.*)?$/);if(f){let m=f[1],p=[l];for(u++;u<o.length;){if(p.push(o[u]),o[u].startsWith(m)&&o[u].trim()===m){u++;break}u++}i.push(...p);continue}i.push(l),u++}return c(),r}#G(e,n){if(Buffer.byteLength(e)<=n)return e;let r="",o=0;for(let s of e){let i=Buffer.byteLength(s);if(o+i>n)break;r+=s,o+=i}return r.length===0?[...e][0]??"":r}#f(e,n,r){let o=[],s=[],i=1,a=()=>{if(s.length===0)return;let c=s.join(`
|
|
562
|
+
`),u=i===1?n:`${n} (${i})`;o.push({title:u,content:c}),i++,s=[]};for(let c of e){if(Buffer.byteLength(c)>r){a();let l=c,d=1;for(;l.length>0;){let f=this.#G(l,r);if(f.length<l.length){let p=f.lastIndexOf(" "),h=f.lastIndexOf(`
|
|
563
|
+
`),g=Math.max(p,h);g>f.length*Aj&&(f=f.slice(0,g))}let m=i===1&&d===1?n:`${n} (${i}.${d})`;o.push({title:m,content:f}),l=l.slice(f.length),d++,i++}continue}let u=s.length>0?s.join(`
|
|
564
|
+
`)+`
|
|
565
|
+
`+c:c;Buffer.byteLength(u)>r&&s.length>0&&a(),s.push(c)}return a(),o}#J(e,n,r=Kc){let o=e.split(/\n\s*\n/);if(o.length>=$j&&o.length<=Oj&&o.every(u=>Buffer.byteLength(u)<Ij))return o.flatMap((u,l)=>{let d=u.trim();if(d.length===0)return[];let f=d.split(`
|
|
566
|
+
`)[0].slice(0,rv)||`Section ${l+1}`;return Buffer.byteLength(d)<=r?[{title:f,content:d}]:this.#f(d.split(`
|
|
567
|
+
`),f,r)});let s=e.split(`
|
|
568
|
+
`);if(s.length<=n)return Buffer.byteLength(e)<=r?[{title:"Output",content:e}]:this.#f(s,"Output",r);let i=[],c=Math.max(n-2,1);for(let u=0;u<s.length;u+=c){let l=s.slice(u,u+n);if(l.length===0)break;let d=u+1,f=Math.min(u+l.length,s.length),m=l[0]?.trim().slice(0,rv),p=l.join(`
|
|
569
|
+
`);if(Buffer.byteLength(p)<=r)i.push({title:m||`Lines ${d}-${f}`,content:p});else{let h=this.#f(l,m||`Lines ${d}-${f}`,r);i.push(...h)}}return i}#F(e,n,r,o){let s=n.length>0?n.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){r.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#F(u,[...n,c],r,o);return}r.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#Q(e,n,r,o);return}r.push({title:s,content:i,hasCode:!1})}#X(e){if(e.length===0)return null;let n=e[0];if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=["id","name","title","path","slug","key","label"],o=n;for(let s of r)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#Y(e,n,r,o,s){let i=e?`${e} > `:"";if(!s)return n===r?`${i}[${n}]`:`${i}[${n}-${r}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#Q(e,n,r,o){let s=n.length>0?n.join(" > "):"(root)",i=this.#X(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#Y(s,c,l,a,i);r.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;l<e.length;l++){a.push(e[l]);let d=JSON.stringify(a,null,2);Buffer.byteLength(d)>o&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#ee(e,n){return e.length===0?n||"Untitled":e.map(r=>r.text).join(" > ")}};function Vm(t,e){return t===void 0?e:`${t}::${e}`}to();import{readFileSync as bw,realpathSync as i1}from"node:fs";import{resolve as Ki}from"node:path";function vw(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function a1(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function c1(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function kw(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function u1(t,e=!1){let n,r=t.indexOf(":");if(r!==-1){let o=t.slice(0,r),s=t.slice(r+1),i=c1(o),a=kw(s);n=`^${i}(\\s${a})?$`}else n=`^${kw(t)}$`;return new RegExp(n,e?"i":"")}function l1(t,e=!1){let n="",r=0;for(;r<t.length;)t[r]==="*"&&t[r+1]==="*"?r+2<t.length&&t[r+2]==="/"?(n+="(.*/)?",r+=3):(n+=".*",r+=2):t[r]==="*"?(n+="[^/]*",r++):t[r]==="?"?(n+="[^/]",r++):(n+=t[r].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),r++);return new RegExp(`^${n}$`,e?"i":"")}function d1(t,e,n=!1){for(let r of e){let o=vw(r);if(o&&u1(o,n).test(t))return r}return null}function Ew(t,e){let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;return n%2===1}function p1(t){let e=[],n="",r=!1,o=!1,s=!1,i=0;for(let a=0;a<t.length;a++){let c=t[a],u=Ew(t,a);c==="'"&&!o&&!s&&!u?(r=!r,n+=c):c==='"'&&!r&&!s&&!u?(o=!o,n+=c):c==="`"&&!r&&!o&&!u?(s=!s,n+=c):!r&&!o&&!s?c==="$"&&t[a+1]==="("&&!u?(i++,n+=c+t[a+1],a++):i>0&&c==="("&&!u?(i++,n+=c):c===")"&&i>0&&!u?(i--,n+=c):i===0&&(c===";"||c===`
|
|
570
|
+
`||c==="\r")&&!u?(e.push(n.trim()),n=""):i===0&&c==="|"&&t[a+1]==="|"||i===0&&c==="&"&&t[a+1]==="&"?(e.push(n.trim()),n="",a++):i===0&&c==="&"&&!u||i===0&&c==="|"?(e.push(n.trim()),n=""):n+=c:n+=c}return n.trim()&&e.push(n.trim()),e.filter(a=>a.length>0)}function ww(t){let e=[],n=!1,r=!1,o=-1,s=[],i=[],a=0;for(let c=0;c<t.length;c++){let u=t[c],l=Ew(t,c);if(u==="'"&&!r&&o===-1&&!l)n=!n;else if(u==='"'&&!n&&o===-1&&!l)r=!r;else if(u==="`"&&!n&&!r&&!l)if(o===-1)o=c+1;else{let d=t.slice(o,c);e.push(d),e.push(...ww(d)),o=-1}else if(!n&&o===-1){if(u==="$"&&t[c+1]==="("&&!l)t[c+2]==="("?(a+=2,c+=2):(s.push(c+2),i.push(a),a++,c++);else if(u==="("&&!l)a++;else if(u===")"&&!l&&(a>0&&a--,i.length>0&&a===i[i.length-1])){i.pop();let d=s.pop(),f=t.slice(d,c);e.push(f)}}}return e}function Tw(t){let e=[],n=p1(t);for(let r of n){e.push(r);for(let o of ww(r))e.push(...Tw(o))}return e}function ig(t){let e;try{e=bw(t,"utf-8")}catch{return null}let n;try{n=JSON.parse(e)}catch{return null}let r=n?.permissions;if(!r||typeof r!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&vw(i)!==null):[];return{allow:o(r.allow),deny:o(r.deny),ask:o(r.ask)}}function ag(t,e){let n=[];if(t){let o=Ki(t,".claude","settings.local.json"),s=ig(o);s&&n.push(s);let i=Ki(t,".claude","settings.json"),a=ig(i);a&&n.push(a)}let r=e!==void 0?[e]:sg();for(let o of r){let s=ig(o);s&&n.push(s)}return n}function bu(t,e,n){let r=[],o=i=>{let a;try{a=bw(i,"utf-8")}catch{return null}let c;try{c=JSON.parse(a)}catch{return null}let u=c?.permissions?.deny;if(!Array.isArray(u))return[];let l=[];for(let d of u){if(typeof d!="string")continue;let f=a1(d);f&&f.tool===t&&l.push(f.glob)}return l};if(e){let i=o(Ki(e,".claude","settings.local.json"));i!==null&&r.push(i);let a=o(Ki(e,".claude","settings.json"));a!==null&&r.push(a)}let s=n!==void 0?[n]:sg();for(let i of s){let a=o(i);a!==null&&r.push(a)}return r}function cg(t,e,n=process.platform==="win32"||process.platform==="darwin"){let r=Tw(t);for(let o of r)for(let s of e){let i=d1(o,s.deny,n);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function vu(t,e,n=process.platform==="win32"||process.platform==="darwin",r){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),r){let i=Ki(r,t);s.add(o(i));try{s.add(o(i1(i)))}catch{}}for(let i of e)for(let a of i){let c=l1(o(a),n);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}var f1={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 m1(t){let e=[],n=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,r;for(;(r=n.exec(t))!==null;){let s=[...r[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function Pw(t,e){let n=f1[e];if(!n&&e!=="python")return[];let r=[];if(n)for(let o of n){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&r.push(i)}}return e==="python"&&r.push(...m1(t)),r}Zc();function ug(t){let{language:e,exitCode:n,stdout:r,stderr:o}=t,s=e==="shell"&&n===1&&r.trim().length>0;return{isError:!s,output:s?r:`Exit code: ${n}
|
|
557
571
|
|
|
558
572
|
stdout:
|
|
559
|
-
${
|
|
573
|
+
${r}
|
|
560
574
|
|
|
561
575
|
stderr:
|
|
562
|
-
${o}`}}import{execFileSync as
|
|
563
|
-
`)}for(let
|
|
564
|
-
|
|
565
|
-
`,
|
|
566
|
-
|
|
567
|
-
`,
|
|
568
|
-
`)}}return s.slice(0,e)}function
|
|
569
|
-
`)}try{let
|
|
570
|
-
`)}if(o==="timeline"){try{if(a){let
|
|
571
|
-
`)}try{let
|
|
572
|
-
`)}}for(let
|
|
573
|
-
`).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{
|
|
574
|
-
`).slice(0,10))if(h.trim())try{let p=JSON.parse(h),m=p?.meta?.cwd??(p?.type==="session_meta"?p?.payload?.cwd:void 0);if(typeof m!="string"||m.length===0)continue;return fu(m)?null:m}catch{return null}}finally{Le.closeSync(u)}}catch{return null}return null}function XE(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...Ih(a),...pL]:fL;for(let l of u){let d=e[l];if(d&&!fu(d))return d}if(o){let l=mL({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!fu(l))return l}if(a==="codex"){let l=hL({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return n&&!fu(n)?n:r}Yo();Yo();Sr();Yn();import{execFileSync as gL}from"node:child_process";import{existsSync as Hr,readdirSync as fs,statSync as yL}from"node:fs";import{homedir as _u}from"node:os";import{join as Tt,sep as _L}from"node:path";function sw(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}var hu={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session intent",goal:"Session goal",role:"Behavior rules",constraint:"Constraints you set",mcp:"MCP tools called",skill:"Skills used",subagent:"Delegated work",decision:"Your decisions","agent-finding":"Agent insights kept","rejected-approach":"Approaches you rejected","external-ref":"External docs indexed",data:"Data references",git:"Git operations",env:"Environment setup",task:"Tasks in progress",error:"Errors caught",compact:"Compactions weathered",resume:"Sessions resumed cleanly",snapshot:"Snapshots restored",cache:"Cache hits saved",latency:"Slow tools recorded","user-prompt":"Your messages remembered",plan:"Plans drafted","blocked-on":"Blockers logged"},xL={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"},ms=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,r){let n=e-r,o=e>0?Math.round(n/e*1e3)/10:0;return{rawBytes:e,contextBytes:r,savedBytes:n,savedPercent:o}}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 o of e){let s;try{s=JSON.parse(o.data)}catch{continue}let i=typeof s.tool_name=="string"?s.tool_name:null;if(!i)continue;let a=r.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,s.truncated!==!0&&s.params&&typeof s.params=="object"){let c=s.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}r.set(i,a)}let n=[];for(let[o,s]of r){let i=null,a=null;if(s.concurrencies.length>0){s.concurrencies.sort((l,d)=>l-d);let c=s.concurrencies,u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}n.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return n.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.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??"",o=Object.values(e.bytesReturned).reduce((E,H)=>E+H,0),s=Object.values(e.calls).reduce((E,H)=>E+H,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+o,c=a/Math.max(o,1),u=a>0?Math.round((1-o/a)*100):0,l=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),d=Array.from(l).sort().map(E=>({tool:E,calls:e.calls[E]||0,context_kb:Math.round((e.bytesReturned[E]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[E]||0)/4)})),h=((Date.now()-e.sessionStart)/6e4).toFixed(1),p,m=e.cacheMisses??0;if(e.cacheHits>0||e.cacheBytesSaved>0||m>0){let E=a+e.cacheBytesSaved,H=E/Math.max(o,1),pe=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),dt=e.cacheHits+m,gn=dt>0?e.cacheHits/dt:0;p={hits:e.cacheHits,misses:m,hit_rate:gn,bytes_saved:e.cacheBytesSaved,ttl_hours_left:pe,total_with_cache:E,total_savings_ratio:H}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(n).cnt,y=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,S=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),k=S?!S.consumed:!1,R=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),$=new Map;for(let E of R){$.has(E.category)||$.set(E.category,new Set);let H=$.get(E.category);if(H.size<5){let pe=E.data;E.category==="file"?pe=E.data.split("/").pop()||E.data:(E.category==="prompt"||E.category==="user-prompt")&&(pe=pe.length>50?pe.slice(0,47)+"...":pe),pe.length>40&&(pe=pe.slice(0,37)+"..."),H.add(pe)}}let C=y.map(E=>({category:E.category,count:E.cnt,label:hu[E.category]||E.category,preview:$.get(E.category)?Array.from($.get(E.category)).join(", "):"",why:xL[E.category]||"Survives context resets"})),A=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),T=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(E=>E.cnt>0).map(E=>({category:E.category,count:E.cnt,label:hu[E.category]||E.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(o/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:d,total_calls:s,total_bytes_returned:o,kept_out:i,total_processed:a},cache:p,session:{id:n,uptime_min:h},continuity:{total_events:g,by_category:C,compact_count:x,resume_ready:k},projectMemory:{total_events:A.cnt,session_count:A.sessions,by_category:T}}}};function SL(t){let e=t?.home??_u();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,o])=>{let s=Tt(e,...o,"context-mode");return{name:n,sessionsDir:Tt(s,"sessions"),contentDir:Tt(s,"content")}})}function vL(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function qi(t){let e=wt(),r=t?.sessionsDir??Tt(e,"context-mode","sessions"),n=t?.memoryRoot??Tt(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(Hr(r)){let h=[];try{h=fs(r).filter(p=>p.endsWith(".db"))}catch{}if(h.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():Ye()}catch{}if(p)for(let m of h){let g=Tt(r,m);try{let y=new p(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),x=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=_?.cnt??0,s+=x?.cnt??0;try{let S=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let k of S)k.category&&(u[k.category]=(u[k.category]??0)+(k.cnt??0))}catch{}try{let S=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();S?.bytes&&(i+=S.bytes)}catch{}try{let S=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(S?.t){let k=S.t.endsWith("Z")?S.t:S.t+"Z",R=Date.parse(k);Number.isFinite(R)&&R<a&&(a=R)}}catch{}try{let S=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let k of S)k.p&&c.add(k.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,f={};if(Hr(n)){let h=[];try{h=fs(n).filter(p=>{try{return yL(Tt(n,p)).isDirectory()}catch{return!1}})}catch{}for(let p of h){let m=Tt(n,p,"memory");if(!Hr(m))continue;let g=[];try{g=fs(m).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=vL(y);f[_]=(f[_]??0)+1}}}}return{totalEvents:o,totalSessions:s,autoMemoryCount:l,autoMemoryProjects:d,autoMemoryByPrefix:f,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function iw(t){let e=t.sessionsDir??Tt(_u(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!Hr(e))return n;let o=[];try{o=fs(e).filter(x=>!(!x.endsWith(".db")||t.worktreeHash&&!x.startsWith(t.worktreeHash)))}catch{return n}if(o.length===0)return n;let s=null;try{s=t.loadDatabase?t.loadDatabase():Ye()}catch{return n}if(!s)return n;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,f=0,h=0,p=new Map,m=x=>Math.floor(x/864e5)*864e5;for(let x of o){let S=Tt(e,x),k=!1;try{let R=new s(S,{readonly:!0});try{let $=R.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let A of $)A.category&&(i[A.category]=(i[A.category]??0)+(A.cnt??0),a+=A.cnt??0,k=!0);let C=R.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(C?.mn){let A=Date.parse(C.mn+(C.mn.endsWith("Z")?"":"Z"));Number.isFinite(A)&&A<d&&(d=A)}if(C?.mx){let A=Date.parse(C.mx+(C.mx.endsWith("Z")?"":"Z"));Number.isFinite(A)&&A>f&&(f=A)}try{let A=R.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 W of A){if(!W.sec)continue;let T=parseInt(W.sec,10)*1e3;if(!Number.isFinite(T))continue;let E=m(T),H=p.get(E)??{count:0,rescueBytes:0};H.count+=W.cnt??0,p.set(E,H)}}catch{}try{let A=R.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(A?.bytes&&(u+=A.bytes),A?.n&&(l+=A.n),A?.lastSec){let W=parseInt(A.lastSec,10)*1e3;if(Number.isFinite(W)&&W>h&&(h=W),Number.isFinite(W)&&(A?.bytes??0)>0){let T=m(W),E=p.get(T)??{count:0,rescueBytes:0};E.rescueBytes=Math.max(E.rescueBytes,A.bytes),p.set(T,E)}}}catch{}}finally{R.close()}}catch{}k&&c++}let g=d<f?(f-d)/864e5:0,y=Object.entries(i).filter(([,x])=>x>0).map(([x,S])=>({category:x,count:S,label:hu[x]||x})).sort((x,S)=>S.count-x.count),_=[...p.entries()].sort((x,S)=>x[0]-S[0]).map(([x,S])=>({ms:x,count:S.count,...S.rescueBytes>0?{rescueBytes:S.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:f>0?f:0,lastRescueMs:h>0?h:void 0,byDay:_}}function bL(t,e,r){if(!t||!e||!Hr(e))return 0;let n=null;try{n=r?.loadDatabase?r.loadDatabase():Ye()}catch{return 0}if(!n)return 0;try{let o=new n(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
575
|
-
FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function
|
|
576
|
-
FROM chunks`).get();return Number(o?.bytes??0)}finally{
|
|
576
|
+
${o}`}}import{execFileSync as h1}from"node:child_process";function g1(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=h1("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),n=parseInt(e,10);return Number.isFinite(n)?n:NaN}catch{return NaN}}function y1(t={}){let e=t.getPpid??(()=>process.ppid),n=t.readGrandparentPpid??g1,r=e(),o=n();return()=>{let s=e();return!(s!==r||s===0||s===1||!Number.isNaN(o)&&o>1&&n()===1)}}var _1=y1();function S1(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<=0?3e4:1e3}function Rw(t){let e=t.checkIntervalMs??S1(),n=t.isParentAlive??_1,r=!1,o=()=>{r||(r=!0,t.onShutdown())},s=setInterval(()=>{n()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,o);let a=()=>{n()||o()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{r=!0,clearInterval(s);for(let c of i)process.removeListener(c,o);process.stdin.removeListener("end",a)}}function Cw(t,e){if(e<=0)return"";if(t.length<=e)return t;let n=e,r=t.charCodeAt(n-1);return r>=55296&&r<=56319&&(n-=1),t.slice(0,n)}kn();es();kn();import{existsSync as lg,unlinkSync as x1}from"node:fs";import{join as Gi}from"node:path";var k1=["","-wal","-shm"];function dg(t,e){try{return x1(t),e.push(t),!0}catch{return!1}}function Eu(t,e){let n=!1;for(let r of k1)dg(`${t}${r}`,e)&&r===""&&(n=!0);return n}function $w(t){let{projectDir:e,sessionsDir:n,storePath:r,contentDir:o,legacyContentDir:s,contentHash:i,sessionId:a,scope:c}=t,u=[],l=[],d=c??(a?"session":"project");if(d==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(d==="session"&&a){let S=tu(e),k=Qe(e),v=jn(e),O=k===v?[k]:[k,v],R=!1;for(let V of O){let P=Gi(n,`${V}${S}.db`);if(!lg(P))continue;let T=null;try{T=new on({dbPath:P});let H=T.getEvents(a).length;T.deleteSession(a),H>0&&(R=!0)}catch{}finally{try{T?.close()}catch{}}}R&&u.push(`session rows for ${a}`);let M=[];if(r&&lg(r)&&M.push(r),o){let V=Qe(e),P=jn(e),T=V===P?[V]:[V,P];for(let H of T){let pe=Gi(o,`${H}.db`);lg(pe)&&!M.includes(pe)&&M.push(pe)}}let D=!1;for(let V of M)try{let P=Ye(),T=new P(V,{timeout:3e4});try{let H=T.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;T.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),T.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),H>0&&(D=!0)}finally{try{T.close()}catch{}}}catch{}return D&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let f=!1;if(r&&Eu(r,l)&&(f=!0),o){let S=Qe(e),k=jn(e),v=S===k?[S]:[S,k];for(let O of v){let R=Gi(o,`${O}.db`);Eu(R,l)&&(f=!0)}}if(f&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let S=Gi(s,`${i}.db`);Eu(S,l)}let m=tu(e),p=Qe(e),h=jn(e),g=p===h?[p]:[p,h],y=!1,_=!1;for(let S of g){let k=Gi(n,`${S}${m}`);Eu(`${k}.db`,l)&&(y=!0),dg(`${k}-events.md`,l)&&(_=!0),dg(`${k}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}kn();import{existsSync as b1}from"node:fs";function pg(t,e){try{if(!b1(t))return;let n=new on({dbPath:t});try{let r=n.getLatestSessionId();if(!r)return;e(n,r)}finally{try{n.close()}catch{}}}catch{}}function Ow(t){pg(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function Iw(t){pg(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function Aw(t){pg(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}kn();import{existsSync as Nw}from"node:fs";function Dw(t,e,n){try{if(!Nw(t))return;let r=new on({dbPath:t});try{let o=r.getLatestSessionId();if(!o)return;r.incrementToolCall(o,e,n)}finally{r.close()}}catch{}}function Mw(t){try{if(!Nw(t))return null;let e=new on({dbPath:t});try{let n=e.getLatestSessionId();if(!n)return null;let r=e.getToolCallStats(n),o={},s={};for(let[a,c]of Object.entries(r.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(n);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(o).length===0&&Object.keys(s).length===0?{calls:o,bytesReturned:s,sessionStart:i}:{calls:o,bytesReturned:s,sessionStart:i}}finally{e.close()}}catch{return null}}to();kn();import{existsSync as fg,readFileSync as v1,readdirSync as E1,statSync as w1}from"node:fs";import{join as ms,isAbsolute as T1}from"node:path";var jw=process.env.DEBUG?.includes("context-mode");function Lw(t,e=5,n,r,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?zw(n,a):null)??r??Rt(),l=o?.getMemoryDir(n),d=ms(u,"memory"),f=n?ms(d,Qe(n)):d,m=l?zw(n,l):f,p=[];if(n)for(let h of i){let g=ms(n,h);fg(g)&&p.push({path:g,label:`project/${h}`})}if(u&&u!==n)for(let h of i){let g=ms(u,h);fg(g)&&p.push({path:g,label:`user/${h}`})}if(m&&fg(m))try{let h=E1(m).filter(g=>g.endsWith(".md"));for(let g of h)p.push({path:ms(m,g),label:`memory/${g}`})}catch(h){jw&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
|
|
577
|
+
`)}for(let h of p){if(s.length>=e)break;try{let g;try{if(g=w1(h.path),g.size>1e6)continue}catch{continue}let y=v1(h.path,"utf-8"),_=y.toLowerCase();for(let S of t){if(s.length>=e)break;let v=S.toLowerCase().split(/\s+/).filter(R=>R.length>=3);if(v.some(R=>{try{return new RegExp(`\\b${R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return _.includes(R)}})){let R=v.reduce((H,pe)=>{let ft=_.indexOf(pe);return ft>=0&&(H<0||ft<H)?ft:H},-1),M=Math.max(0,R-200),D=Math.min(y.length,R+500),V=y.lastIndexOf(`
|
|
578
|
+
|
|
579
|
+
`,M),P=y.indexOf(`
|
|
580
|
+
|
|
581
|
+
`,D);V>=0&&(M=V+2),P>=0&&(D=P);let T=y.slice(M,D).trim();s.push({title:`[auto-memory] ${h.label}`,content:T,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){jw&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
|
|
582
|
+
`)}}return s.slice(0,e)}function zw(t,e){return e?T1(e)||!t?e:ms(t,e):t??""}var wu=process.env.DEBUG?.includes("context-mode");function Hw(t){let{query:e,limit:n,store:r,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l,projectScope:d}=t,f=[],m=new Date().toISOString(),p;if(typeof d=="string"&&a)try{p=new Set(a.getSessionIdsForProject(d))}catch(h){wu&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${h}
|
|
583
|
+
`)}try{let h=r.searchWithFallback(e,n,s,i,"like",p);f.push(...h.map(g=>({title:g.title,content:g.content,source:g.source,origin:"current-session",timestamp:g.timestamp||m,rank:g.rank,matchLayer:g.matchLayer,highlighted:g.highlighted,contentType:g.contentType})))}catch(h){wu&&process.stderr.write(`[ctx] ContentStore search failed: ${h}
|
|
584
|
+
`)}if(o==="timeline"){try{if(a){let h=a.searchEvents(e,n,c||"",s);f.push(...h.map(g=>({title:`[${g.category}] ${g.type}`,content:g.data,source:"prior-session",origin:"prior-session",timestamp:g.created_at})))}}catch(h){wu&&process.stderr.write(`[ctx] SessionDB search failed: ${h}
|
|
585
|
+
`)}try{let h=Lw([e],n,c,u,l);f.push(...h)}catch(h){wu&&process.stderr.write(`[ctx] auto-memory search failed: ${h}
|
|
586
|
+
`)}}for(let h of f)h.timestamp&&!h.timestamp.includes("T")&&(h.timestamp=h.timestamp.replace(" ","T")+"Z");return o==="timeline"&&f.sort((h,g)=>(h.timestamp||"").localeCompare(g.timestamp||"")),f.slice(0,n)}function P1(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function Uw(t){let e=t?{project:$.string().optional().describe("Project scope. Default (omit): this session's project \u2014 auto-resolved from the host adapter. 'global': span every project in the shared store (cross-project recall). <absolute-path>: scope to that specific project directory.")}:{};return $.object({queries:$.preprocess(P1,$.array($.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:$.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:$.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:$.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:$.enum(["relevance","timeline"]).optional().default("relevance").describe("Sort mode. 'relevance' (default): BM25 ranked, current session only. 'timeline': chronological across current session, prior sessions, and auto-memory."),...e})}function Fw(t,e,n){if(e)return t===void 0?n():t==="global"?null:t}var mg=!!process.env.CONTEXT_MODE_PROJECT_DIR;var Tu=class{#e;#t=new Map;#n;constructor(e,n=4096){this.#e=e,this.#n=Math.max(1,n)}record(e,n=Date.now()){let r=this.#t.get(e);return(!r||n-r.windowStart>this.#e.windowMs)&&(r={count:0,windowStart:n},this.#t.set(e,r),this.#o()),r.count++,{count:r.count,windowStart:r.windowStart,blocked:r.count>this.#e.blockAfter,softCapped:r.count>this.#e.softCapAfter}}size(){return this.#t.size}#o(){if(this.#t.size<=this.#n)return;let e,n=1/0;for(let[r,o]of this.#t)o.windowStart<n&&(n=o.windowStart,e=r);e!==void 0&&this.#t.delete(e)}};Mn();fs();Sh();Mn();function R1(t){let e=[];if(t&&typeof t=="object"){let n=t.command;typeof n=="string"&&e.push(n);let r=t.hooks;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function C1(t){let e=Uc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function Zw(t,e){let n=new Set,r=t.generateHookConfig(e);for(let o of Object.values(r))if(Array.isArray(o))for(let s of o)for(let i of R1(s)){let a=C1(i);a&&n.add(a)}return[...n]}Ui();to();fs();import*as Ue from"node:fs";import*as Bw from"node:os";import*as hs from"node:path";var $1=["CONTEXT_MODE_PROJECT_DIR"],O1=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"];function Pu(t){return t?/[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function I1(t){if(!Ue.existsSync(t.projectsRoot))return;let e,n=0;try{for(let r of Ue.readdirSync(t.projectsRoot)){let o=hs.join(t.projectsRoot,r),s;try{s=Ue.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=Ue.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=hs.join(o,a);try{let u=Ue.statSync(c).mtimeMs;u>n&&(n=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-n>t.maxAgeMs))try{let r=Ue.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Ue.readSync(r,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
|
|
587
|
+
`).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{Ue.closeSync(r)}}catch{}}function A1(t){let e=t?.codexHome??process.env.CODEX_HOME??hs.join(Bw.homedir(),".codex"),n=hs.join(e,"sessions");if(!Ue.existsSync(n))return null;let r=4,o=1e4,s=0,i,a=0,c=(u,l)=>{if(s>=o)return;let d;try{d=Ue.readdirSync(u)}catch{return}d.sort().reverse();for(let f of d){if(s>=o)return;s++;let m=hs.join(u,f),p;try{p=Ue.statSync(m)}catch{continue}if(p.isDirectory()){l<r&&c(m,l+1);continue}if(!p.isFile()||!f.endsWith(".jsonl"))continue;let h=p.mtimeMs;h>a&&(a=h,i=m)}};try{c(n,0)}catch{return null}if(!i||typeof t?.transcriptMaxAgeMs=="number"&&(t.now??Date.now())-a>t.transcriptMaxAgeMs)return null;try{let u=Ue.openSync(i,"r");try{let l=Buffer.alloc(1048576),d=Ue.readSync(u,l,0,l.length,0),f=l.subarray(0,d).toString("utf-8");for(let m of f.split(`
|
|
588
|
+
`).slice(0,10))if(m.trim())try{let p=JSON.parse(m),h=p?.meta?.cwd??(p?.type==="session_meta"?p?.payload?.cwd:void 0);if(typeof h!="string"||h.length===0)continue;return Pu(h)?null:h}catch{return null}}finally{Ue.closeSync(u)}}catch{return null}return null}function qw(t){let{env:e,cwd:n,pwd:r,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...ng(a),...$1]:O1;for(let l of u){let d=e[l];if(d&&!Pu(d))return d}if(o){let l=I1({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!Pu(l))return l}if(a==="codex"){let l=A1({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return r&&!Pu(r)?r:n}es();es();kn();to();import{execFileSync as N1}from"node:child_process";import{existsSync as Fn,readdirSync as gs,statSync as D1}from"node:fs";import{homedir as Iu}from"node:os";import{join as $t,sep as M1}from"node:path";function Qw(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}var Cu={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session intent",goal:"Session goal",role:"Behavior rules",constraint:"Constraints you set",mcp:"MCP tools called",skill:"Skills used",subagent:"Delegated work",decision:"Your decisions","agent-finding":"Agent insights kept","rejected-approach":"Approaches you rejected","external-ref":"External docs indexed",data:"Data references",git:"Git operations",env:"Environment setup",task:"Tasks in progress",error:"Errors caught",compact:"Compactions weathered",resume:"Sessions resumed cleanly",snapshot:"Snapshots restored",cache:"Cache hits saved",latency:"Slow tools recorded","user-prompt":"Your messages remembered",plan:"Plans drafted","blocked-on":"Blockers logged"},j1={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"},ys=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,n){let r=e-n,o=e>0?Math.round(r/e*1e3)/10:0;return{rawBytes:e,contextBytes:n,savedBytes:r,savedPercent:o}}static thinkInCodeComparison(e,n){let r=n>0?Math.round(e/n*10)/10:0;return{fileBytes:e,outputBytes:n,ratio:r}}static toolSavings(e){return e.map(n=>({...n,savedBytes:n.rawBytes-n.contextBytes}))}static sandboxIO(e,n){return{inputBytes:e,outputBytes:n}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let n=new Map;for(let o of e){let s;try{s=JSON.parse(o.data)}catch{continue}let i=typeof s.tool_name=="string"?s.tool_name:null;if(!i)continue;let a=n.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,s.truncated!==!0&&s.params&&typeof s.params=="object"){let c=s.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}n.set(i,a)}let r=[];for(let[o,s]of n){let i=null,a=null;if(s.concurrencies.length>0){s.concurrencies.sort((l,d)=>l-d);let c=s.concurrencies,u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}r.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return r.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),r}queryAll(e){let r=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",o=Object.values(e.bytesReturned).reduce((T,H)=>T+H,0),s=Object.values(e.calls).reduce((T,H)=>T+H,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+o,c=a/Math.max(o,1),u=a>0?Math.round((1-o/a)*100):0,l=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),d=Array.from(l).sort().map(T=>({tool:T,calls:e.calls[T]||0,context_kb:Math.round((e.bytesReturned[T]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[T]||0)/4)})),m=((Date.now()-e.sessionStart)/6e4).toFixed(1),p,h=e.cacheMisses??0;if(e.cacheHits>0||e.cacheBytesSaved>0||h>0){let T=a+e.cacheBytesSaved,H=T/Math.max(o,1),pe=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),ft=e.cacheHits+h,En=ft>0?e.cacheHits/ft:0;p={hits:e.cacheHits,misses:h,hit_rate:En,bytes_saved:e.cacheBytesSaved,ttl_hours_left:pe,total_with_cache:T,total_savings_ratio:H}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(r).cnt,y=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(r),S=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(r)?.compact_count??0,k=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(r),v=k?!k.consumed:!1,O=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(r),R=new Map;for(let T of O){R.has(T.category)||R.set(T.category,new Set);let H=R.get(T.category);if(H.size<5){let pe=T.data;T.category==="file"?pe=T.data.split("/").pop()||T.data:(T.category==="prompt"||T.category==="user-prompt")&&(pe=pe.length>50?pe.slice(0,47)+"...":pe),pe.length>40&&(pe=pe.slice(0,37)+"..."),H.add(pe)}}let M=y.map(T=>({category:T.category,count:T.cnt,label:Cu[T.category]||T.category,preview:R.get(T.category)?Array.from(R.get(T.category)).join(", "):"",why:j1[T.category]||"Survives context resets"})),D=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(T=>T.cnt>0).map(T=>({category:T.category,count:T.cnt,label:Cu[T.category]||T.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(o/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:d,total_calls:s,total_bytes_returned:o,kept_out:i,total_processed:a},cache:p,session:{id:r,uptime_min:m},continuity:{total_events:g,by_category:M,compact_count:S,resume_ready:v},projectMemory:{total_events:D.cnt,session_count:D.sessions,by_category:P}}}};function z1(t){let e=t?.home??Iu();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["antigravity-cli",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["copilot-cli",[".copilot"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([r,o])=>{let s=$t(e,...o,"context-mode");return{name:r,sessionsDir:$t(s,"sessions"),contentDir:$t(s,"content")}})}function L1(t){let n=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return n?n[1].toLowerCase():"other"}function Ji(t){let e=Rt(),n=t?.sessionsDir??$t(e,"context-mode","sessions"),r=t?.memoryRoot??$t(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(Fn(n)){let m=[];try{m=gs(n).filter(p=>p.endsWith(".db"))}catch{}if(m.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():Ye()}catch{}if(p)for(let h of m){let g=$t(n,h);try{let y=new p(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),S=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=_?.cnt??0,s+=S?.cnt??0;try{let k=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let v of k)v.category&&(u[v.category]=(u[v.category]??0)+(v.cnt??0))}catch{}try{let k=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();k?.bytes&&(i+=k.bytes)}catch{}try{let k=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(k?.t){let v=k.t.endsWith("Z")?k.t:k.t+"Z",O=Date.parse(v);Number.isFinite(O)&&O<a&&(a=O)}}catch{}try{let k=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let v of k)v.p&&c.add(v.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,f={};if(Fn(r)){let m=[];try{m=gs(r).filter(p=>{try{return D1($t(r,p)).isDirectory()}catch{return!1}})}catch{}for(let p of m){let h=$t(r,p,"memory");if(!Fn(h))continue;let g=[];try{g=gs(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=L1(y);f[_]=(f[_]??0)+1}}}}return{totalEvents:o,totalSessions:s,autoMemoryCount:l,autoMemoryProjects:d,autoMemoryByPrefix:f,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function eT(t){let e=t.sessionsDir??$t(Iu(),".claude","context-mode","sessions"),n=t.sessionId,r={sessionId:n,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!n||!Fn(e))return r;let o=[];try{o=gs(e).filter(S=>!(!S.endsWith(".db")||t.worktreeHash&&!S.startsWith(t.worktreeHash)))}catch{return r}if(o.length===0)return r;let s=null;try{s=t.loadDatabase?t.loadDatabase():Ye()}catch{return r}if(!s)return r;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,f=0,m=0,p=new Map,h=S=>Math.floor(S/864e5)*864e5;for(let S of o){let k=$t(e,S),v=!1;try{let O=new s(k,{readonly:!0});try{let R=O.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(n);for(let D of R)D.category&&(i[D.category]=(i[D.category]??0)+(D.cnt??0),a+=D.cnt??0,v=!0);let M=O.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(n);if(M?.mn){let D=Date.parse(M.mn+(M.mn.endsWith("Z")?"":"Z"));Number.isFinite(D)&&D<d&&(d=D)}if(M?.mx){let D=Date.parse(M.mx+(M.mx.endsWith("Z")?"":"Z"));Number.isFinite(D)&&D>f&&(f=D)}try{let D=O.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(n);for(let V of D){if(!V.sec)continue;let P=parseInt(V.sec,10)*1e3;if(!Number.isFinite(P))continue;let T=h(P),H=p.get(T)??{count:0,rescueBytes:0};H.count+=V.cnt??0,p.set(T,H)}}catch{}try{let D=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(n);if(D?.bytes&&(u+=D.bytes),D?.n&&(l+=D.n),D?.lastSec){let V=parseInt(D.lastSec,10)*1e3;if(Number.isFinite(V)&&V>m&&(m=V),Number.isFinite(V)&&(D?.bytes??0)>0){let P=h(V),T=p.get(P)??{count:0,rescueBytes:0};T.rescueBytes=Math.max(T.rescueBytes,D.bytes),p.set(P,T)}}}catch{}}finally{O.close()}}catch{}v&&c++}let g=d<f?(f-d)/864e5:0,y=Object.entries(i).filter(([,S])=>S>0).map(([S,k])=>({category:S,count:k,label:Cu[S]||S})).sort((S,k)=>k.count-S.count),_=[...p.entries()].sort((S,k)=>S[0]-k[0]).map(([S,k])=>({ms:S,count:k.count,...k.rescueBytes>0?{rescueBytes:k.rescueBytes}:{}}));return{sessionId:n,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:f>0?f:0,lastRescueMs:m>0?m:void 0,byDay:_}}function H1(t,e,n){if(!t||!e||!Fn(e))return 0;let r=null;try{r=n?.loadDatabase?n.loadDatabase():Ye()}catch{return 0}if(!r)return 0;try{let o=new r(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
589
|
+
FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function tT(t,e){if(!t||!Fn(t))return 0;let n=null;try{n=e?.loadDatabase?e.loadDatabase():Ye()}catch{return 0}if(!n)return 0;try{let r=new n(t,{readonly:!0});try{let o=r.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
590
|
+
FROM chunks`).get();return Number(o?.bytes??0)}finally{r.close()}}catch{return 0}}function Xi(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},n=t.sessionsDir??$t(Iu(),".claude","context-mode","sessions");if(!Fn(n))return e;let r=[];try{r=gs(n).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(r.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():Ye()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of r){let f=$t(n,d);Ev(f,o);try{let m=new o(f,{readonly:!0});try{if(t.sessionId){let p=m.prepare(`SELECT
|
|
577
591
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
578
592
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
579
593
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
580
|
-
FROM session_events WHERE session_id = ?`).get(t.sessionId);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let m
|
|
594
|
+
FROM session_events WHERE session_id = ?`).get(t.sessionId);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume WHERE session_id = ?").get(t.sessionId);h?.bytes&&(c+=Number(h.bytes))}catch{}}else if(t.projectDir){let p=m.prepare(`SELECT
|
|
581
595
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
582
596
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
583
597
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
584
598
|
FROM session_events
|
|
585
599
|
WHERE session_id IN (
|
|
586
600
|
SELECT session_id FROM session_meta WHERE project_dir = ?
|
|
587
|
-
)`).get(t.projectDir);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let m
|
|
601
|
+
)`).get(t.projectDir);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=m.prepare(`SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes
|
|
588
602
|
FROM session_resume
|
|
589
603
|
WHERE session_id IN (
|
|
590
604
|
SELECT session_id FROM session_meta WHERE project_dir = ?
|
|
591
|
-
)`).get(t.projectDir);
|
|
605
|
+
)`).get(t.projectDir);h?.bytes&&(c+=Number(h.bytes))}catch{}}else{let p=m.prepare(`SELECT
|
|
592
606
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
593
607
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
594
608
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
595
|
-
FROM session_events`).get();p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let m=h.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();m?.bytes&&(c+=Number(m.bytes))}catch{}}}finally{h.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=bL(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let l=Math.floor((s+i+c)/4);return{eventDataBytes:s,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:l}}var kL={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};function EL(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(!Hr(t.sessionsDir))return n;let o=[];try{o=fs(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return n}if(o.length===0)return n;let s=null;try{s=e()}catch{return n}if(!s)return n;let i=new Set,a=new Set;for(let l of o){let d=Tt(t.sessionsDir,l);try{let f=new s(d,{readonly:!0});try{let h=f.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();h&&(n.eventCount+=Number(h.cnt??0),n.dataBytes+=Number(h.bytes??0));try{let p=f.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=f.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=f.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let m=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(m)&&m<n.firstMs&&(n.firstMs=m)}if(p?.mx){let m=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(m)&&m>n.lastMs&&(n.lastMs=m)}}catch{}try{let p=f.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let m of p)m.p&&i.add(m.p)}catch{}try{let p=f.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let m of p)m.s&&a.add(m.s)}catch{}}finally{f.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 xu(t){let e=SL({home:t?.home}),r=t?.loadDatabase??Ye,n={...kL,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!Hr(c.sessionsDir))continue;let u=EL(c,r,n);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}var cw={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},wL={"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"};function gu(t){return wL[t]??t}function et(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 TL(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 mu(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function PL(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!mu(e)&&(e=""),!e){if(process.platform==="darwin"){try{let n=gL("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}e&&!mu(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-")),e&&!mu(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return mu(e)||(e="en-US"),{locale:e,tz:r||"UTC"}}function YE(t){let e=_u();return e?t===e?"~":t.startsWith(e+_L)?"~"+t.slice(e.length):t:t}function RL(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*Vi(),o=(y,_=2)=>y.toFixed(_),s=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),f=(e*1.25/1e6).toFixed(2),h=(e*1/1e6).toFixed(2),p=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,m=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return p&&m?g.push(` $${o(n)} of ${m} tokens your team didn't burn.`):p?g.push(` $${o(n)} of tokens your team didn't burn.`):g.push(` $${o(n)} of Opus 4.7 tokens your team didn't burn.`),g.push(` context-mode kept ${et(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(g.push(""),g.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function $L(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],f=e.events*nw,h=Math.round((e.snapshotBytes??0)/4),p=f+h,m=o?.conversation?.totalSavedTokens??0,g=Math.max(p,m),y=(r?.totalEvents??0)*nw,_=Math.round((r?.rescueBytes??0)/4),x=y+_,S=o?.lifetime?.totalSavedTokens??0,k=Math.max(x,S),R=o?.lifetime?.bytesReturned??0,$=o?.lifetime?.bytesAvoided??0,C=R+$>0?Math.max(1,Math.floor(R/4)):Math.max(1,Math.round(k*.02)),A=n?.totalBytes&&n.totalBytes>0?n.totalBytes:k*4,W=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,T=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`,E=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,H=E>0?Math.max(1,Math.round((c-E)/864e5)):0,pe=n?.totalSessions??r?.totalSessions??1,dt=n?.perAdapter.filter(Me=>Me.isReal).length??0,gn;if(n&&dt>=2)gn=`across ${dt} AI tools`;else if(n&&dt===1){let Me=n.perAdapter.find(Vt=>Vt.isReal);gn=`in ${Me?gu(Me.name):"Claude Code"}`}else gn="in Claude Code";H>0?d.push(` Across ${H} days you ran ${sr(pe)} conversations ${gn}.`):d.push(` You ran ${sr(pe)} conversations ${gn}.`);let Aw=H>0?A/H:0;d.push(` context-mode kept ${et(A)} out of your context window \u2014 about ${et(Aw)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let ig=e.firstEventMs&&e.firstEventMs>0?QE(e.firstEventMs,i,a):"";if(ig?d.push(` This conversation started ${ig} in ${YE(s)}.`):d.push(` This conversation lives in ${YE(s)}.`),d.push(` ${T}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Me=e.lastRescueMs&&e.lastRescueMs>0?QE(e.lastRescueMs,i,a):"",Vt=Math.round(e.snapshotBytes/1024);Me?d.push(` On ${Me}, /compact fired \u2014 ${Vt} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${Vt} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let ag=o?.conversation,cg=ag?.bytesAvoided??0,Nu=ag?.bytesReturned??0;if(cg+Nu===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Me=cg+Nu,Vt=Math.max(1,Nu),Wt=Math.max(1,Math.floor(Me/4)),kr=Math.max(1,Math.floor(Vt/4)),Du=hn(Wt,Wt,32),zw=hn(kr,Wt,32),Lw=(1-kr/Wt)*100,Hw=Math.max(1,Math.round(Wt/kr));d.push(` Without context-mode ${et(Me).padStart(8)} ${Du} ${sr(Wt).padStart(7)} tokens`),d.push(` With context-mode ${et(Vt).padStart(8)} ${zw} ${sr(kr).padStart(7)} tokens`),d.push(` ${Lw.toFixed(0)}% kept out of context \xB7 your AI ran ${Hw}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Me=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${et(W)} built up \u2014 ${Me} days, ${e.byDay.length} active:`),d.push(""),d.push(...OL(e.byDay,i,a))}d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),d.push("");let Nw=e.byCategory.reduce((Me,Vt)=>Me+Vt.count,0).toLocaleString(i);d.push(` ${Nw} things \u2014 files, errors, decisions, agent runs:`),d.push("");let Dw=e.byCategory[0]?.count??1;for(let Me of e.byCategory)d.push(` ${Me.label.padEnd(26)} ${String(Me.count).padStart(5)} ${hn(Me.count,Dw,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let ug=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",lg=E>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(E)):"",dg=r?.distinctProjects??0,Mw=r?.totalEvents??n?.totalEvents??0;if(d.push(` This chat: ${et(W)} kept out \xB7 ${e.events.toLocaleString(i)} captures${ug?` \xB7 started ${ug}`:""}.`),d.push(` All your work: ${et(A)} kept out \xB7 ${Mw.toLocaleString(i)} captures across ${dg} project${dg===1?"":"s"}${lg?` \xB7 since ${lg}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...RL(A,k,H)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),r&&r.autoMemoryCount>0){d.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let Me=Object.entries(r.autoMemoryByPrefix).sort((Wt,kr)=>kr[1]-Wt[1]),Vt=Me.length>0?Me[0][1]:1;for(let[Wt,kr]of Me){let Du=cw[Wt]??Wt;d.push(` ${Du.padEnd(26)} ${String(kr).padStart(2)} ${hn(kr,Vt,20)}`)}}else d.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");d.push(""),d.push(""),d.push(" Your AI talks less, remembers more, costs less."),d.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),d.push("");let jw=u?`v${u}`:"context-mode";return d.push(` ${jw}`),u&&l&&l!=="unknown"&&sw(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),CL(d)}function CL(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 OL(t,e,r){if(t.length===0)return[];let n=[...t].sort((f,h)=>f.ms-h.ms),o=n[0],s=n[n.length-1],i=Math.max(1,s.ms-o.ms),a=n[0];for(let f of n)f.count>a.count&&(a=f);let c=56,u=Array.from({length:c},()=>"\u2500");for(let f of n){let h=Math.round((f.ms-o.ms)/i*(c-1)),p="\u25CF";f===a&&(p="\u2588"),(f.rescueBytes??0)>0&&(p="\u25C6"),u[h]=p}let l=f=>{let h=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(f)),p=(h.find(g=>g.type==="month")?.value??"").toLowerCase(),m=h.find(g=>g.type==="day")?.value??"";return`${p} ${m}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let f of n){let h=l(f.ms).padEnd(7),p=`${f.count} captures`,m=f===a?" \u2190 peak":"",g=(f.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((f.rescueBytes??0)/1024)} KB`:"";d.push(` ${h} ${p}${m}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function QE(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),s=d=>o.find(f=>f.type===d)?.value??"",i=s("day"),a=s("month"),c=s("year"),u=s("hour"),l=s("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${l} (${r})`}function sr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Vi(){let t=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN;if(t!==void 0&&t!==""){let e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 5/1e6}var UW=5/1e6;function yu(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Vi()).toFixed(2)}`}function hn(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 ew(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(m=>m.isReal).length??0,a=s?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=s?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let m=i>=2?" everywhere":"";o.push(` All your work${m} \xB7 ${sr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${sr(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let m=c===0&&r>0?1:c,g=m===1?"1 session":`${sr(m)} sessions`,y=a*256+r;o.push(` ${sr(a)} events \xB7 ${g} \xB7 ~${yu(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,m])=>m>0).map(([m,g])=>({category:m,count:g,label:hu[m]||m})).sort((m,g)=>g.count-m.count):d=(t.by_category??[]).filter(m=>m&&m.count>0);let f=d.slice(0,n),h=f.length>0?f[0].count:1;for(let m of f)o.push(` ${m.label.padEnd(26)} ${String(m.count).padStart(5)} ${hn(m.count,h,30)}`);let p=Math.max(0,d.length-n);return p>0&&o.push(` ... ${p} more categor${p===1?"y":"ies"}`),o}function tw(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[o,s]of r){let i=cw[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${hn(s,n,20)}`)}return e}function rw(t,e){let r=[],n=yu(t),o=(e?.totalEvents??0)*256+t,s=yu(o);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${s} lifetime`),r.push("\u2500".repeat(65)),r}var nw=256;function ow(t){if(!t)return[];let e=[],r=[];for(let o of t.perAdapter)(o.isReal?e:r).push(o);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let o=16,s=10,i=10,a=16;n.push(` ${"Tool".padEnd(o)}${"Captures".padStart(s)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,l)=>l.dataBytes+l.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let l=u.dataBytes+u.rescueBytes,d=u.eventCount>0?sr(u.eventCount):"\u2014",f=et(u.dataBytes),h=et(l);n.push(` ${gu(u.name).padEnd(o)}${d.padStart(s)}${f.padStart(i)}${h.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let o=r.map(s=>gu(s.name)).join(", ");n.push(` Skipped (${r.length}): ${o}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function Su(t,e,r,n){let o=[],s=TL(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,l=n?.multiAdapter,d=l?.perAdapter.filter(R=>R.isReal).length??0;if(l&&d>0){let R=l.totalSessions||i?.totalSessions||0,$=i?.firstEventMs??0,C=$>0?Math.max(1,Math.round((Date.now()-$)/864e5)):0,A=C>0?`Across ${C} day${C===1?"":"s"} `:"",W=R>0?`you ran ${sr(R)} conversation${R===1?"":"s"} `:"you ran ",T;if(d>=2)T=`across ${d} AI tools`;else{let E=l.perAdapter.find(H=>H.isReal);T=`in ${E?gu(E.name):"Claude Code"}`}o.push(`${A}${W}${T}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let R=PL(),$=n?.cwd??process.cwd(),C=n?.now??Date.now(),A=n?.locale??R.locale,W=n?.tz??R.tz;return o.push(...$L({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:$,locale:A,tz:W,now:C,version:e,latestVersion:r})),o.join(`
|
|
596
|
-
`)}let f=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),
|
|
597
|
-
`)}o.push(`${
|
|
598
|
-
`)}var
|
|
599
|
-
`)}),process.on("uncaughtException",t=>{
|
|
600
|
-
`)}));var
|
|
601
|
-
|
|
602
|
-
`);
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
`)}function v1(t,e,r,n=80*1024,o="batch"){let s=[],i=0,a=o==="global"?void 0:r;for(let c of e){if(i>n){s.push(`## ${c}
|
|
609
|
+
FROM session_events`).get();p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();h?.bytes&&(c+=Number(h.bytes))}catch{}}}finally{m.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=H1(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let l=Math.floor((s+i+c)/4);return{eventDataBytes:s,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:l}}var U1={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};function F1(t,e,n){let r={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!Fn(t.sessionsDir))return r;let o=[];try{o=gs(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return r}if(o.length===0)return r;let s=null;try{s=e()}catch{return r}if(!s)return r;let i=new Set,a=new Set;for(let l of o){let d=$t(t.sessionsDir,l);try{let f=new s(d,{readonly:!0});try{let m=f.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();m&&(r.eventCount+=Number(m.cnt??0),r.dataBytes+=Number(m.bytes??0));try{let p=f.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();r.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=f.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(r.rescueBytes+=Number(p.bytes))}catch{}try{let p=f.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<r.firstMs&&(r.firstMs=h)}if(p?.mx){let h=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>r.lastMs&&(r.lastMs=h)}}catch{}try{let p=f.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=f.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of p)h.s&&a.add(h.s)}catch{}}finally{f.close()}}catch{}}r.projectDirs=Array.from(i),r.uuidConvs=a.size;let c=r.eventCount>0?r.dataBytes/r.eventCount:0,u=r.lastMs>0&&n.nowMs-r.lastMs<=n.recencyMs;return r.isReal=r.eventCount>=n.minEvents&&i.size>=n.minProjects&&u&&c>=n.minAvgBytes,r}function Au(t){let e=z1({home:t?.home}),n=t?.loadDatabase??Ye,r={...U1,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!Fn(c.sessionsDir))continue;let u=F1(c,n,r);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}var nT={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},Z1={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity","antigravity-cli":"Antigravity CLI",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot","copilot-cli":"GitHub Copilot CLI",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};function $u(t){return Z1[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 n=e/1024;if(n<1024)return n<100?`${n.toFixed(1)} MB`:`${Math.round(n)} MB`;let r=n/1024;return r<100?`${r.toFixed(2)} GB`:`${r.toFixed(1)} GB`}function B1(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let n=Math.floor(e/60),r=Math.round(e%60);return r>0?`${n}h ${r}m`:`${n}h`}function Ru(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function q1(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!Ru(e)&&(e=""),!e){if(process.platform==="darwin"){try{let r=N1("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();r&&(e=r.replace(/_/g,"-"))}catch{}e&&!Ru(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let r=(t.LC_TIME||t.LANG||"").split(".")[0];r&&(e=r.replace(/_/g,"-")),e&&!Ru(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let n=t.CONTEXT_MODE_TZ??"";if(!n)try{n=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n="UTC"}return Ru(e)||(e="en-US"),{locale:e,tz:n||"UTC"}}function Vw(t){let e=Iu();return e?t===e?"~":t.startsWith(e+M1)?"~"+t.slice(e.length):t:t}function V1(t,e,n){if(!Number.isFinite(e)||e<=0)return[];let r=e*Yi(),o=(y,_=2)=>y.toFixed(_),s=Math.round(r/20),i=(r/200).toFixed(1),a=Math.round(r/73.67),c=Math.round(r*10),u=n>0?Math.round(r*10/n*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),f=(e*1.25/1e6).toFixed(2),m=(e*1/1e6).toFixed(2),p=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,h=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return p&&h?g.push(` $${o(r)} of ${h} tokens your team didn't burn.`):p?g.push(` $${o(r)} of tokens your team didn't burn.`):g.push(` $${o(r)} of Opus 4.7 tokens your team didn't burn.`),g.push(` context-mode kept ${tt(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(g.push(""),g.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function W1(t){let{conversation:e,lifetime:n,multiAdapter:r,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],f=e.events*Xw,m=Math.round((e.snapshotBytes??0)/4),p=f+m,h=o?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(n?.totalEvents??0)*Xw,_=Math.round((n?.rescueBytes??0)/4),S=y+_,k=o?.lifetime?.totalSavedTokens??0,v=Math.max(S,k),O=o?.lifetime?.bytesReturned??0,R=o?.lifetime?.bytesAvoided??0,M=O+R>0?Math.max(1,Math.floor(O/4)):Math.max(1,Math.round(v*.02)),D=r?.totalBytes&&r.totalBytes>0?r.totalBytes:v*4,V=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,P=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`,T=n?.firstEventMs??r?.perAdapter?.[0]?.firstMs??0,H=T>0?Math.max(1,Math.round((c-T)/864e5)):0,pe=r?.totalSessions??n?.totalSessions??1,ft=r?.perAdapter.filter(Ne=>Ne.isReal).length??0,En;if(r&&ft>=2)En=`across ${ft} AI tools`;else if(r&&ft===1){let Ne=r.perAdapter.find(Wt=>Wt.isReal);En=`in ${Ne?$u(Ne.name):"Claude Code"}`}else En="in Claude Code";H>0?d.push(` Across ${H} days you ran ${sn(pe)} conversations ${En}.`):d.push(` You ran ${sn(pe)} conversations ${En}.`);let Gu=H>0?D/H:0;d.push(` context-mode kept ${tt(D)} out of your context window \u2014 about ${tt(Gu)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let Og=e.firstEventMs&&e.firstEventMs>0?Ww(e.firstEventMs,i,a):"";if(Og?d.push(` This conversation started ${Og} in ${Vw(s)}.`):d.push(` This conversation lives in ${Vw(s)}.`),d.push(` ${P}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ne=e.lastRescueMs&&e.lastRescueMs>0?Ww(e.lastRescueMs,i,a):"",Wt=Math.round(e.snapshotBytes/1024);Ne?d.push(` On ${Ne}, /compact fired \u2014 ${Wt} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${Wt} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let Ig=o?.conversation,Ag=Ig?.bytesAvoided??0,Ju=Ig?.bytesReturned??0;if(Ag+Ju===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Ne=Ag+Ju,Wt=Math.max(1,Ju),Kt=Math.max(1,Math.floor(Ne/4)),wn=Math.max(1,Math.floor(Wt/4)),Xu=gr(Kt,Kt,32),OT=gr(wn,Kt,32),IT=(1-wn/Kt)*100,AT=Math.max(1,Math.round(Kt/wn));d.push(` Without context-mode ${tt(Ne).padStart(8)} ${Xu} ${sn(Kt).padStart(7)} tokens`),d.push(` With context-mode ${tt(Wt).padStart(8)} ${OT} ${sn(wn).padStart(7)} tokens`),d.push(` ${IT.toFixed(0)}% kept out of context \xB7 your AI ran ${AT}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Ne=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${tt(V)} built up \u2014 ${Ne} days, ${e.byDay.length} active:`),d.push(""),d.push(...G1(e.byDay,i,a))}d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),d.push("");let PT=e.byCategory.reduce((Ne,Wt)=>Ne+Wt.count,0).toLocaleString(i);d.push(` ${PT} things \u2014 files, errors, decisions, agent runs:`),d.push("");let RT=e.byCategory[0]?.count??1;for(let Ne of e.byCategory)d.push(` ${Ne.label.padEnd(26)} ${String(Ne.count).padStart(5)} ${gr(Ne.count,RT,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let Ng=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Dg=T>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(T)):"",Mg=n?.distinctProjects??0,CT=n?.totalEvents??r?.totalEvents??0;if(d.push(` This chat: ${tt(V)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Ng?` \xB7 started ${Ng}`:""}.`),d.push(` All your work: ${tt(D)} kept out \xB7 ${CT.toLocaleString(i)} captures across ${Mg} project${Mg===1?"":"s"}${Dg?` \xB7 since ${Dg}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...V1(D,v,H)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),n&&n.autoMemoryCount>0){d.push(` ${n.autoMemoryCount} preferences picked up across ${n.autoMemoryProjects} project${n.autoMemoryProjects===1?"":"s"}:`);let Ne=Object.entries(n.autoMemoryByPrefix).sort((Kt,wn)=>wn[1]-Kt[1]),Wt=Ne.length>0?Ne[0][1]:1;for(let[Kt,wn]of Ne){let Xu=nT[Kt]??Kt;d.push(` ${Xu.padEnd(26)} ${String(wn).padStart(2)} ${gr(wn,Wt,20)}`)}}else d.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");d.push(""),d.push(""),d.push(" Your AI talks less, remembers more, costs less."),d.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),d.push("");let $T=u?`v${u}`:"context-mode";return d.push(` ${$T}`),u&&l&&l!=="unknown"&&Qw(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),K1(d)}function K1(t){let e=[],n=0;for(let r of t)r===""?(n++,n<=2&&e.push(r)):(n=0,e.push(r));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function G1(t,e,n){if(t.length===0)return[];let r=[...t].sort((f,m)=>f.ms-m.ms),o=r[0],s=r[r.length-1],i=Math.max(1,s.ms-o.ms),a=r[0];for(let f of r)f.count>a.count&&(a=f);let c=56,u=Array.from({length:c},()=>"\u2500");for(let f of r){let m=Math.round((f.ms-o.ms)/i*(c-1)),p="\u25CF";f===a&&(p="\u2588"),(f.rescueBytes??0)>0&&(p="\u25C6"),u[m]=p}let l=f=>{let m=new Intl.DateTimeFormat(e,{timeZone:n,month:"short",day:"numeric"}).formatToParts(new Date(f)),p=(m.find(g=>g.type==="month")?.value??"").toLowerCase(),h=m.find(g=>g.type==="day")?.value??"";return`${p} ${h}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let f of r){let m=l(f.ms).padEnd(7),p=`${f.count} captures`,h=f===a?" \u2190 peak":"",g=(f.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((f.rescueBytes??0)/1024)} KB`:"";d.push(` ${m} ${p}${h}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function Ww(t,e,n){if(!Number.isFinite(t)||t<=0)return"";let r=new Date(t);if(Number.isNaN(r.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:n,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(r),s=d=>o.find(f=>f.type===d)?.value??"",i=s("day"),a=s("month"),c=s("year"),u=s("hour"),l=s("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${l} (${n})`}function sn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Yi(){let t=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN;if(t!==void 0&&t!==""){let e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 5/1e6}var $6=5/1e6;function Ou(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Yi()).toFixed(2)}`}function gr(t,e,n=40){if(e<=0)return"\u2591".repeat(n);let r=Math.max(1,Math.round(t/e*n));return"\u2588".repeat(Math.min(r,n))+"\u2591".repeat(Math.max(0,n-r))}function Kw(t,e){let n=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&n===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let r=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(h=>h.isReal).length??0,a=s?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=s?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let h=i>=2?" everywhere":"";o.push(` All your work${h} \xB7 ${sn(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${sn(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&n>0?1:c,g=h===1?"1 session":`${sn(h)} sessions`,y=a*256+n;o.push(` ${sn(a)} events \xB7 ${g} \xB7 ~${Ou(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:Cu[h]||h})).sort((h,g)=>g.count-h.count):d=(t.by_category??[]).filter(h=>h&&h.count>0);let f=d.slice(0,r),m=f.length>0?f[0].count:1;for(let h of f)o.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${gr(h.count,m,30)}`);let p=Math.max(0,d.length-r);return p>0&&o.push(` ... ${p} more categor${p===1?"y":"ies"}`),o}function Gw(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let n=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),r=n.length>0?n[0][1]:1;for(let[o,s]of n){let i=nT[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${gr(s,r,20)}`)}return e}function Jw(t,e){let n=[],r=Ou(t),o=(e?.totalEvents??0)*256+t,s=Ou(o);return n.push(""),n.push("\u2500".repeat(65)),n.push("Your AI talks less, remembers more, costs less."),n.push(`${r} this session \xB7 ${s} lifetime`),n.push("\u2500".repeat(65)),n}var Xw=256;function Yw(t){if(!t)return[];let e=[],n=[];for(let o of t.perAdapter)(o.isReal?e:n).push(o);if(e.length===0&&n.length===0)return[];let r=[];if(e.length>0){r.push(""),r.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),r.push("");let o=16,s=10,i=10,a=16;r.push(` ${"Tool".padEnd(o)}${"Captures".padStart(s)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,l)=>l.dataBytes+l.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let l=u.dataBytes+u.rescueBytes,d=u.eventCount>0?sn(u.eventCount):"\u2014",f=tt(u.dataBytes),m=tt(l);r.push(` ${$u(u.name).padEnd(o)}${d.padStart(s)}${f.padStart(i)}${m.padStart(a)}`)}}if(n.length>0){e.length>0&&r.push("");let o=n.map(s=>$u(s.name)).join(", ");r.push(` Skipped (${n.length}): ${o}`),r.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),r.push(" or detection probes \u2014 no real chat activity.")}return r}function Nu(t,e,n,r){let o=[],s=B1(t.session.uptime_min),i=r?.lifetime,a=r?.mcpUsage,c=r?.conversation,u=r?.realBytes,l=r?.multiAdapter,d=l?.perAdapter.filter(O=>O.isReal).length??0;if(l&&d>0){let O=l.totalSessions||i?.totalSessions||0,R=i?.firstEventMs??0,M=R>0?Math.max(1,Math.round((Date.now()-R)/864e5)):0,D=M>0?`Across ${M} day${M===1?"":"s"} `:"",V=O>0?`you ran ${sn(O)} conversation${O===1?"":"s"} `:"you ran ",P;if(d>=2)P=`across ${d} AI tools`;else{let T=l.perAdapter.find(H=>H.isReal);P=`in ${T?$u(T.name):"Claude Code"}`}o.push(`${D}${V}${P}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let O=q1(),R=r?.cwd??process.cwd(),M=r?.now??Date.now(),D=r?.locale??O.locale,V=r?.tz??O.tz;return o.push(...W1({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:R,locale:D,tz:V,now:M,version:e,latestVersion:n})),o.join(`
|
|
610
|
+
`)}let f=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),m=t.savings.total_bytes_returned,p=t.savings.total_calls,h=f+m,g=h>0?f/h*100:0,y=Math.round(f/4),_=m>0?Math.max(1,Math.round(h/Math.max(m,1))):0;if(f===0){o.push(`context-mode ${s} ${p} calls`),o.push(""),p===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${tt(m)} entered context | 0 tokens saved`),o.push(...Kw(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...Yw(l)),o.push(...Gw(i)),o.push(...Jw(0,i)),o.push("");let O=e?`v${e}`:"context-mode";return o.push(O),e&&n&&n!=="unknown"&&Qw(n,e)&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
|
|
611
|
+
`)}o.push(`${sn(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${Ou(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${gr(h,h)}| ${tt(h)}`),o.push(`With context-mode |${gr(m,h)}| ${tt(m)}`),o.push(""),_>=2?o.push(`${tt(f)} kept out of your conversation \u2014 ${_}\xD7 longer sessions before compact.`):o.push(`${tt(f)} kept out of your conversation. Never entered context.`),o.push("");let S=[`${p} calls`];t.cache&&t.cache.hits>0&&S.push(`${t.cache.hits} cache hits (+${tt(t.cache.bytes_saved)})`),o.push(S.join(" \xB7 "));let k=t.savings.by_tool.filter(O=>O.calls>0);if(k.length>=2){o.push("");let O=k.map(R=>{let M=R.context_kb*1024,D=g<100?M/(1-g/100):M,V=Math.max(0,D-M);return{...R,returnedBytes:M,estimatedSaved:V}}).sort((R,M)=>M.estimatedSaved-R.estimatedSaved);for(let R of O){let M=R.tool.length>22?R.tool.slice(0,19)+"...":R.tool;o.push(` ${M.padEnd(22)} ${String(R.calls).padStart(4)} calls ${tt(R.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let O=a.filter(R=>R.median_concurrency!=null&&(R.max_concurrency??1)>1);if(O.length>0){o.push(""),o.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let R of O){let M=R.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${M.padEnd(22)} ${R.calls} batches \xB7 ${R.median_concurrency} typical, ${R.max_concurrency} peak`)}}}o.push(...Kw(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...Yw(l)),o.push(...Gw(i)),o.push(...Jw(y,i)),o.push("");let v=e?`v${e}`:"context-mode";return o.push(v),e&&n&&n!=="unknown"&&n!==e&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
|
|
612
|
+
`)}var zu=bs(nH(import.meta.url)),Zn=(()=>{for(let t of["../package.json","./package.json"]){let e=pt(zu,t);if(ze(e))try{return JSON.parse(ta(e,"utf8")).version}catch{}}return"unknown"})();function _T(){return ze(pt(zu,"package.json"))?zu:bs(zu)}function iH(t){try{let e=process.platform==="win32"?Fu("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):Fu("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});if(e.status!==0)return t;let n=au(String(e.stdout));if(n&&ze(pt(n,".codex-plugin","hooks.json")))return n}catch{}return t}function ST(t){let e=_T();return t==="codex"?iH(e):e}process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
|
|
613
|
+
`)}),process.on("uncaughtException",t=>{try{J1(2,`[context-mode] uncaughtException: ${t?.message??t}
|
|
614
|
+
`)}finally{process.exit(1)}}));var fo=Bc(),Lu=jb(fo),Te=new zc({name:"context-mode",version:Zn}),aH=[];function cH(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let n=t.platform??vt().platform;if(n!=="opencode"&&n!=="kilo")return!1;let r=t.settings??uH(n);return lH(r)&&dH(r)}function uH(t){let e=t==="kilo"?"kilo":"opencode",n=[pt(`${e}.json`),pt(`${e}.jsonc`),pt(`.${e}`,`${e}.json`),pt(`.${e}`,`${e}.jsonc`),Et(ks(),".config",e,`${e}.json`),Et(ks(),".config",e,`${e}.jsonc`)];for(let r of n)try{if(!ze(r))continue;return JSON.parse(Hi(ta(r,"utf8")))}catch{}return null}function lH(t){let e=t?.plugin;return Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.includes("context-mode"))}function dH(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}var xT=cH(),Sg=!1;function pH(t={}){if(Sg)return;Sg=!0;let e=t.write??(r=>{process.stderr.write(r)}),n=t.platform??"opencode/kilo";e(`[context-mode] ctx_* tools/list intentionally empty on this MCP child: legacy mcp.context-mode block coexists with plugin: ["context-mode"] in ${n}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
|
|
615
|
+
`)}function g3(){Sg=!1}function fH(t=Te){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(Ur,async()=>({tools:[]}))}var mH=Te.registerTool.bind(Te);Te.registerTool=(...t)=>{let[e,n,r]=t;if(xT){pH();return}let o=hH(e,r);return aH.push({name:e,config:n,handler:o}),t[2]=o,mH(...t)};function hH(t,e){return async n=>{try{return await e(n)}catch(r){let o=bH(r);if(o)try{return K(t,o)}catch(s){if(s instanceof dr)return o;throw s}throw r}}}xT&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&fH(Te);var wg=new sH;async function y3(t,e){let n=typeof t=="string"?{projectDir:t}:t;return wg.run(n,e)}Te.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Te.server.setRequestHandler(Oo,async()=>({prompts:[]}));Te.server.setRequestHandler(Co,async()=>({resources:[]}));Te.server.setRequestHandler($o,async()=>({resourceTemplates:[]}));function xg(t){if(Array.isArray(t))return t.map(xg);if(t===null||typeof t!="object")return t;let e={};for(let[n,r]of Object.entries(t))if(n!=="additionalProperties"){if(n==="const"){e.enum=[r];continue}e[n]=xg(r)}return e}function gH(t=Te){try{let n=t.server._requestHandlers?.get("tools/list");if(typeof n!="function")return;t.server.setRequestHandler(Ur,async(r,o)=>{let s=await n(r,o);if(s&&Array.isArray(s.tools)){for(let i of s.tools)if(!(!i||i.inputSchema==null))try{i.inputSchema=xg(i.inputSchema)}catch{}}return s})}catch{}}var na=new Ci({runtimes:fo,projectRoot:()=>Ot()}),Ku=Et(Eg(),`cm-fs-preload-${process.pid}.js`);Uu(Ku,`(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){}})();
|
|
616
|
+
`);process.on("exit",()=>{try{xs(Ku)}catch{}});var an=null;function yr(){let t=wg.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??yH();if(e)return{sessionId:e}}var Du;function yH(t){let e=Date.now();if(!t?.bypassCache&&Du&&e-Du.checkedAt<2e3)return Du.sid;try{let n=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!n)return;let r=t?.sessionsDir??je(),o=ji({projectDir:n,sessionsDir:r});if(!ze(o))return;let s=Ye(),i=new s(o,{readonly:!0,fileMustExist:!0});try{let c=i.prepare("SELECT session_id FROM session_events ORDER BY created_at DESC LIMIT 1").get()?.session_id;return c&&(Du={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function _H(t){try{let e=je();if(!ze(e))return;let n=fT(e).filter(r=>r.endsWith("-events.md"));for(let r of n){let o=Et(e,r);try{t.index({path:o,source:"session-events",attribution:yr()}),xs(o)}catch{}}}catch{}}var cn=null;async function SH(){if(cn)return cn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(fs(),rg)),e=vt();return await t(e.platform)}catch{return null}}function _s(){if(cn)return cn.getSessionDir();try{let t=vt(),e=Vi(t.platform);if(e)return Gm({configDir:Et(...e),configDirEnv:xH(e)})}catch{}return Gm({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function xH(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function je(){return eu(Mi(_s))}function Ot(){let t=wg.getStore();if(t)return t.projectDir;let e,n,r;try{let o=vt().platform;n=o,o==="claude-code"&&(e=Et(ks(),".claude","projects")),o==="codex"&&(r=process.env.CODEX_HOME??Et(ks(),".codex"))}catch{}return qw({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:n,codexHome:r})}function kH(t){return tH(t)?t:pt(Ot(),t)}function ea(){return ji({projectDir:Ot(),sessionsDir:je()})}function Zu(){let t=eu(Jm(_s));return bv({projectDir:Ot(),contentDir:t})}function vn(){if(!an){let t=Zu();an=new Jc(t),an.setDenyChecker(e=>{try{let n=Ot(),r=bu("Read",n);return vu(e,r,process.platform==="win32",n).denied}catch{return!0}});try{let e=bs(Zu());qm(e,14),an.cleanupStaleSources(14);let n=Et(ks(),".context-mode","content");ze(n)&&qm(n,0)}catch{}Bm()}return _H(an),an}var ne={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};function bH(t){return t instanceof dr?{content:[{type:"text",text:Sv(t)}],isError:!0}:null}var Bn=null,Mu=0,rT=0,vH=3,EH=3600*1e3;async function oT(){return new Promise(t=>{let e=oH("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{try{let o=JSON.parse(r);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function wH(){let t=cn?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function TH(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function PH(){return!Bn||Bn==="unknown"?!1:TH(Bn,Zn)}function RH(){if(!PH())return!1;let t=Date.now();if(Mu>=vH){if(t-rT<EH)return!1;Mu=0}return Mu===0&&(rT=t),Mu++,!0}var sT=!1;function CH(){if(!sT){sT=!0;try{let t=Rt(),e=pt(t,"plugins","installed_plugins.json");if(!ze(e))return;let n=JSON.parse(ta(e,"utf-8")),r=pt(t,"plugins","cache"),o;try{o=yT(r)}catch{o=r}let s=_T();for(let[i,a]of Object.entries(n.plugins??{}))if(i==="context-mode@context-mode")for(let c of a){let u=c.installPath;if(!u||ze(u)||!pt(u).startsWith(o+eH))continue;try{gT(u).isSymbolicLink()&&xs(u)}catch{}let l=bs(u);ze(l)||Y1(l,{recursive:!0}),ze(s)&&Q1(s,u,process.platform==="win32"?"junction":void 0)}}catch{}}}function K(t,e){if(CH(),RH()&&e.content.length>0){let r=wH();e.content[0].text=`\u26A0\uFE0F context-mode v${Zn} outdated \u2192 v${Bn} available. Upgrade: ${r}
|
|
617
|
+
|
|
618
|
+
`+e.content[0].text}let n=e.content.reduce((r,o)=>r+Buffer.byteLength(o.text),0);return ne.calls[t]=(ne.calls[t]||0)+1,ne.bytesReturned[t]=(ne.bytesReturned[t]||0)+n,Bu(),setImmediate(()=>Dw(ea(),t,n)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>Ow({sessionDbPath:ea(),toolName:t,bytesReturned:n})),e}function un(t,e="unknown"){ne.bytesIndexed+=t,Bu(),t>0&&setImmediate(()=>Iw({sessionDbPath:ea(),source:e,bytesAvoided:t}))}var $H=500,OH=2,IH=3e4,AH=256,kg=0,ju,NH=/^[A-Za-z0-9._-]+$/;function DH(t){return NH.test(t)?t:`pid-${process.ppid}`}function kT(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=DH(t),n=eu(Xm(_s));return Et(n,`stats-${e}.json`)}function Bu(){let t=Date.now();if(!(t-kg<$H)){kg=t;try{let e=Object.values(ne.bytesReturned).reduce((d,f)=>d+f,0),n=Object.values(ne.calls).reduce((d,f)=>d+f,0),r=ne.bytesIndexed+ne.bytesSandboxed+ne.cacheBytesSaved,o=r+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(r/4),a=ju?.tokens??0;if(!ju||t-ju.computedAt>IH)try{a=(Ji({sessionsDir:je()})?.totalEvents??0)*AH,ju={tokens:a,computedAt:t}}catch{}let c={schemaVersion:OH,version:Zn,updated_at:t,session_start:ne.sessionStart,uptime_ms:t-ne.sessionStart,total_calls:n,bytes_returned:e,bytes_indexed:ne.bytesIndexed,bytes_sandboxed:ne.bytesSandboxed,cache_hits:ne.cacheHits,cache_bytes_saved:ne.cacheBytesSaved,kept_out:r,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*Yi()).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*Yi()).toFixed(2),by_tool:Object.fromEntries(Object.keys({...ne.calls,...ne.bytesReturned}).map(d=>[d,{calls:ne.calls[d]||0,bytes:ne.bytesReturned[d]||0}]))},u=kT(),l=`${u}.tmp`;Uu(l,JSON.stringify(c)),X1(l,u)}catch{}}}function Tg(t,e){try{let n=ag(process.env.CLAUDE_PROJECT_DIR),r=cg(t,n);if(r.decision==="deny")return K(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${r.matchedPattern}`}],isError:!0})}catch{}return null}function bT(t,e,n){try{let r=Pw(t,e);if(r.length===0)return null;let o=ag(process.env.CLAUDE_PROJECT_DIR);for(let s of r){let i=cg(s,o);if(i.decision==="deny")return K(n,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function bg(t,e){try{let n=Ot(),r=bu("Read",n),o=vu(t,r,process.platform==="win32",n);if(o.denied)return K(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}var MH=Lu.join(", "),jH=qc()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",zH="",LH="";function HH(t){let e=[],n=0,r=0;for(;r<t.length;)if(t[r]===zH){for(e.push(n),r++;r<t.length&&t[r]!==LH;)n++,r++;r<t.length&&r++}else n++,r++;return e}function vT(t,e,n=1500,r){if(t.length<=n)return t;let o=[];if(r)for(let u of HH(r))o.push(u);if(o.length===0){let u=e.toLowerCase().split(/\s+/).filter(d=>d.length>2),l=t.toLowerCase();for(let d of u){let f=l.indexOf(d);for(;f!==-1;)o.push(f),f=l.indexOf(d,f+1)}}if(o.length===0)return t.slice(0,n)+`
|
|
619
|
+
\u2026`;o.sort((u,l)=>u-l);let s=300,i=[];for(let u of o){let l=Math.max(0,u-s),d=Math.min(t.length,u+s);i.length>0&&l<=i[i.length-1][1]?i[i.length-1][1]=d:i.push([l,d])}let a=[],c=0;for(let[u,l]of i){if(c>=n)break;let d=t.slice(u,Math.min(l,u+(n-c)));a.push((u>0?"\u2026":"")+d+(l<t.length?"\u2026":"")),c+=d.length}return a.join(`
|
|
620
|
+
|
|
621
|
+
`)}function UH(t,e,n,r=80*1024,o="batch"){let s=[],i=0,a=o==="global"?void 0:n;for(let c of e){if(i>r){s.push(`## ${c}
|
|
610
622
|
(output cap reached \u2014 use ctx_search(queries: ["${c}"]) for details)
|
|
611
|
-
`);continue}let u=t.searchWithFallback(c,3,a,void 0,"exact");if(s.push(`## ${c}`),s.push(""),u.length>0){for(let l of u){let d=
|
|
612
|
-
> **Scope:** Queries searched the entire persistent index (query_scope: "global").`):s.push('\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])` or call ctx_batch_execute with `query_scope: "global"`.'),s}function
|
|
613
|
-
\u2026 (truncated)`}function
|
|
623
|
+
`);continue}let u=t.searchWithFallback(c,3,a,void 0,"exact");if(s.push(`## ${c}`),s.push(""),u.length>0){for(let l of u){let d=vT(l.content,c,3e3,l.highlighted);s.push(`### ${l.title}`),s.push(d),s.push(""),i+=d.length+l.title.length}continue}s.push("No matching sections found."),s.push("")}return o==="global"?s.push(`
|
|
624
|
+
> **Scope:** Queries searched the entire persistent index (query_scope: "global").`):s.push('\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])` or call ctx_batch_execute with `query_scope: "global"`.'),s}function FH(t){return`'${t.replace(/'/g,"'\\''")}'`}function ZH(t){return`'${t.replace(/'/g,"''")}'`}function BH(t,e){let n=`--require ${e}`,r=t.toLowerCase(),o=r.split(/[\\/]/).pop()??r;return r.includes("powershell")||r.includes("pwsh")?`$env:NODE_OPTIONS=${ZH(n)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${n.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${FH(n)} `}var iT=500;function ET(t){let e=t.replace(/\s+/g," ").trim();return e.length<=iT?e:e.slice(0,iT)+"\u2026"}var qH=12e4;function Pg(t){if(t!==void 0)return t;if(vt().platform!=="antigravity-cli")return;let e=Number(process.env.CONTEXT_MODE_AGY_EXEC_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:qH}var aT=2e3;function VH(t){return t.length<=aT?t:t.slice(0,aT)+`
|
|
625
|
+
\u2026 (truncated)`}function wT(t,e,n){let r=n?`path=${n}
|
|
614
626
|
`:"",o=`\`\`\`${t}
|
|
615
|
-
${
|
|
616
|
-
\`\`\``;return`${
|
|
627
|
+
${VH(e)}
|
|
628
|
+
\`\`\``;return`${r}${o}
|
|
617
629
|
|
|
618
|
-
`}function
|
|
630
|
+
`}function cT(t,e,n,r){let o=n||"(no output)",s=o.matchAll(/__CM_FS__:(\d+)/g),i=0;for(let c of s)i+=parseInt(c[1]);i>0&&(r?.(i),o=o.replace(/__CM_FS__:\d+\n?/g,""));let a=ET(e);return`# ${t}
|
|
619
631
|
|
|
620
632
|
$ ${a}
|
|
621
633
|
|
|
622
634
|
${o}
|
|
623
|
-
`}function
|
|
635
|
+
`}function uT(t){let e=t.stdout||"",n=t.stderr||"";return n?e?`${e}${e.endsWith(`
|
|
624
636
|
`)?"":`
|
|
625
|
-
`}${
|
|
637
|
+
`}${n}`:n:e}async function WH(t,e,n){let{timeout:r,concurrency:o,nodeOptsPrefix:s,cwd:i,onFsBytes:a}=e;if(o<=1){let f=[],m=Date.now(),p=!1;for(let h=0;h<t.length;h++){let g=t[h],y;if(r!==void 0){let S=Date.now()-m,k=r-S;if(k<=0){f.push(`# ${g.label}
|
|
626
638
|
|
|
627
639
|
(skipped \u2014 batch timeout exceeded)
|
|
628
|
-
`),
|
|
640
|
+
`),p=!0;continue}y=k}let _=await n.execute({language:"shell",code:`${s}${g.command}`,timeout:y,cwd:i});if(f.push(cT(g.label,g.command,uT(_),a)),_.timedOut){p=!0;for(let S=h+1;S<t.length;S++)f.push(`# ${t[S].label}
|
|
629
641
|
|
|
630
642
|
(skipped \u2014 batch timeout exceeded)
|
|
631
|
-
`);break}}return{outputs:
|
|
632
|
-
(timed out after ${
|
|
633
|
-
`:
|
|
643
|
+
`);break}}return{outputs:f,timedOut:p}}let c=t.map(f=>({run:async()=>{let m=await n.execute({language:"shell",code:`${s}${f.command}`,timeout:r,cwd:i}),p=cT(f.label,f.command,uT(m),a);return{output:m.timedOut?p.replace(/\n$/,"")+`
|
|
644
|
+
(timed out after ${r??"?"}ms)
|
|
645
|
+
`:p,timedOut:!!m.timedOut}}})),{settled:u}=await Dm(c,{concurrency:o}),l=new Array(t.length),d=!1;for(let f=0;f<u.length;f++){let m=u[f];if(m.status==="fulfilled")l[f]=m.value.output,m.value.timedOut&&(d=!0);else{let p=m.reason instanceof Error?m.reason.message:String(m.reason);l[f]=`# ${t[f].label}
|
|
634
646
|
|
|
635
|
-
(executor error: ${
|
|
636
|
-
`}}return{outputs:
|
|
647
|
+
(executor error: ${p})
|
|
648
|
+
`}}return{outputs:l,timedOut:d}}Te.registerTool("ctx_execute",{title:"Execute Code",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run code in a sandboxed subprocess.${jH} Languages: ${MH}.
|
|
637
649
|
|
|
638
650
|
Think-in-Code \u2014 the core philosophy: the bytes your code processes never enter your conversation memory; only what you console.log() does. Reading a 700 KB log directly means 700 KB of your remaining reasoning capacity gets spent on raw bytes. Running code over that same log in this sandbox and printing a 3 KB summary leaves you with 697 KB of capacity for the actual work.
|
|
639
651
|
|
|
@@ -663,10 +675,10 @@ WHEN NOT:
|
|
|
663
675
|
RETURNS:
|
|
664
676
|
Only what your code prints. Wrap risky calls in try/catch \u2014 uncaught errors go to stderr and may leak more than intended. When \`intent\` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout; use ctx_search(queries: [...]) to drill into specific sections.
|
|
665
677
|
|
|
666
|
-
EXAMPLE: ctx_execute(language: "
|
|
667
|
-
EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(\`\${hooks.length} hook-related issues\`)")`,inputSchema
|
|
678
|
+
EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('npm test', {encoding:'utf8', stdio:['ignore','pipe','pipe']}); console.log(out.split('\\\\n').filter(l => /(FAIL|\u2717|\xD7|Error:|Tests +.*(failed|passed))/i.test(l)).slice(0, 60).join('\\\\n'))")
|
|
679
|
+
EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(\`\${hooks.length} hook-related issues\`)")`,inputSchema:$.object({language:$.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:$.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), IO.puts (Elixir), or Console.WriteLine (C#) to output a summary to context."),timeout:$.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:$.preprocess($g,$.boolean()).optional().default(!1).describe("Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts \u2014 the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background."),cwd:$.string().optional().describe("Optional working directory for shell commands. Non-shell languages still execute from their sandbox temp directory."),intent:$.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'.
|
|
668
680
|
|
|
669
|
-
TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:
|
|
681
|
+
TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:n,background:r,cwd:o,intent:s})=>{if(t==="shell"){let i=Tg(e,"execute");if(i)return i}else{let i=bT(e,t,"execute");if(i)return i}try{let i=e;(t==="javascript"||t==="typescript")&&(i=`
|
|
670
682
|
// FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
|
|
671
683
|
let __cm_fs=0;
|
|
672
684
|
process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
|
|
@@ -723,21 +735,21 @@ if(__cm_req.cache)require.cache=__cm_req.cache;}
|
|
|
723
735
|
async function __cm_main(){
|
|
724
736
|
${e}
|
|
725
737
|
}
|
|
726
|
-
__cm_main().catch(e=>{console.error(e);process.exitCode=1});${
|
|
738
|
+
__cm_main().catch(e=>{console.error(e);process.exitCode=1});${r?`
|
|
727
739
|
setInterval(()=>{},2147483647);`:""}
|
|
728
|
-
})(typeof require!=='undefined'?require:null);`);let
|
|
740
|
+
})(typeof require!=='undefined'?require:null);`);let a=Pg(n),c=await na.execute({language:t,code:i,timeout:a,background:r,cwd:o}),u=wT(t,e),l=c.stderr?.match(/__CM_NET__:(\d+)/);l&&(ne.bytesSandboxed+=parseInt(l[1]),c.stderr=c.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let d=c.stderr?.match(/__CM_FS__:(\d+)/);if(d&&(ne.bytesSandboxed+=parseInt(d[1]),c.stderr=c.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),c.timedOut){let m=c.stdout?.trim();return c.backgrounded&&m?K("ctx_execute",{content:[{type:"text",text:`${u}${m}
|
|
729
741
|
|
|
730
|
-
_(process backgrounded after ${
|
|
742
|
+
_(process backgrounded after ${a}ms \u2014 still running)_`}]}):m?K("ctx_execute",{content:[{type:"text",text:`${u}${m}
|
|
731
743
|
|
|
732
|
-
_(timed out after ${
|
|
744
|
+
_(timed out after ${a}ms \u2014 partial output shown above)_`}]}):K("ctx_execute",{content:[{type:"text",text:`${u}Execution timed out after ${a}ms
|
|
733
745
|
|
|
734
746
|
stderr:
|
|
735
|
-
${
|
|
736
|
-
Use ctx_search(queries: ["..."]) to query this content. Use source: "${
|
|
737
|
-
`).length,s=Buffer.byteLength(t),i=
|
|
738
|
-
`)}let l=[`Indexed ${a.totalChunks} sections from "${
|
|
747
|
+
${c.stderr}`}],isError:!0})}if(c.exitCode!==0){let{isError:m,output:p}=ug({language:t,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return s&&s.trim().length>0&&Buffer.byteLength(p)>qu?(un(Buffer.byteLength(p)),K("ctx_execute",{content:[{type:"text",text:`${u}${Ss(p,s,m?`execute:${t}:error`:`execute:${t}`)}`}],isError:m})):Buffer.byteLength(p)>Vu?(un(Buffer.byteLength(p)),K("ctx_execute",{content:[{type:"text",text:`${u}${Ss(p,"errors failures exceptions",m?`execute:${t}:error`:`execute:${t}`)}`}],isError:m})):K("ctx_execute",{content:[{type:"text",text:`${u}${p}`}],isError:m})}let f=c.stdout||"(no output)";if(s&&s.trim().length>0&&Buffer.byteLength(f)>qu)return un(Buffer.byteLength(f)),K("ctx_execute",{content:[{type:"text",text:`${u}${Ss(f,s,`execute:${t}`)}`}]});if(Buffer.byteLength(f)>Vu){let m=TT(f,`execute:${t}`),p={...m,content:m.content.map((h,g)=>g===0&&h.type==="text"?{...h,text:`${u}${h.text}`}:h)};return K("ctx_execute",p)}return K("ctx_execute",{content:[{type:"text",text:`${u}${f}`}]})}catch(i){let a=i instanceof Error?i.message:String(i);return K("ctx_execute",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});function TT(t,e){let n=vn();un(Buffer.byteLength(t));let r=n.index({content:t,source:e,attribution:yr()});return{content:[{type:"text",text:`Indexed ${r.totalChunks} sections (${r.codeChunks} with code) from: ${r.label}
|
|
748
|
+
Use ctx_search(queries: ["..."]) to query this content. Use source: "${r.label}" to scope results.`}]}}var qu=5e3,Vu=102400;function Ss(t,e,n,r=5){let o=t.split(`
|
|
749
|
+
`).length,s=Buffer.byteLength(t),i=vn(),a=i.indexPlainText(t,n,void 0,yr()),c=i.searchWithFallback(e,r,n),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let d=[`Indexed ${a.totalChunks} sections from "${n}" into knowledge base.`,`No sections matched intent "${e}" in ${o}-line output (${(s/1024).toFixed(1)}KB).`];return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to explore the indexed content."),d.join(`
|
|
750
|
+
`)}let l=[`Indexed ${a.totalChunks} sections from "${n}" into knowledge base.`,`${c.length} sections matched "${e}" (${o} lines, ${(s/1024).toFixed(1)}KB):`,""];for(let d of c){let f=d.content.split(`
|
|
739
751
|
`)[0].slice(0,120);l.push(` - ${d.title}: ${f}`)}return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to retrieve full content of any section."),l.join(`
|
|
740
|
-
`)}
|
|
752
|
+
`)}Te.registerTool("ctx_execute_file",{title:"Execute File Processing",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Read a file into a sandboxed FILE_CONTENT variable and run code over it. Only what you console.log() enters your conversation \u2014 the file bytes stay in the sandbox.
|
|
741
753
|
|
|
742
754
|
Think-in-Code applied to file-level analysis: Reading the whole file means every byte enters your conversation memory and costs reasoning capacity for the rest of the session. Running code over it here lets you keep the raw bytes out and only the derived answer in. Same principle as ctx_execute, scoped to one named file via the FILE_CONTENT variable.
|
|
743
755
|
|
|
@@ -756,7 +768,7 @@ RETURNS:
|
|
|
756
768
|
Only what your code prints. The FILE_CONTENT variable holds the raw bytes inside the sandbox; nothing else leaves. When \`intent\` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout.
|
|
757
769
|
|
|
758
770
|
EXAMPLE: ctx_execute_file(path: "huge.log", language: "javascript", code: "const errs = FILE_CONTENT.split('\\\\n').filter(l => /ERROR|FATAL/.test(l)); console.log(\`\${errs.length} error lines\`); console.log(errs.slice(-5).join('\\\\n'))")
|
|
759
|
-
EXAMPLE: ctx_execute_file(path: "data.csv", language: "javascript", code: "const rows = FILE_CONTENT.split('\\\\n'); console.log(\`rows: \${rows.length - 1}, header: \${rows[0]}\`)")`,inputSchema
|
|
771
|
+
EXAMPLE: ctx_execute_file(path: "data.csv", language: "javascript", code: "const rows = FILE_CONTENT.split('\\\\n'); console.log(\`rows: \${rows.length - 1}, header: \${rows[0]}\`)")`,inputSchema:$.object({path:$.string().describe("Absolute file path or relative to project root"),language:$.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:$.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:$.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:$.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:n,timeout:r,intent:o})=>{let s=bg(t,"ctx_execute_file");if(s)return s;if(e==="shell"){let i=Tg(n,"execute_file");if(i)return i}else{let i=bT(n,e,"execute_file");if(i)return i}try{let i=Pg(r),a=await na.executeFile({path:t,language:e,code:n,timeout:i}),c=wT(e,n,t);if(a.timedOut)return K("ctx_execute_file",{content:[{type:"text",text:`${c}Timed out processing ${t} after ${i}ms`}],isError:!0});if(a.exitCode!==0){let{isError:l,output:d}=ug({language:e,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr});return o&&o.trim().length>0&&Buffer.byteLength(d)>qu?(un(Buffer.byteLength(d)),K("ctx_execute_file",{content:[{type:"text",text:`${c}${Ss(d,o,l?`file:${t}:error`:`file:${t}`)}`}],isError:l})):Buffer.byteLength(d)>Vu?(un(Buffer.byteLength(d)),K("ctx_execute_file",{content:[{type:"text",text:`${c}${Ss(d,"errors failures exceptions",l?`file:${t}:error`:`file:${t}`)}`}],isError:l})):K("ctx_execute_file",{content:[{type:"text",text:`${c}${d}`}],isError:l})}let u=a.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(u)>qu)return un(Buffer.byteLength(u)),K("ctx_execute_file",{content:[{type:"text",text:`${c}${Ss(u,o,`file:${t}`)}`}]});if(Buffer.byteLength(u)>Vu){let l=TT(u,`file:${t}`),d={...l,content:l.content.map((f,m)=>m===0&&f.type==="text"?{...f,text:`${c}${f.text}`}:f)};return K("ctx_execute_file",d)}return K("ctx_execute_file",{content:[{type:"text",text:`${c}${u}`}]})}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})}});Te.registerTool("ctx_index",{title:"Index Content",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},description:`Store content in a searchable knowledge base (BM25 over FTS5). Splits markdown by headings, keeps code blocks intact, and persists the raw chunks. The full content stays in storage \u2014 retrieve any section on-demand via ctx_search; nothing is summarized or truncated.
|
|
760
772
|
|
|
761
773
|
WHEN:
|
|
762
774
|
- Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
|
|
@@ -774,40 +786,40 @@ RETURNS:
|
|
|
774
786
|
Indexing metadata: chunk counts (total, code-bearing), source label, and the exact ctx_search call shape to query the indexed content. Raw content is NOT echoed back \u2014 it lives in storage, retrievable via ctx_search(source: "<label>"). When \`path\` is provided, a content hash is stored so ctx_search results auto-flag staleness on future calls.
|
|
775
787
|
|
|
776
788
|
EXAMPLE: ctx_index(content: "# React useEffect\\n\\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
|
|
777
|
-
EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema
|
|
778
|
-
Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)
|
|
779
|
-
Use ctx_search(queries: ["..."]) to query this content. Use source: "${f.label}" to scope results.`}]})}catch(l){let d=l instanceof Error?l.message:String(l);return
|
|
789
|
+
EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:$.object({content:$.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:$.string().optional().describe("File OR directory path to read and index (content never enters context). Provide this OR content. Directory paths trigger a bounded recursive walk (#687)."),source:$.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')"),include:$.array($.string()).optional().describe("Directory-only: glob patterns to include (default: all matching extensions)."),exclude:$.array($.string()).optional().describe("Directory-only: glob patterns to exclude. Merged with defaults (node_modules, .git, dist, build, .next, coverage, .venv, __pycache__, .DS_Store)."),maxDepth:$.number().int().min(0).optional().describe("Directory-only: max recursion depth from root (default: 5)."),maxFiles:$.number().int().min(1).optional().describe("Directory-only: hard cap on files indexed (default: 200) \u2014 FTS5 blow-up guard."),extensions:$.array($.string()).optional().describe("Directory-only: allowed file extensions (default: .md .mdx .txt .json .yaml .yml .ts .tsx .js .jsx .py .rs .go .sh)."),respectGitignore:$.boolean().optional().describe("Directory-only: apply nearest .gitignore (default: true)."),followSymlinks:$.boolean().optional().describe("Directory-only: follow directory symlinks (default: false \u2014 cycle hazard + escape risk).")})},async({content:t,path:e,source:n,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return K("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let l=bg(e,"ctx_index");if(l)return l}try{let l=e?kH(e):void 0;if(l&&ze(l)&&gT(l).isSymbolicLink()){let p;try{p=yT(l)}catch{return K("ctx_index",{content:[{type:"text",text:"Error: symlink target could not be resolved."}]})}if(p!==l){let h=bg(p,"ctx_index");if(h)return h}}if(l&&ze(l)&&hT(l).isDirectory()){let m=vn(),p=Ot(),h=bu("Read",p),g=process.platform==="win32",y=O=>{try{return vu(O,h,g,p).denied}catch{return!1}},_=m.indexDirectory({path:l,source:n??l,attribution:yr(),perFileDeny:y,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),S=_.capped?` (cap reached \u2014 only first ${_.filesIndexed} of ${_.totalSeen}+ files; raise maxFiles to index more)`:"",k=_.denied>0?` (${_.denied} file${_.denied===1?"":"s"} blocked by Read deny policy)`:"",v=_.failed>0?` (${_.failed} file${_.failed===1?"":"s"} failed to read)`:"";return K("ctx_index",{content:[{type:"text",text:`Indexed ${_.filesIndexed} file${_.filesIndexed===1?"":"s"} (${_.totalChunks} sections) from directory: ${_.label}${S}${k}${v}
|
|
790
|
+
Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)un(Buffer.byteLength(t));else if(l)try{let m=await import("fs");un(m.readFileSync(l).byteLength)}catch{}let f=vn().index({content:t,path:l,source:n??l,attribution:yr()});return K("ctx_index",{content:[{type:"text",text:`Indexed ${f.totalChunks} sections (${f.codeChunks} with code) from: ${f.label}
|
|
791
|
+
Use ctx_search(queries: ["..."]) to query this content. Use source: "${f.label}" to scope results.`}]})}catch(l){let d=l instanceof Error?l.message:String(l);return K("ctx_index",{content:[{type:"text",text:`Index error: ${d}`}],isError:!0})}});function Rg(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}var KH=Rg("CONTEXT_MODE_SEARCH_WINDOW_MS",6e4),vg=Rg("CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER",3),Hu=Rg("CONTEXT_MODE_SEARCH_BLOCK_AFTER",8),GH=new Tu({windowMs:KH,softCapAfter:vg,blockAfter:Hu});function JH(){try{return yr()?.sessionId??"__default__"}catch{return"__default__"}}function Cg(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function $g(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function XH(t){let e=Cg(t);return Array.isArray(e)?e.map((n,r)=>typeof n=="string"?{label:`cmd_${r+1}`,command:n}:n):e}Te.registerTool("ctx_search",{title:"Search Indexed Content",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},description:'Search a unified knowledge base with a multi-strategy ranking pipeline. Two parallel matchers run on every query: a Porter-stemming matcher ("caching" finds "cached", "caches", "cach") and a trigram-substring matcher ("useEff" finds "useEffect"). Their ranked lists are merged via Reciprocal Rank Fusion, so a document that ranks well in both surfaces above one that wins only on a single strategy. Multi-term queries get an additional proximity-rerank pass that boosts passages where the query terms appear close together. Typos are corrected via Levenshtein distance and re-searched. Result snippets are window-extracted around the matched terms, not blindly truncated.\n\nThe knowledge base is unified: queries reach indexed content you stored (ctx_index, ctx_fetch_and_index, ctx_batch_execute output) AND auto-captured session memory written by hooks (decisions, errors, blockers, plans, user prompts, rejected approaches, tool failures, compaction guides \u2014 26 event categories). File-backed sources carry a content hash and auto-flag staleness when the source file changes.\n\nWHEN:\n - You want to recall something that exists in storage (recently indexed content, prior session events, auto-memory) instead of re-reading raw sources\n - You have multiple related questions about the same body of knowledge \u2014 batch every question into one call (the ranking pipeline runs per-query but the round-trip cost is paid once)\n - You want to scope the query to one labelled source (pass `source` \u2014 partial match is fine)\n - You want a chronological view across current session + prior sessions + persistent auto-memory (pass `sort: "timeline"` \u2014 the default `relevance` mode only ranks within the current session)\n - You want to filter ranked results by content shape (pass `contentType: "code"` to surface implementation snippets or `contentType: "prose"` to surface explanations)\n\nWHEN NOT:\n - The data you want to query has never been stored in the knowledge base AND no session memory has accumulated around it \u2014 capture first (run a gather-and-index call), then come back here to query\n - You have one ad-hoc question against data that is not in the knowledge base \u2014 answer it inline by running code in the sandbox tool; one round-trip instead of capture-then-query\n\nRETURNS:\n Per-query ranked sections with window-extracted snippets. Use 2-4 specific technical terms per query. Common session-memory source labels: `decision` (user corrections / preferences), `error` and `error-resolution` (past failures + their fixes), `blocker`, `plan`, `user-prompt`, `rejected-approach`, `compaction` (post-compact session guide). See ctx_stats for live category counts. Each response carries a throttle counter (call #N/M in the rolling time window); results taper toward the soft cap and calls block after the hard cap. Tune via CONTEXT_MODE_SEARCH_WINDOW_MS, CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER, CONTEXT_MODE_SEARCH_BLOCK_AFTER.\n\nEXAMPLE: ctx_search(queries: ["root cause", "proposed fix", "test coverage"], source: "issue-#683")\nEXAMPLE: ctx_search(queries: ["what did we decide about caching"], source: "decision", sort: "timeline")\nEXAMPLE: ctx_search(queries: ["useEffect cleanup pattern"], source: "react-docs", contentType: "code", limit: 5)\nEXAMPLE: ctx_search(queries: ["last user prompt", "active skills", "open blockers"], sort: "timeline")',inputSchema:Uw(mg)},async t=>{try{let e=vn(),n=t.sort||"relevance";if(n!=="timeline"&&e.getStats().chunks===0)return K("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
|
|
780
792
|
|
|
781
793
|
ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
|
|
782
794
|
\u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
|
|
783
795
|
\u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
|
|
784
796
|
\u2022 ctx_index(content, source) \u2014 manually index text content
|
|
785
797
|
|
|
786
|
-
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let
|
|
798
|
+
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let r=t,o=[];if(Array.isArray(r.queries)&&r.queries.length>0?o.push(...r.queries):typeof r.query=="string"&&r.query.length>0&&o.push(r.query),o.length===0)return K("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a,project:c}=t,u=Fw(c,mg,()=>Ot()),l=Date.now(),d=GH.record(JH(),l),f=d.count;if(d.blocked)return K("ctx_search",{content:[{type:"text",text:`BLOCKED: ${f} search calls in ${Math.round((l-d.windowStart)/1e3)}s. You're flooding context. STOP making individual search calls. Use ctx_batch_execute(commands, queries) for your next research step.`}],isError:!0});let m=d.softCapped?1:Math.min(s,2),p=40*1024,h=0,g=[],y=null;if(n==="timeline"||typeof u=="string")try{let M=je(),D=Ot(),V=ji({projectDir:D,sessionsDir:M});ze(V)&&(y=new on({dbPath:V}))}catch{}let S;if(typeof u=="string"&&y)try{S=new Set(y.getSessionIdsForProject(u))}catch{}let k=cn?.getConfigDir()??Rt();try{for(let M of o){if(h>p){g.push(`## ${M}
|
|
787
799
|
(output cap reached)
|
|
788
|
-
`);continue}let
|
|
789
|
-
No results found.`);continue}let
|
|
790
|
-
${
|
|
800
|
+
`);continue}let D;if(n==="timeline"?D=Hw({query:M,limit:m,store:e,sort:n,source:i,contentType:a,sessionDB:y,projectDir:Ot(),configDir:k,adapter:cn??void 0,projectScope:u}):D=e.searchWithFallback(M,m,i,a,"like",S),D.length===0){g.push(`## ${M}
|
|
801
|
+
No results found.`);continue}let V=D.map((P,T)=>{let H=P.origin||"current-session",pe=P.timestamp?P.timestamp.slice(0,16).replace("T"," "):"",ft=`--- [${H}${pe?" | "+pe:""} | ${P.source}] ---`,En=`### ${P.title}`,Gu=vT(P.content,M,1500,P.highlighted);return`${ft}
|
|
802
|
+
${En}
|
|
791
803
|
|
|
792
|
-
${
|
|
804
|
+
${Gu}`}).join(`
|
|
793
805
|
|
|
794
|
-
`);
|
|
806
|
+
`);g.push(`## ${M}
|
|
795
807
|
|
|
796
|
-
${
|
|
808
|
+
${V}`),h+=V.length}}finally{try{y?.close()}catch{}}let v=g.join(`
|
|
797
809
|
|
|
798
810
|
---
|
|
799
811
|
|
|
800
|
-
`);e.lastRefreshCount>0&&(
|
|
812
|
+
`);e.lastRefreshCount>0&&(v=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
|
|
801
813
|
|
|
802
|
-
`+
|
|
814
|
+
`+v);let O=Math.max(0,Hu-f),R=Math.max(0,vg-f);if(f>=vg?v+=`
|
|
803
815
|
|
|
804
|
-
\u26A0 search call #${
|
|
816
|
+
\u26A0 search call #${f}/${Hu} in this window. Results limited to ${m}/query. ${O} call(s) remaining before block. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`:v+=`
|
|
805
817
|
|
|
806
|
-
> Throttle: call #${
|
|
807
|
-
Indexed sources: ${
|
|
818
|
+
> Throttle: call #${f}/${Hu} in this window. ${R} call(s) before soft cap. Prefer ctx_search(queries: [...]) array form for multi-query workloads \u2014 it counts as a single call.`,v.trim().length===0){let M=e.listSources(),D=M.length>0?`
|
|
819
|
+
Indexed sources: ${M.map(V=>`"${V.label}" (${V.chunkCount} sections)`).join(", ")}`:"";return K("ctx_search",{content:[{type:"text",text:`No results found.${D}`}]})}return K("ctx_search",{content:[{type:"text",text:v}]})}catch(e){let n=e instanceof Error?e.message:String(e);return K("ctx_search",{content:[{type:"text",text:`Search error: ${n}`}],isError:!0})}});var hg=null,gg=null;function YH(){return hg||(hg=pT(import.meta.url).resolve("turndown")),hg}function QH(){return gg||(gg=pT(import.meta.url).resolve("turndown-plugin-gfm")),gg}function eU(t,e){let n=JSON.stringify(YH()),r=JSON.stringify(QH()),o=JSON.stringify(e),s=Wu.toString(),i=Wu.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
|
|
808
820
|
var classifyIp = ${i};`,c=process.env.CTX_FETCH_STRICT==="1";return`
|
|
809
|
-
const TurndownService = require(${
|
|
810
|
-
const { gfm } = require(${
|
|
821
|
+
const TurndownService = require(${n});
|
|
822
|
+
const { gfm } = require(${r});
|
|
811
823
|
const fs = require('fs');
|
|
812
824
|
const dns = require('no' + 'de:dns');
|
|
813
825
|
const dnsPromises = require('no' + 'de:dns/promises');
|
|
@@ -1049,9 +1061,9 @@ async function main() {
|
|
|
1049
1061
|
emit('text', text);
|
|
1050
1062
|
}
|
|
1051
1063
|
main();
|
|
1052
|
-
`}var
|
|
1064
|
+
`}var tU=1440*60*1e3,lT=3072;function nU(t){if(t===0)return"0ms";let e=1440*60*1e3,n=3600*1e3,r=60*1e3;return t%e===0?`${t/e}d`:t%n===0?`${t/n}h`:t%r===0?`${t/r}m`:`${t}ms`}async function rU(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let n=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:r}=await import("node:dns/promises"),o=await r(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=Wu(s.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${s.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&n)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${s.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(r){let o=r?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=r instanceof Error?r.message:String(r),a=s?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`DNS lookup failed for "${e.hostname}": ${i}${a}`,reason:"exit"}}return null}function Wu(t){let e=t.indexOf("%"),n=e===-1?t:t.slice(0,e),r=n.toLowerCase();if(r.includes(":")){let a=r.match(/^::ffff:([\d.]+)$/);return a?Wu(a[1]):r==="::"||r.startsWith("fe8")||r.startsWith("fe9")||r.startsWith("fea")||r.startsWith("feb")||r.startsWith("ff")?"block":r==="::1"||r.startsWith("fc")||r.startsWith("fd")?"private":"public"}if(!n.includes("."))return"block";let o=n.split(".").map(a=>parseInt(a,10));if(o.length!==4||o.some(a=>isNaN(a)||a<0||a>255))return"block";let[s,i]=o;return s===169&&i===254||s===0||s>=224?"block":s===127||s===10||s===172&&i>=16&&i<=31||s===192&&i===168?"private":"public"}async function oU(t,e,n,r){let o=await rU(t);if(o)return o;if(!n&&r!==0){let i=vn(),a=Vm(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=r??tU;if(l<d){let f=Math.floor(l/36e5),m=Math.floor(l/(60*1e3)),p=f>0?`${f}h ago`:m>0?`${m}m ago`:"just now",h=c.chunkCount*1600;return{kind:"cached",label:c.label,chunkCount:c.chunkCount,estimatedBytes:h,ageStr:p,ttlStr:nU(d)}}}}let s=Et(Eg(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=eU(t,s),a=await na.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let l=a.stderr||a.stdout||"unknown error",f=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(l)?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`${l}${f}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{let d=hT(s).size;if(d>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${d} bytes exceeds cap 52428800`,reason:"read"};u=ta(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return u.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:u,header:c}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{mT(s)}catch{}}}function sU(t){let e=vn(),n=Vm(t.source,t.url),r=yr(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,n,void 0,r):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,n,void 0,r):o=e.index({content:t.markdown,source:n,attribution:r}),un(Buffer.byteLength(t.markdown));let s=t.markdown.length>lT?Cw(t.markdown,lT)+`
|
|
1053
1065
|
|
|
1054
|
-
\u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:o.label,totalChunks:o.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}
|
|
1066
|
+
\u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:o.label,totalChunks:o.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}Te.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},description:`Fetches URL content, converts HTML to markdown (JSON is chunked by key paths, plain text indexed directly), persists it in a searchable knowledge base, and returns a small preview window per source. The raw page bytes never enter your conversation \u2014 they live in storage and you retrieve any section on-demand via ctx_search.
|
|
1055
1067
|
|
|
1056
1068
|
Caching: every fetch is cached on disk and reused for repeat calls within the TTL window. The default TTL is 24 hours; override per-call with the \`ttl\` parameter (milliseconds, \`ttl: 0\` bypasses cache like \`force: true\`). Stored content older than 14 days is cleaned up on startup.
|
|
1057
1069
|
|
|
@@ -1071,15 +1083,15 @@ RETURNS:
|
|
|
1071
1083
|
EXAMPLE: ctx_fetch_and_index(
|
|
1072
1084
|
requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
|
|
1073
1085
|
concurrency: 5
|
|
1074
|
-
)`,inputSchema
|
|
1086
|
+
)`,inputSchema:$.object({url:$.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:$.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:$.preprocess(Cg,$.array($.object({url:$.string().describe("URL to fetch"),source:$.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:$.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:$.preprocess($g,$.boolean()).optional().describe("Skip cache and re-fetch even if content was recently indexed"),ttl:$.coerce.number().int().min(0).optional().describe("Override the cache freshness window for this call, in milliseconds. `ttl: 0` bypasses the cache like `force: true`; omit to use the default 24h TTL.")})},async({url:t,source:e,requests:n,concurrency:r,force:o,ttl:s})=>{let i=n||(t?[{url:t,source:e}]:[]);if(i.length===0)return 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 a=!n&&i.length===1,c=r??1,u=i.map(P=>({run:()=>oU(P.url,P.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:f}=await Dm(u,{concurrency:c,capByCpuCount:!a&&c>1}),m=[];for(let P=0;P<l.length;P++){let T=l[P];if(T.status==="rejected"){let pe=T.reason instanceof Error?T.reason.message:String(T.reason);m.push({kind:"job_error",url:i[P].url,error:pe});continue}let H=T.value;if(H.kind==="cached"){ne.cacheHits++,ne.cacheBytesSaved+=H.estimatedBytes;let pe=H.estimatedBytes,ft=H.label;setImmediate(()=>Aw({sessionDbPath:ea(),source:ft,bytesAvoided:pe})),m.push({kind:"cached",label:H.label,chunkCount:H.chunkCount,ageStr:H.ageStr,ttlStr:H.ttlStr})}else H.kind==="fetch_error"?m.push({kind:"fetch_error",url:H.url,error:H.error,reason:H.reason}):(ne.cacheMisses++,m.push({kind:"fetched",indexed:sU(H)}))}if(a){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: ${P.ttlStr}).
|
|
1075
1087
|
To refresh: call ctx_fetch_and_index again with \`force: true\`.
|
|
1076
1088
|
|
|
1077
1089
|
You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
|
|
1078
|
-
Use: ctx_search(queries: [...], source: "${
|
|
1079
|
-
`);return
|
|
1090
|
+
Use: ctx_search(queries: [...], source: "${P.label}")`}]});if(P.kind==="fetched"){let T=(P.indexed.totalBytes/1024).toFixed(1),H=[`Fetched and indexed **${P.indexed.totalChunks} sections** (${T}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(`
|
|
1091
|
+
`);return K("ctx_fetch_and_index",{content:[{type:"text",text:H}]})}if(P.kind==="fetch_error"){let T=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:T}],isError:!0})}return K("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${P.error}`}],isError:!0})}let p=384,h=[],g=0,y=0,_=0,S=0,k=0,v=[];for(let P of m)if(P.kind==="cached")_++,h.push(`- [cache] ${P.label} \u2014 ${P.chunkCount} sections (${P.ageStr}, TTL: ${P.ttlStr})`);else if(P.kind==="fetched"){S++,g+=P.indexed.totalChunks,y+=P.indexed.totalBytes;let T=(P.indexed.totalBytes/1024).toFixed(1);h.push(`- [new] ${P.indexed.label} \u2014 ${P.indexed.totalChunks} sections (${T}KB)`);let H=P.indexed.preview.length>p?P.indexed.preview.slice(0,p).trimEnd()+"\u2026":P.indexed.preview;v.push(`### ${P.indexed.label}
|
|
1080
1092
|
|
|
1081
|
-
${H}`)}else
|
|
1082
|
-
`);return
|
|
1093
|
+
${H}`)}else k++,h.push(`- [err] ${P.url}: ${P.error}`);let O=(y/1024).toFixed(1),R=f?` cap=${d}/${rH().length}cpu`:"",M=(P,T,H)=>`${P} ${P===1?T:H}`,V=[`fetched ${i.length} c=${d}${R}. ok=${S} cache=${_} err=${k}. ${M(g,"section","sections")} ${O}KB.`,"",...h,"",'ctx_search(queries: [...], source: "<label>") for full content.',...v.length>0?["","---","",...v]:[]].join(`
|
|
1094
|
+
`);return K("ctx_fetch_and_index",{content:[{type:"text",text:V}],isError:k===i.length})});Te.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run multiple commands in ONE call. Every command's output is auto-indexed into the knowledge base; if you also pass \`queries\`, the matching sections come back in the same round trip so a follow-up search call is not needed.
|
|
1083
1095
|
|
|
1084
1096
|
Concurrency parallelizes the FETCH phase (run-the-commands). The DERIVATION phase \u2014 turning raw output into an answer \u2014 still belongs in code: add a processing command that consumes the indexed output and prints only the answer, so the raw bytes never enter your conversation (Think-in-Code, same principle as the sandbox tool).
|
|
1085
1097
|
|
|
@@ -1104,14 +1116,14 @@ EXAMPLE: ctx_batch_execute(
|
|
|
1104
1116
|
],
|
|
1105
1117
|
queries: ["root cause", "proposed fix"],
|
|
1106
1118
|
concurrency: 2
|
|
1107
|
-
)`,inputSchema
|
|
1108
|
-
`),
|
|
1109
|
-
`).length;if(
|
|
1110
|
-
Searchable terms for follow-up: ${
|
|
1111
|
-
`);return
|
|
1112
|
-
`)}]})});
|
|
1113
|
-
`),
|
|
1114
|
-
`);return
|
|
1119
|
+
)`,inputSchema:$.object({commands:$.preprocess(XH,$.array($.object({label:$.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:$.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:$.preprocess(Cg,$.array($.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:$.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:$.coerce.number().int().min(1).max(8).optional().default(1).describe("Max commands to run in parallel (1-8, default: 1). Use 4-8 for I/O-bound batches (network, gh, curl, multi-repo git reads). Keep at 1 for CPU-bound (npm test, build, lint) or stateful commands (ports, locks). >1 switches to per-command timeouts (no shared budget) and individual `(timed out)` blocks instead of cascading skip."),cwd:$.string().optional().describe("Optional working directory for all shell commands in this batch."),query_scope:$.enum(["batch","global"]).optional().default("batch").describe("Scope for `queries` (default: `batch`). `batch` searches ONLY the chunks produced by this batch's commands \u2014 useful when you want answers about the just-fetched output. `global` searches the entire persistent index (same scope as ctx_search) \u2014 useful when you want the batch commands to enrich context and the queries to also surface related prior knowledge in one round trip.")})},async({commands:t,queries:e,timeout:n,concurrency:r,cwd:o,query_scope:s})=>{for(let i of t){let a=Tg(i.command,"batch_execute");if(a)return a}try{let i=BH(fo.shell,Ku),a=Pg(n),{outputs:c,timedOut:u}=await WH(t,{timeout:a,concurrency:r,nodeOptsPrefix:i,cwd:o,onFsBytes:R=>{ne.bytesSandboxed+=R}},na),l=c.join(`
|
|
1120
|
+
`),d=Buffer.byteLength(l),f=l.split(`
|
|
1121
|
+
`).length;if(u&&c.length===0)return K("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${a}ms. No output captured.`}],isError:!0});un(d);let m=vn(),p=`batch:${t.map(R=>R.label).join(",").slice(0,80)}`,h=m.index({content:l,source:p,attribution:yr()}),g=["## Commands",""];for(let R of t)g.push(`- ${R.label}: \`${ET(R.command)}\``);let y=m.getChunksBySource(h.sourceId),_=["## Indexed Sections",""],S=[];for(let R of y){let M=Buffer.byteLength(R.content);_.push(`- ${R.title} (${(M/1024).toFixed(1)}KB)`),S.push(R.title)}let k=UH(m,e,p,void 0,s),v=m.getDistinctiveTerms?m.getDistinctiveTerms(h.sourceId):[],O=[`Executed ${t.length} commands (${f} lines, ${(d/1024).toFixed(1)}KB). Indexed ${h.totalChunks} sections. Searched ${e.length} queries.`,"",...g,"",..._,"",...k,v.length>0?`
|
|
1122
|
+
Searchable terms for follow-up: ${v.join(", ")}`:""].join(`
|
|
1123
|
+
`);return K("ctx_batch_execute",{content:[{type:"text",text:O}]})}catch(i){let a=i instanceof Error?i.message:String(i);return K("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${a}`}],isError:!0})}});function yg(t,e){if(!ze(e))return;let n=0;try{for(let r of fT(e))if(!(!r.startsWith("stats-")||!r.endsWith(".json")))try{let o=JSON.parse(ta(Et(e,r),"utf-8"));n+=(o?.bytes_sandboxed??0)+(o?.bytes_indexed??0)}catch{}}catch{}if(n>0){let r=(t.rescueBytes??0)/4;t.totalEvents=Math.round((n/4+r)/256)}}function dT(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}Te.registerTool("ctx_stats",{title:"Session Statistics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:$.object({})},async()=>{let t;try{let e=Ot(),n=Qe(e),r=ji({projectDir:e,sessionsDir:je()});if(ze(r)){let o=Ye(),s=new o(r,{readonly:!0});try{let i=new ys(s),a=i.queryAll(ne),c=i.getMcpToolUsage(),u=Ji({sessionsDir:je()}),l;try{l=Au()}catch{}let d,f;try{let p=process.env.CLAUDE_SESSION_ID;if(p||(p=s.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),p){d=eT({sessionId:p,sessionsDir:je(),worktreeHash:n});let h=Zu(),g;try{let k=Ye(),v=(await import("node:fs")).readdirSync(je()).filter(R=>R.endsWith(".db")&&(!n||R.startsWith(n))),O;for(let R of v)try{let M=new k((await import("node:path")).join(je(),R),{readonly:!0});try{let D=M.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(p);if(D?.project_dir){O=D.project_dir;break}}finally{M.close()}}catch{}g=O?Xi({projectDir:O,sessionsDir:je(),worktreeHash:n,contentDbPath:h}):Xi({sessionId:p,sessionsDir:je(),worktreeHash:n,contentDbPath:h})}catch{g=Xi({sessionId:p,sessionsDir:je(),worktreeHash:n,contentDbPath:h})}let y=Xi({sessionsDir:je()}),_=tT(h),S={...y,contentBytes:y.contentBytes+_,bytesAvoided:y.bytesAvoided+_,totalSavedTokens:Math.floor((y.eventDataBytes+y.bytesAvoided+_+y.snapshotBytes)/4)};f={conversation:g,lifetime:S}}}catch{}cn?.name==="Pi"&&yg(u,je());let m;try{m=vn().getIndexState()}catch{}t=Nu(a,Zn,Bn,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:f,indexState:m,cwd:e})}finally{s.close()}}else{let s=new ys(dT()).queryAll(ne),i=Ji({sessionsDir:je()});cn?.name==="Pi"&&yg(i,je());let a;try{a=Au()}catch{}let c;try{c=vn().getIndexState()}catch{}t=Nu(s,Zn,Bn,{lifetime:i,multiAdapter:a,indexState:c})}}catch{let n=new ys(dT()).queryAll(ne),r;try{r=Ji({sessionsDir:je()})}catch{}cn?.name==="Pi"&&r&&yg(r,je());let o;try{o=Au()}catch{}t=Nu(n,Zn,Bn,r||o?{lifetime:r,multiAdapter:o}:void 0)}return K("ctx_stats",{content:[{type:"text",text:t}]})});Te.registerTool("ctx_doctor",{title:"Run Diagnostics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},description:"Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.",inputSchema:$.object({})},async()=>{let t=["context-mode doctor",""],e;try{e=vt(Te.server.getClientVersion()??void 0).platform}catch{e=vt().platform}let n=ST(e),r=11,o=(Lu.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${Lu.length}/${r} (${o}%) \u2014 ${Lu.join(", ")}`),qc()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let s=Mi(_s),i=Jm(_s),a=Xm(_s);t.push(`[OK] Storage sessions: ${s.path} (${Qc(s)})`),t.push(`[OK] Storage content: ${i.path} (${Qc(i)})`),t.push(`[OK] Storage stats: ${a.path} (${Qc(a)})`);{let u=new Ci({runtimes:fo});try{let l=await u.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(l.exitCode===0&&l.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let d=l.stderr?.trim()?` (${l.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${l.exitCode}${d}`)}}catch(l){t.push(`[FAIL] Server test: FAIL \u2014 ${l instanceof Error?l.message:l}`)}finally{u.cleanupBackgrounded()}}{let u;try{let l=Ye();u=new l(":memory:"),u.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),u.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let d=u.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();d&&d.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(l){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${l instanceof Error?l.message:l}`)}finally{try{u?.close()}catch{}}}let c=await SH();if(c){for(let l of c.validateHooks(n)){let d=l.status==="pass"?"[OK]":l.status==="warn"?"[WARN]":"[FAIL]",f=l.fix?` \u2014 fix: ${l.fix}`:"";t.push(`${d} ${l.check}: ${l.message}${f}`)}let u=Zw(c,n);u.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let l of u){let d=pt(n,l);ze(d)?t.push(`[OK] Hook script: PASS \u2014 ${d}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${d}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${Zn}`),K("ctx_doctor",{content:[{type:"text",text:t.join(`
|
|
1124
|
+
`)}]})});Te.registerTool("ctx_upgrade",{title:"Upgrade Plugin",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:$.object({})},async()=>{let t="",e,n;try{let c=Te.server.getClientVersion(),u=vt(c??void 0);n=u.platform,t=` --platform ${u.platform}`,e=Fc(u.platform)&&fo.javascript?{platform:u.platform,jsRuntime:fo.javascript}:void 0}catch{try{n=vt().platform}catch{}}let r=ST(n),o=pt(r,"cli.bundle.mjs"),s=pt(r,"build","cli.js");try{let c=je(),u=Et(bs(c),"insight-cache");ze(u)&&(cU(4747),mT(u,{recursive:!0,force:!0}))}catch{}let i;if(ze(o))i=`${Pi(o,e)} upgrade${t}`;else if(ze(s))i=`${Pi(s,e)} upgrade${t}`;else{let u=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync,lstatSync}from"node:fs";','import{join,resolve,sep}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(r)};`,'const T=mkdtempSync(join(tmpdir(),"ctx-upgrade-"));',"try{",'console.log("- [x] Starting inline upgrade (no CLI found)");','execFileSync("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",T],{stdio:"inherit"});','console.log("- [x] Cloned latest source");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["run","build"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Built from source");','const pkg=JSON.parse(readFileSync(join(T,"package.json"),"utf8"));','const items=[...(Array.isArray(pkg.files)?pkg.files:[]),"src","package.json"];',"const PW=resolve(P)+sep;const TW=resolve(T)+sep;","const noSymlink=(src)=>{try{return !lstatSync(src).isSymbolicLink()}catch{return false}};","for(const item of items){const from=resolve(T,item);const to=resolve(P,item);if(!(to+sep).startsWith(PW))continue;if(!(from+sep).startsWith(TW))continue;if(!noSymlink(from))continue;if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true,filter:noSymlink});}}",'console.log("- [x] Copied package files");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install","--production"],{cwd:P,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Installed production dependencies");','console.log("## context-mode upgrade complete");',"}catch(e){",'console.error("- [ ] Upgrade failed:",e.message);',"process.exit(1);","}finally{","try{rmSync(T,{recursive:true,force:true})}catch{}","}"].join(`
|
|
1125
|
+
`),l=pt(r,".ctx-upgrade-inline.mjs"),{writeFileSync:d}=await import("node:fs");d(l,u),i=Pi(l,e)}let a=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",i,"```","","After the command completes, display results as a markdown checklist:","- `[x]` for success, `[ ]` for failure","- Example format:"," ```"," ## context-mode upgrade"," - [x] Pulled latest from GitHub"," - [x] Built and installed v0.9.24"," - [x] npm global updated"," - [x] Hooks configured"," - [x] Doctor: all checks PASS"," ```","- Tell the user to restart their session to pick up the new version."].join(`
|
|
1126
|
+
`);return K("ctx_upgrade",{content:[{type:"text",text:a}]})});Te.registerTool("ctx_purge",{title:"Purge Knowledge Base",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},description:`DESTRUCTIVE: permanently delete indexed content. Cannot be undone. Requires confirm:true and exactly one scope.
|
|
1115
1127
|
|
|
1116
1128
|
WHEN:
|
|
1117
1129
|
- User explicitly asks to clear a specific session ('purge this session', 'wipe this conversation')
|
|
@@ -1135,14 +1147,7 @@ RETURNS:
|
|
|
1135
1147
|
A summary of removed rows + the resolved scope.
|
|
1136
1148
|
|
|
1137
1149
|
EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
|
|
1138
|
-
EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
- Or use a different port: ctx_insight({ port: ${s+1} })`}]})}let k=`http://localhost:${s}`,R=xw(k),$=R.ok?"":` (auto-open failed: ${R.reason}; navigate manually)`;return h.push(`Dashboard running at ${k}${$}`),Z("ctx_insight",{content:[{type:"text",text:h.map(C=>`- ${C}`).join(`
|
|
1143
|
-
`)+`
|
|
1144
|
-
|
|
1145
|
-
Open: ${k}
|
|
1146
|
-
PID: ${S.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${S.pid} /F`:`kill ${S.pid}`}`}]})}catch(h){let p=h instanceof Error?h.message:String(h);return Z("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${p}`}]})}});async function z1(){let t=Rm();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?eg():"/tmp",r=ke(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{Ji.cleanupBackgrounded(),ir&&ir.close();try{ys(Au)}catch{}try{ys(r)}catch{}if(Ur&&Ur.pid&&!Ur.killed)try{Ur.kill("SIGTERM")}catch{}},o=async()=>{try{Xh=0,$u()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),NE({onShutdown:()=>o()});let s=new Nc;await De.connect(s);try{Qh(r,String(process.pid))}catch{}try{let{detectPlatform:i,getAdapter:a}=await Promise.resolve().then(()=>(co(),cu)),c=De.server.getClientVersion(),u=i(c??void 0);ar=await a(u.platform),c&&console.error(`MCP client: ${c.name} v${c.version} \u2192 ${u.platform}`)}catch{}try{let i=FE(Ki());if(i){for(let[a,c]of Object.entries(i.calls))te.calls[a]=c;for(let[a,c]of Object.entries(i.bytesReturned))te.bytesReturned[a]=c;i.sessionStart>0&&(te.sessionStart=i.sessionStart)}}catch{}dw().then(i=>{i!=="unknown"&&(Zr=i)}),setInterval(()=>{dw().then(i=>{i!=="unknown"&&(Zr=i)})},3600*1e3).unref(),setInterval(()=>$u(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${Fr} running on stdio`),console.error(`Detected runtimes:
|
|
1147
|
-
${lb(uo)}`),Hc()||(console.error(`
|
|
1148
|
-
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&z1().catch(t=>{console.error("Fatal:",t),process.exit(1)});export{UL as REGISTERED_CTX_TOOLS,kK as __resetSuppressionDiagnosticForTests,j1 as browserOpenArgv,E1 as buildBatchNodeOptionsPrefix,O1 as buildFetchCode,Iu as classifyIp,lo as currentAttribution,WL as emitSuppressionDiagnostic,Rw as extractSnippet,v1 as formatBatchQueryResults,$t as getProjectDir,Iw as killProcessOnPort,xw as openBrowserSync,S1 as positionsFromHighlight,KL as registerEmptyToolsListHandler,XL as resolveSessionIdFromSessionDB,T1 as runBatchCommands,De as server,FL as shouldSuppressMcpToolsForNativePluginHost,EK as withProjectDirOverride};
|
|
1150
|
+
EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:$.object({confirm:$.preprocess($g,$.boolean()).describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:$.string().optional().describe("UUID of a single session. Pairs with confirm:true to wipe only that session's events + per-session FTS5 chunks. Sibling sessions and the stats file are preserved. MUST NOT be combined with scope:'project'."),scope:$.enum(["session","project"]).optional().describe("Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.")})},async({confirm:t,sessionId:e,scope:n})=>{if(e&&n==="project")return K("ctx_purge",{content:[{type:"text",text:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe."}],isError:!0});if(!t)return K("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let r=n??(e?"session":"project");!n&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let o;try{o=Zu()}catch{}if(an){try{an.cleanup()}catch{}an=null}let s=o?bs(o):void 0,{deleted:i}=$w({projectDir:Ot(),sessionsDir:je(),storePath:o,contentDir:s,legacyContentDir:Et(ks(),".context-mode","content"),contentHash:jn(Ot()),scope:r,sessionId:e});if(r==="project"){ne.calls={},ne.bytesReturned={},ne.bytesIndexed=0,ne.bytesSandboxed=0,ne.cacheHits=0,ne.cacheBytesSaved=0,ne.sessionStart=Date.now(),i.push("session stats");try{let c=kT();ze(c)&&xs(c)}catch{}}let a=r==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return K("ctx_purge",{content:[{type:"text",text:a}]})});var Qi=5e3;function iU(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 aU(t,e=process.platform,n=Fu){let r=iU(t,e),o=[];for(let{cmd:s,args:i}of r)try{let a=n(s,i,{stdio:"ignore",timeout:Qi});if(!a.error&&a.status===0)return{ok:!0,method:s};let c=a.error?.message??`status=${a.status===null?"signaled":a.status}`;o.push(`${s}: ${c}`)}catch(a){o.push(`${s}: ${a instanceof Error?a.message:String(a)}`)}return{ok:!1,method:"none",reason:o.join("; ")}}function cU(t,e=process.platform,n=Fu){let r={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return r.errors.push(`invalid port: ${t}`),r;try{if(e==="win32"){let o=n("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Qi});if(o.error)return r.errors.push(`netstat: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;let s=`:${t}`,i=new Set;for(let a of o.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let l=u[0],d=u[1],f=u[2],m=u[u.length-1];l==="TCP"&&d.endsWith(s)&&(f!=="0.0.0.0:0"&&f!=="[::]:0"||/^\d+$/.test(m)&&i.add(m))}for(let a of i){r.attemptedPids.push(a);try{let c=n("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:Qi});c.error||c.status!==0?r.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):r.killedPids.push(a)}catch(c){r.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=n("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Qi});if(o.error)return r.errors.push(`lsof: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){r.attemptedPids.push(i);try{let a=n("kill",[i],{stdio:"ignore",timeout:Qi});a.error||a.status!==0?r.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):r.killedPids.push(i)}catch(a){r.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){r.errors.push(o instanceof Error?o.message:String(o))}return r}var _g="https://context-mode.com/insight";Te.registerTool("ctx_insight",{title:"Open Insight Dashboard",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},description:"Opens the context-mode Insight dashboard (https://context-mode.com/insight) in your default browser \u2014 a dashboard launcher for the hosted analytics layer, not a Q&A engine. Insight surfaces per-engineer productive rate, retry waste, blocker detection, and role-narrowed views for CTO, EM, IC, CISO, FinOps, and DevOps. For natural-language queries over your indexed content, use ctx_search.",inputSchema:$.object({})},async()=>{let t=aU(_g),e=t.ok?`Opening Insight in your browser: ${_g}`:`Could not auto-open your browser (${t.reason}).
|
|
1151
|
+
Open Insight manually: ${_g}`;return K("ctx_insight",{content:[{type:"text",text:e}]})});async function uU(){let t=Bm();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?Eg():"/tmp",n=Et(e,`context-mode-mcp-ready-${process.pid}`),r,o=()=>{na.cleanupBackgrounded(),an&&an.close();try{xs(Ku)}catch{}try{xs(n)}catch{}r&&clearInterval(r)},s=async()=>{try{kg=0,Bu()}catch{}o(),process.exit(0)};process.on("exit",o),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),Rw({onShutdown:()=>s()});let i=new Hc;await Te.connect(i);try{Uu(n,String(process.pid))}catch{}r=setInterval(()=>{try{Uu(n,String(process.pid))}catch{}},3e4),r.unref();try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(fs(),rg)),u=Te.server.getClientVersion(),l=a(u??void 0);cn=await c(l.platform),u&&console.error(`MCP client: ${u.name} v${u.version} \u2192 ${l.platform}`)}catch{}try{let a=Mw(ea());if(a){for(let[c,u]of Object.entries(a.calls))ne.calls[c]=u;for(let[c,u]of Object.entries(a.bytesReturned))ne.bytesReturned[c]=u;a.sessionStart>0&&(ne.sessionStart=a.sessionStart)}}catch{}oT().then(a=>{a!=="unknown"&&(Bn=a)}),setInterval(()=>{oT().then(a=>{a!=="unknown"&&(Bn=a)})},3600*1e3).unref(),setInterval(()=>Bu(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${Zn} running on stdio`),console.error(`Detected runtimes:
|
|
1152
|
+
${Mb(fo)}`),qc()||(console.error(`
|
|
1153
|
+
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}gH();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&uU().catch(t=>{console.error("Fatal:",t),process.exit(1)});export{qH as AGY_DEFAULT_EXEC_TIMEOUT_MS,aH as REGISTERED_CTX_TOOLS,g3 as __resetSuppressionDiagnosticForTests,iU as browserOpenArgv,BH as buildBatchNodeOptionsPrefix,eU as buildFetchCode,Wu as classifyIp,yr as currentAttribution,pH as emitSuppressionDiagnostic,vT as extractSnippet,UH as formatBatchQueryResults,Ot as getProjectDir,gH as installStrictClientSchemaCompat,cU as killProcessOnPort,aU as openBrowserSync,HH as positionsFromHighlight,fH as registerEmptyToolsListHandler,Pg as resolveExecTimeout,yH as resolveSessionIdFromSessionDB,WH as runBatchCommands,xg as sanitizeSchemaForStrictClients,Te as server,cH as shouldSuppressMcpToolsForNativePluginHost,y3 as withProjectDirOverride};
|