dsh-context-mode 0.1.3 → 0.2.0
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/LICENSING.md +37 -0
- package/README.md +39 -13
- package/lib/types/cjk.d.ts +54 -0
- package/lib/types/cjk.d.ts.map +1 -0
- package/lib/types/cjk.js +64 -0
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/index.js +65 -21
- package/lib/types/output-containment.d.ts +35 -0
- package/lib/types/output-containment.d.ts.map +1 -0
- package/lib/types/output-containment.js +103 -0
- package/lib/types/routing.d.ts +3 -1
- package/lib/types/routing.d.ts.map +1 -1
- package/lib/types/routing.js +81 -6
- package/package.json +9 -5
- package/skills/context-mode/SKILL.md +104 -11
- package/vendor/context-mode/LICENSE +94 -0
- package/vendor/context-mode/server.bundle.mjs +1126 -0
- package/vendor/context-mode/src/cli.ts +2040 -0
- package/vendor/context-mode/src/db-base.ts +617 -0
- package/vendor/context-mode/src/executor.ts +785 -0
- package/vendor/context-mode/src/exit-classify.ts +33 -0
- package/vendor/context-mode/src/fetch-cache.ts +15 -0
- package/vendor/context-mode/src/lifecycle.ts +305 -0
- package/vendor/context-mode/src/platform/client-map.ts +45 -0
- package/vendor/context-mode/src/platform/detect.ts +645 -0
- package/vendor/context-mode/src/platform/dsh.ts +206 -0
- package/vendor/context-mode/src/platform/types.ts +503 -0
- package/vendor/context-mode/src/runPool.ts +81 -0
- package/vendor/context-mode/src/runtime.ts +765 -0
- package/vendor/context-mode/src/search/auto-memory.ts +200 -0
- package/vendor/context-mode/src/search/ctx-search-schema.ts +143 -0
- package/vendor/context-mode/src/search/flood-guard.ts +111 -0
- package/vendor/context-mode/src/search/unified.ts +176 -0
- package/vendor/context-mode/src/security.ts +889 -0
- package/vendor/context-mode/src/server.ts +4991 -0
- package/vendor/context-mode/src/session/analytics.ts +3085 -0
- package/vendor/context-mode/src/session/db.ts +1726 -0
- package/vendor/context-mode/src/session/error-classifier.ts +392 -0
- package/vendor/context-mode/src/session/event-emit.ts +132 -0
- package/vendor/context-mode/src/session/extract.ts +2958 -0
- package/vendor/context-mode/src/session/index.ts +130 -0
- package/vendor/context-mode/src/session/model-prices.json +429 -0
- package/vendor/context-mode/src/session/persist-tool-calls.ts +128 -0
- package/vendor/context-mode/src/session/pricing.ts +191 -0
- package/vendor/context-mode/src/session/project-attribution.ts +309 -0
- package/vendor/context-mode/src/session/purge.ts +338 -0
- package/vendor/context-mode/src/session/retrieval-marker.ts +65 -0
- package/vendor/context-mode/src/session/snapshot.ts +577 -0
- package/vendor/context-mode/src/store-directory.ts +290 -0
- package/vendor/context-mode/src/store.ts +2071 -0
- package/vendor/context-mode/src/truncate.ts +154 -0
- package/vendor/context-mode/src/types.ts +147 -0
- package/vendor/context-mode/src/util/claude-config.ts +95 -0
- package/vendor/context-mode/src/util/hook-config.ts +78 -0
- package/vendor/context-mode/src/util/jsonc.ts +70 -0
- package/vendor/context-mode/src/util/plugin-cache-integrity.ts +167 -0
- package/vendor/context-mode/src/util/project-dir.ts +347 -0
- package/vendor/context-mode/src/util/sibling-mcp.ts +228 -0
|
@@ -0,0 +1,1126 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var QS=Object.create;var Dc=Object.defineProperty;var e0=Object.getOwnPropertyDescriptor;var t0=Object.getOwnPropertyNames;var r0=Object.getPrototypeOf,n0=Object.prototype.hasOwnProperty;var zc=(t,e)=>()=>(t&&(e=t(t=0)),e);var O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),As=(t,e)=>{for(var r in e)Dc(t,r,{get:e[r],enumerable:!0})},s0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of t0(e))!n0.call(t,s)&&s!==r&&Dc(t,s,{get:()=>e[s],enumerable:!(n=e0(e,s))||n.enumerable});return t};var Pm=(t,e,r)=>(r=t!=null?QS(r0(t)):{},s0(e||!t||!t.__esModule?Dc(r,"default",{value:t,enumerable:!0}):r,t));var lo=O(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.regexpCode=le.getEsmExportName=le.getProperty=le.safeStringify=le.stringify=le.strConcat=le.addCodeArg=le.str=le._=le.nil=le._Code=le.Name=le.IDENTIFIER=le._CodeOrName=void 0;var co=class{};le._CodeOrName=co;le.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var hn=class extends co{constructor(e){if(super(),!le.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}}};le.Name=hn;var kt=class extends co{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),{})}};le._Code=kt;le.nil=new kt("");function ky(t,...e){let r=[t[0]],n=0;for(;n<e.length;)_d(r,e[n]),r.push(t[++n]);return new kt(r)}le._=ky;var yd=new kt("+");function Ty(t,...e){let r=[uo(t[0])],n=0;for(;n<e.length;)r.push(yd),_d(r,e[n]),r.push(yd,uo(t[++n]));return r$(r),new kt(r)}le.str=Ty;function _d(t,e){e instanceof kt?t.push(...e._items):e instanceof hn?t.push(e):t.push(o$(e))}le.addCodeArg=_d;function r$(t){let e=1;for(;e<t.length-1;){if(t[e]===yd){let r=n$(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function n$(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 s$(t,e){return e.emptyStr()?t:t.emptyStr()?e:Ty`${t}${e}`}le.strConcat=s$;function o$(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:uo(Array.isArray(t)?t.join(","):t)}function i$(t){return new kt(uo(t))}le.stringify=i$;function uo(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}le.safeStringify=uo;function a$(t){return typeof t=="string"&&le.IDENTIFIER.test(t)?new kt(`.${t}`):ky`[${t}]`}le.getProperty=a$;function c$(t){if(typeof t=="string"&&le.IDENTIFIER.test(t))return new kt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}le.getEsmExportName=c$;function u$(t){return new kt(t.toString())}le.regexpCode=u$});var xd=O(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.ValueScope=ut.ValueScopeName=ut.Scope=ut.varKinds=ut.UsedValueState=void 0;var ct=lo(),bd=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ra;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ra||(ut.UsedValueState=ra={}));ut.varKinds={const:new ct.Name("const"),let:new ct.Name("let"),var:new ct.Name("var")};var na=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof ct.Name?e:this.name(e)}name(e){return new ct.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}}};ut.Scope=na;var sa=class extends ct.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,ct._)`.${new ct.Name(r)}[${n}]`}};ut.ValueScopeName=sa;var l$=(0,ct._)`\n`,vd=class extends na{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?l$:ct.nil}}get(){return this._scope}name(e){return new sa(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let l=a.get(i);if(l)return l}else a=this._values[o]=new Map;a.set(i,s);let c=this._scope[o]||(this._scope[o]=[]),u=c.length;return c[u]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,ct._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=ct.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,ra.Started);let l=r(u);if(l){let d=this.opts.es5?ut.varKinds.var:ut.varKinds.const;o=(0,ct._)`${o}${d} ${u} = ${l};${this.opts._n}`}else if(l=s?.(u))o=(0,ct._)`${o}${l}${this.opts._n}`;else throw new bd(u);c.set(u,ra.Completed)})}return o}};ut.ValueScope=vd});var Q=O(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 ae=lo(),zt=xd(),Cr=lo();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return Cr._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return Cr.str}});Object.defineProperty(ee,"strConcat",{enumerable:!0,get:function(){return Cr.strConcat}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return Cr.nil}});Object.defineProperty(ee,"getProperty",{enumerable:!0,get:function(){return Cr.getProperty}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return Cr.stringify}});Object.defineProperty(ee,"regexpCode",{enumerable:!0,get:function(){return Cr.regexpCode}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return Cr.Name}});var ca=xd();Object.defineProperty(ee,"Scope",{enumerable:!0,get:function(){return ca.Scope}});Object.defineProperty(ee,"ValueScope",{enumerable:!0,get:function(){return ca.ValueScope}});Object.defineProperty(ee,"ValueScopeName",{enumerable:!0,get:function(){return ca.ValueScopeName}});Object.defineProperty(ee,"varKinds",{enumerable:!0,get:function(){return ca.varKinds}});ee.operators={GT:new ae._Code(">"),GTE:new ae._Code(">="),LT:new ae._Code("<"),LTE:new ae._Code("<="),EQ:new ae._Code("==="),NEQ:new ae._Code("!=="),NOT:new ae._Code("!"),OR:new ae._Code("||"),AND:new ae._Code("&&"),ADD:new ae._Code("+")};var pr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Sd=class extends pr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?zt.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=rs(this.rhs,e,r)),this}get names(){return this.rhs instanceof ae._CodeOrName?this.rhs.names:{}}},oa=class extends pr{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 ae.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=rs(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ae.Name?{}:{...this.lhs.names};return aa(e,this.rhs)}},wd=class extends oa{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ed=class extends pr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},kd=class extends pr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Td=class extends pr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},$d=class extends pr{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=rs(this.code,e,r),this}get names(){return this.code instanceof ae._CodeOrName?this.code.names:{}}},po=class extends pr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(d$(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>_n(e,r.names),{})}},fr=class extends po{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Rd=class extends po{},ts=class extends fr{};ts.kind="else";var gn=class t extends fr{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 ts(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t($y(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=rs(this.condition,e,r),this}get names(){let e=super.names;return aa(e,this.condition),this.else&&_n(e,this.else.names),e}};gn.kind="if";var yn=class extends fr{};yn.kind="for";var Pd=class extends yn{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=rs(this.iteration,e,r),this}get names(){return _n(super.names,this.iteration.names)}},Cd=class extends yn{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?zt.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=aa(super.names,this.from);return aa(e,this.to)}},ia=class extends yn{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=rs(this.iterable,e,r),this}get names(){return _n(super.names,this.iterable.names)}},fo=class extends fr{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)}};fo.kind="func";var mo=class extends po{render(e){return"return "+super.render(e)}};mo.kind="return";var Id=class extends fr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&_n(e,this.catch.names),this.finally&&_n(e,this.finally.names),e}},ho=class extends fr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ho.kind="catch";var go=class extends fr{render(e){return"finally"+super.render(e)}};go.kind="finally";var Od=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
3
|
+
`:""},this._extScope=e,this._scope=new zt.Scope({parent:e}),this._nodes=[new Rd]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new Sd(e,o,n)),o}const(e,r,n){return this._def(zt.varKinds.const,e,r,n)}let(e,r,n){return this._def(zt.varKinds.let,e,r,n)}var(e,r,n){return this._def(zt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new oa(e,r,n))}add(e,r){return this._leafNode(new wd(e,ee.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ae.nil&&this._leafNode(new $d(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,ae.addCodeArg)(r,s));return r.push("}"),new ae._Code(r)}if(e,r,n){if(this._blockNode(new gn(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 gn(e))}else(){return this._elseNode(new ts)}endIf(){return this._endBlockNode(gn,ts)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Pd(e),r)}forRange(e,r,n,s,o=this.opts.es5?zt.varKinds.var:zt.varKinds.let){let i=this._scope.toName(e);return this._for(new Cd(o,i,r,n),()=>s(i))}forOf(e,r,n,s=zt.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ae.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ae._)`${i}.length`,a=>{this.var(o,(0,ae._)`${i}[${a}]`),n(o)})}return this._for(new ia("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?zt.varKinds.var:zt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ae._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new ia("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(yn)}label(e){return this._leafNode(new Ed(e))}break(e){return this._leafNode(new kd(e))}return(e){let r=new mo;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(mo)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Id;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new ho(o),r(o)}return n&&(this._currNode=s.finally=new go,this.code(n)),this._endBlockNode(ho,go)}throw(e){return this._leafNode(new Td(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=ae.nil,n,s){return this._blockNode(new fo(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(fo)}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 gn))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=Od;function _n(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function aa(t,e){return e instanceof ae._CodeOrName?_n(t,e.names):t}function rs(t,e,r){if(t instanceof ae.Name)return n(t);if(!s(t))return t;return new ae._Code(t._items.reduce((o,i)=>(i instanceof ae.Name&&(i=n(i)),i instanceof ae._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof ae._Code&&o._items.some(i=>i instanceof ae.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function d$(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function $y(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ae._)`!${Ad(t)}`}ee.not=$y;var p$=Ry(ee.operators.AND);function f$(...t){return t.reduce(p$)}ee.and=f$;var m$=Ry(ee.operators.OR);function h$(...t){return t.reduce(m$)}ee.or=h$;function Ry(t){return(e,r)=>e===ae.nil?r:r===ae.nil?e:(0,ae._)`${Ad(e)} ${t} ${Ad(r)}`}function Ad(t){return t instanceof ae.Name?t:(0,ae._)`(${t})`}});var ce=O(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 he=Q(),g$=lo();function y$(t){let e={};for(let r of t)e[r]=!0;return e}re.toHash=y$;function _$(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Iy(t,e),!Oy(e,t.self.RULES.all))}re.alwaysValidSchema=_$;function Iy(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||Dy(t,`unknown keyword: "${o}"`)}re.checkUnknownRules=Iy;function Oy(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}re.schemaHasRules=Oy;function b$(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=b$;function v$({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,he._)`${r}`}return(0,he._)`${t}${e}${(0,he.getProperty)(n)}`}re.schemaRefOrVal=v$;function x$(t){return Ay(decodeURIComponent(t))}re.unescapeFragment=x$;function S$(t){return encodeURIComponent(Dd(t))}re.escapeFragment=S$;function Dd(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=Dd;function Ay(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=Ay;function w$(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}re.eachItem=w$;function Py({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof he.Name?(o instanceof he.Name?t(s,o,i):e(s,o,i),i):o instanceof he.Name?(e(s,i,o),o):r(o,i);return a===he.Name&&!(c instanceof he.Name)?n(s,c):c}}re.mergeEvaluated={props:Py({mergeNames:(t,e,r)=>t.if((0,he._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,he._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,he._)`${r} || {}`).code((0,he._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,he._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,he._)`${r} || {}`),zd(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Ny}),items:Py({mergeNames:(t,e,r)=>t.if((0,he._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,he._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,he._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,he._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Ny(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,he._)`{}`);return e!==void 0&&zd(t,r,e),r}re.evaluatedPropsToName=Ny;function zd(t,e,r){Object.keys(r).forEach(n=>t.assign((0,he._)`${e}${(0,he.getProperty)(n)}`,!0))}re.setEvaluated=zd;var Cy={};function E$(t,e){return t.scopeValue("func",{ref:e,code:Cy[e.code]||(Cy[e.code]=new g$._Code(e.code))})}re.useFunc=E$;var Nd;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Nd||(re.Type=Nd={}));function k$(t,e,r){if(t instanceof he.Name){let n=e===Nd.Num;return r?n?(0,he._)`"[" + ${t} + "]"`:(0,he._)`"['" + ${t} + "']"`:n?(0,he._)`"/" + ${t}`:(0,he._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,he.getProperty)(t).toString():"/"+Dd(t)}re.getErrorPath=k$;function Dy(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=Dy});var mr=O(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var Ge=Q(),T$={data:new Ge.Name("data"),valCxt:new Ge.Name("valCxt"),instancePath:new Ge.Name("instancePath"),parentData:new Ge.Name("parentData"),parentDataProperty:new Ge.Name("parentDataProperty"),rootData:new Ge.Name("rootData"),dynamicAnchors:new Ge.Name("dynamicAnchors"),vErrors:new Ge.Name("vErrors"),errors:new Ge.Name("errors"),this:new Ge.Name("this"),self:new Ge.Name("self"),scope:new Ge.Name("scope"),json:new Ge.Name("json"),jsonPos:new Ge.Name("jsonPos"),jsonLen:new Ge.Name("jsonLen"),jsonPart:new Ge.Name("jsonPart")};Md.default=T$});var yo=O(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.extendErrors=Je.resetErrorsCount=Je.reportExtraError=Je.reportError=Je.keyword$DataError=Je.keywordError=void 0;var ue=Q(),ua=ce(),et=mr();Je.keywordError={message:({keyword:t})=>(0,ue.str)`must pass "${t}" keyword validation`};Je.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ue.str)`"${t}" keyword must be ${e} ($data)`:(0,ue.str)`"${t}" keyword is invalid ($data)`};function $$(t,e=Je.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=Ly(t,e,r);n??(i||a)?zy(o,c):My(s,(0,ue._)`[${c}]`)}Je.reportError=$$;function R$(t,e=Je.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=Ly(t,e,r);zy(s,a),o||i||My(n,et.default.vErrors)}Je.reportExtraError=R$;function P$(t,e){t.assign(et.default.errors,e),t.if((0,ue._)`${et.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ue._)`${et.default.vErrors}.length`,e),()=>t.assign(et.default.vErrors,null)))}Je.resetErrorsCount=P$;function C$({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,et.default.errors,a=>{t.const(i,(0,ue._)`${et.default.vErrors}[${a}]`),t.if((0,ue._)`${i}.instancePath === undefined`,()=>t.assign((0,ue._)`${i}.instancePath`,(0,ue.strConcat)(et.default.instancePath,o.errorPath))),t.assign((0,ue._)`${i}.schemaPath`,(0,ue.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,ue._)`${i}.schema`,r),t.assign((0,ue._)`${i}.data`,n))})}Je.extendErrors=C$;function zy(t,e){let r=t.const("err",e);t.if((0,ue._)`${et.default.vErrors} === null`,()=>t.assign(et.default.vErrors,(0,ue._)`[${r}]`),(0,ue._)`${et.default.vErrors}.push(${r})`),t.code((0,ue._)`${et.default.errors}++`)}function My(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,ue._)`new ${t.ValidationError}(${e})`):(r.assign((0,ue._)`${n}.errors`,e),r.return(!1))}var bn={keyword:new ue.Name("keyword"),schemaPath:new ue.Name("schemaPath"),params:new ue.Name("params"),propertyName:new ue.Name("propertyName"),message:new ue.Name("message"),schema:new ue.Name("schema"),parentSchema:new ue.Name("parentSchema")};function Ly(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ue._)`{}`:I$(t,e,r)}function I$(t,e,r={}){let{gen:n,it:s}=t,o=[O$(s,r),A$(t,r)];return N$(t,e,o),n.object(...o)}function O$({errorPath:t},{instancePath:e}){let r=e?(0,ue.str)`${t}${(0,ua.getErrorPath)(e,ua.Type.Str)}`:t;return[et.default.instancePath,(0,ue.strConcat)(et.default.instancePath,r)]}function A$({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,ue.str)`${e}/${t}`;return r&&(s=(0,ue.str)`${s}${(0,ua.getErrorPath)(r,ua.Type.Str)}`),[bn.schemaPath,s]}function N$(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([bn.keyword,s],[bn.params,typeof e=="function"?e(t):e||(0,ue._)`{}`]),c.messages&&n.push([bn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([bn.schema,i],[bn.parentSchema,(0,ue._)`${l}${d}`],[et.default.data,o]),u&&n.push([bn.propertyName,u])}});var Fy=O(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.boolOrEmptySchema=ns.topBoolOrEmptySchema=void 0;var D$=yo(),z$=Q(),M$=mr(),L$={message:"boolean schema is false"};function j$(t){let{gen:e,schema:r,validateName:n}=t;r===!1?jy(t,!1):typeof r=="object"&&r.$async===!0?e.return(M$.default.data):(e.assign((0,z$._)`${n}.errors`,null),e.return(!0))}ns.topBoolOrEmptySchema=j$;function F$(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),jy(t)):r.var(e,!0)}ns.boolOrEmptySchema=F$;function jy(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,D$.reportError)(s,L$,void 0,e)}});var Ld=O(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.getRules=ss.isJSONType=void 0;var Z$=["string","number","integer","boolean","null","object","array"],U$=new Set(Z$);function q$(t){return typeof t=="string"&&U$.has(t)}ss.isJSONType=q$;function B$(){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:{}}}ss.getRules=B$});var jd=O(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.shouldUseRule=Ir.shouldUseGroup=Ir.schemaHasRulesForType=void 0;function H$({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Zy(t,n)}Ir.schemaHasRulesForType=H$;function Zy(t,e){return e.rules.some(r=>Uy(t,r))}Ir.shouldUseGroup=Zy;function Uy(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))}Ir.shouldUseRule=Uy});var _o=O(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.reportTypeError=Ke.checkDataTypes=Ke.checkDataType=Ke.coerceAndCheckDataType=Ke.getJSONTypes=Ke.getSchemaTypes=Ke.DataType=void 0;var V$=Ld(),W$=jd(),G$=yo(),X=Q(),qy=ce(),os;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(os||(Ke.DataType=os={}));function J$(t){let e=By(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}Ke.getSchemaTypes=J$;function By(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(V$.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ke.getJSONTypes=By;function K$(t,e){let{gen:r,data:n,opts:s}=t,o=X$(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,W$.schemaHasRulesForType)(t,e[0]));if(i){let a=Zd(e,n,s.strictNumbers,os.Wrong);r.if(a,()=>{o.length?Y$(t,e,o):Ud(t)})}return i}Ke.coerceAndCheckDataType=K$;var Hy=new Set(["string","number","integer","boolean","null"]);function X$(t,e){return e?t.filter(r=>Hy.has(r)||e==="array"&&r==="array"):[]}function Y$(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,X._)`typeof ${s}`),a=n.let("coerced",(0,X._)`undefined`);o.coerceTypes==="array"&&n.if((0,X._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,X._)`${s}[0]`).assign(i,(0,X._)`typeof ${s}`).if(Zd(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,X._)`${a} !== undefined`);for(let u of r)(Hy.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),Ud(t),n.endIf(),n.if((0,X._)`${a} !== undefined`,()=>{n.assign(s,a),Q$(t,a)});function c(u){switch(u){case"string":n.elseIf((0,X._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,X._)`"" + ${s}`).elseIf((0,X._)`${s} === null`).assign(a,(0,X._)`""`);return;case"number":n.elseIf((0,X._)`${i} == "boolean" || ${s} === null
|
|
4
|
+
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,X._)`+${s}`);return;case"integer":n.elseIf((0,X._)`${i} === "boolean" || ${s} === null
|
|
5
|
+
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,X._)`+${s}`);return;case"boolean":n.elseIf((0,X._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,X._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,X._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,X._)`${i} === "string" || ${i} === "number"
|
|
6
|
+
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,X._)`[${s}]`)}}}function Q$({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,X._)`${e} !== undefined`,()=>t.assign((0,X._)`${e}[${r}]`,n))}function Fd(t,e,r,n=os.Correct){let s=n===os.Correct?X.operators.EQ:X.operators.NEQ,o;switch(t){case"null":return(0,X._)`${e} ${s} null`;case"array":o=(0,X._)`Array.isArray(${e})`;break;case"object":o=(0,X._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,X._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,X._)`typeof ${e} ${s} ${t}`}return n===os.Correct?o:(0,X.not)(o);function i(a=X.nil){return(0,X.and)((0,X._)`typeof ${e} == "number"`,a,r?(0,X._)`isFinite(${e})`:X.nil)}}Ke.checkDataType=Fd;function Zd(t,e,r,n){if(t.length===1)return Fd(t[0],e,r,n);let s,o=(0,qy.toHash)(t);if(o.array&&o.object){let i=(0,X._)`typeof ${e} != "object"`;s=o.null?i:(0,X._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=X.nil;o.number&&delete o.integer;for(let i in o)s=(0,X.and)(s,Fd(i,e,r,n));return s}Ke.checkDataTypes=Zd;var eR={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,X._)`{type: ${t}}`:(0,X._)`{type: ${e}}`};function Ud(t){let e=tR(t);(0,G$.reportError)(e,eR)}Ke.reportTypeError=Ud;function tR(t){let{gen:e,data:r,schema:n}=t,s=(0,qy.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var Wy=O(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.assignDefaults=void 0;var is=Q(),rR=ce();function nR(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)Vy(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>Vy(t,o,s.default))}la.assignDefaults=nR;function Vy(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,is._)`${o}${(0,is.getProperty)(e)}`;if(s){(0,rR.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,is._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,is._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,is._)`${a} = ${(0,is.stringify)(r)}`)}});var Tt=O(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.validateUnion=me.validateArray=me.usePattern=me.callValidateCode=me.schemaProperties=me.allSchemaProperties=me.noPropertyInData=me.propertyInData=me.isOwnProperty=me.hasPropFunc=me.reportMissingProp=me.checkMissingProp=me.checkReportMissingProp=void 0;var ve=Q(),qd=ce(),Or=mr(),sR=ce();function oR(t,e){let{gen:r,data:n,it:s}=t;r.if(Hd(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ve._)`${e}`},!0),t.error()})}me.checkReportMissingProp=oR;function iR({gen:t,data:e,it:{opts:r}},n,s){return(0,ve.or)(...n.map(o=>(0,ve.and)(Hd(t,e,o,r.ownProperties),(0,ve._)`${s} = ${o}`)))}me.checkMissingProp=iR;function aR(t,e){t.setParams({missingProperty:e},!0),t.error()}me.reportMissingProp=aR;function Gy(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ve._)`Object.prototype.hasOwnProperty`})}me.hasPropFunc=Gy;function Bd(t,e,r){return(0,ve._)`${Gy(t)}.call(${e}, ${r})`}me.isOwnProperty=Bd;function cR(t,e,r,n){let s=(0,ve._)`${e}${(0,ve.getProperty)(r)} !== undefined`;return n?(0,ve._)`${s} && ${Bd(t,e,r)}`:s}me.propertyInData=cR;function Hd(t,e,r,n){let s=(0,ve._)`${e}${(0,ve.getProperty)(r)} === undefined`;return n?(0,ve.or)(s,(0,ve.not)(Bd(t,e,r))):s}me.noPropertyInData=Hd;function Jy(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}me.allSchemaProperties=Jy;function uR(t,e){return Jy(e).filter(r=>!(0,qd.alwaysValidSchema)(t,e[r]))}me.schemaProperties=uR;function lR({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,u){let l=u?(0,ve._)`${t}, ${e}, ${n}${s}`:e,d=[[Or.default.instancePath,(0,ve.strConcat)(Or.default.instancePath,o)],[Or.default.parentData,i.parentData],[Or.default.parentDataProperty,i.parentDataProperty],[Or.default.rootData,Or.default.rootData]];i.opts.dynamicRef&&d.push([Or.default.dynamicAnchors,Or.default.dynamicAnchors]);let f=(0,ve._)`${l}, ${r.object(...d)}`;return c!==ve.nil?(0,ve._)`${a}.call(${c}, ${f})`:(0,ve._)`${a}(${f})`}me.callValidateCode=lR;var dR=(0,ve._)`new RegExp`;function pR({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,ve._)`${s.code==="new RegExp"?dR:(0,sR.useFunc)(t,s)}(${r}, ${n})`})}me.usePattern=pR;function fR(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let c=e.const("len",(0,ve._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:qd.Type.Num},o),e.if((0,ve.not)(o),a)})}}me.validateArray=fR;function mR(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,qd.alwaysValidSchema)(s,c))&&!s.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,ve._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ve.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}me.validateUnion=mR});var Yy=O(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.validateKeywordUsage=Yt.validSchemaType=Yt.funcKeywordCode=Yt.macroKeywordCode=void 0;var tt=Q(),vn=mr(),hR=Tt(),gR=yo();function yR(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=Xy(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:tt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Yt.macroKeywordCode=yR;function _R(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;vR(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,l=Xy(n,s,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&&Ky(t),g(()=>t.error());else{let y=e.async?h():p();e.modifying&&Ky(t),g(()=>bR(t,y))}}function h(){let y=n.let("ruleErrs",null);return n.try(()=>m((0,tt._)`await `),b=>n.assign(d,!1).if((0,tt._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,tt._)`${b}.errors`),()=>n.throw(b))),y}function p(){let y=(0,tt._)`${l}.errors`;return n.assign(y,null),m(tt.nil),y}function m(y=e.async?(0,tt._)`await `:tt.nil){let b=c.opts.passContext?vn.default.this:vn.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,tt._)`${y}${(0,hR.callValidateCode)(t,l,b,_)}`,e.modifying)}function g(y){var b;n.if((0,tt.not)((b=e.valid)!==null&&b!==void 0?b:d),y)}}Yt.funcKeywordCode=_R;function Ky(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,tt._)`${n.parentData}[${n.parentDataProperty}]`))}function bR(t,e){let{gen:r}=t;r.if((0,tt._)`Array.isArray(${e})`,()=>{r.assign(vn.default.vErrors,(0,tt._)`${vn.default.vErrors} === null ? ${e} : ${vn.default.vErrors}.concat(${e})`).assign(vn.default.errors,(0,tt._)`${vn.default.vErrors}.length`),(0,gR.extendErrors)(t)},()=>t.error())}function vR({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Xy(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,tt.stringify)(r)})}function xR(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")}Yt.validSchemaType=xR;function SR({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Yt.validateKeywordUsage=SR});var e_=O(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.extendSubschemaMode=Ar.extendSubschemaData=Ar.getSubschema=void 0;var Qt=Q(),Qy=ce();function wR(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Qt._)`${t.schemaPath}${(0,Qt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Qt._)`${t.schemaPath}${(0,Qt.getProperty)(e)}${(0,Qt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Qy.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Ar.getSubschema=wR;function ER(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,f=a.let("data",(0,Qt._)`${e.data}${(0,Qt.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Qt.str)`${u}${(0,Qy.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Qt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Qt.Name?s:a.let("data",s,!0);c(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Ar.extendSubschemaData=ER;function kR(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}Ar.extendSubschemaMode=kR});var Vd=O((IZ,t_)=>{"use strict";t_.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var n_=O((OZ,r_)=>{"use strict";var Nr=r_.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};da(e,n,s,t,"",t)};Nr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Nr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Nr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Nr.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 da(t,e,r,n,s,o,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Nr.arrayKeywords)for(var f=0;f<d.length;f++)da(t,e,r,d[f],s+"/"+l+"/"+f,o,s,l,n,f)}else if(l in Nr.propsKeywords){if(d&&typeof d=="object")for(var h in d)da(t,e,r,d[h],s+"/"+l+"/"+TR(h),o,s,l,n,h)}else(l in Nr.keywords||t.allKeys&&!(l in Nr.skipKeywords))&&da(t,e,r,d,s+"/"+l,o,s,l,n)}r(n,s,o,i,a,c,u)}}function TR(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var bo=O(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.getSchemaRefs=lt.resolveUrl=lt.normalizeId=lt._getFullPath=lt.getFullPath=lt.inlineRef=void 0;var $R=ce(),RR=Vd(),PR=n_(),CR=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function IR(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Wd(t):e?s_(t)<=e:!1}lt.inlineRef=IR;var OR=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Wd(t){for(let e in t){if(OR.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Wd)||typeof r=="object"&&Wd(r))return!0}return!1}function s_(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!CR.has(r)&&(typeof t[r]=="object"&&(0,$R.eachItem)(t[r],n=>e+=s_(n)),e===1/0))return 1/0}return e}function o_(t,e="",r){r!==!1&&(e=as(e));let n=t.parse(e);return i_(t,n)}lt.getFullPath=o_;function i_(t,e){return t.serialize(e).split("#")[0]+"#"}lt._getFullPath=i_;var AR=/#\/?$/;function as(t){return t?t.replace(AR,""):""}lt.normalizeId=as;function NR(t,e,r){return r=as(r),t.resolve(e,r)}lt.resolveUrl=NR;var DR=/^[a-z_][-a-z0-9._]*$/i;function zR(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=as(t[r]||e),o={"":s},i=o_(n,s,!1),a={},c=new Set;return PR(t,{allKeys:!0},(d,f,h,p)=>{if(p===void 0)return;let m=i+f,g=o[p];typeof d[r]=="string"&&(g=y.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),o[f]=g;function y(_){let x=this.opts.uriResolver.resolve;if(_=as(g?x(g,_):_),c.has(_))throw l(_);c.add(_);let w=this.refs[_];return typeof w=="string"&&(w=this.refs[w]),typeof w=="object"?u(d,w.schema,_):_!==as(m)&&(_[0]==="#"?(u(d,a[_],_),a[_]=d):this.refs[_]=m),_}function b(_){if(typeof _=="string"){if(!DR.test(_))throw new Error(`invalid anchor "${_}"`);y.call(this,`#${_}`)}}}),a;function u(d,f,h){if(f!==void 0&&!RR(d,f))throw l(h)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}lt.getSchemaRefs=zR});var So=O(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.getData=Dr.KeywordCxt=Dr.validateFunctionCode=void 0;var d_=Fy(),a_=_o(),Jd=jd(),pa=_o(),MR=Wy(),xo=Yy(),Gd=e_(),U=Q(),J=mr(),LR=bo(),hr=ce(),vo=yo();function jR(t){if(m_(t)&&(h_(t),f_(t))){UR(t);return}p_(t,()=>(0,d_.topBoolOrEmptySchema)(t))}Dr.validateFunctionCode=jR;function p_({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,U._)`${J.default.data}, ${J.default.valCxt}`,n.$async,()=>{t.code((0,U._)`"use strict"; ${c_(r,s)}`),ZR(t,s),t.code(o)}):t.func(e,(0,U._)`${J.default.data}, ${FR(s)}`,n.$async,()=>t.code(c_(r,s)).code(o))}function FR(t){return(0,U._)`{${J.default.instancePath}="", ${J.default.parentData}, ${J.default.parentDataProperty}, ${J.default.rootData}=${J.default.data}${t.dynamicRef?(0,U._)`, ${J.default.dynamicAnchors}={}`:U.nil}}={}`}function ZR(t,e){t.if(J.default.valCxt,()=>{t.var(J.default.instancePath,(0,U._)`${J.default.valCxt}.${J.default.instancePath}`),t.var(J.default.parentData,(0,U._)`${J.default.valCxt}.${J.default.parentData}`),t.var(J.default.parentDataProperty,(0,U._)`${J.default.valCxt}.${J.default.parentDataProperty}`),t.var(J.default.rootData,(0,U._)`${J.default.valCxt}.${J.default.rootData}`),e.dynamicRef&&t.var(J.default.dynamicAnchors,(0,U._)`${J.default.valCxt}.${J.default.dynamicAnchors}`)},()=>{t.var(J.default.instancePath,(0,U._)`""`),t.var(J.default.parentData,(0,U._)`undefined`),t.var(J.default.parentDataProperty,(0,U._)`undefined`),t.var(J.default.rootData,J.default.data),e.dynamicRef&&t.var(J.default.dynamicAnchors,(0,U._)`{}`)})}function UR(t){let{schema:e,opts:r,gen:n}=t;p_(t,()=>{r.$comment&&e.$comment&&y_(t),WR(t),n.let(J.default.vErrors,null),n.let(J.default.errors,0),r.unevaluated&&qR(t),g_(t),KR(t)})}function qR(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,U._)`${r}.evaluated`),e.if((0,U._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,U._)`${t.evaluated}.props`,(0,U._)`undefined`)),e.if((0,U._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,U._)`${t.evaluated}.items`,(0,U._)`undefined`))}function c_(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,U._)`/*# sourceURL=${r} */`:U.nil}function BR(t,e){if(m_(t)&&(h_(t),f_(t))){HR(t,e);return}(0,d_.boolOrEmptySchema)(t,e)}function f_({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 m_(t){return typeof t.schema!="boolean"}function HR(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&y_(t),GR(t),JR(t);let o=n.const("_errs",J.default.errors);g_(t,o),n.var(e,(0,U._)`${o} === ${J.default.errors}`)}function h_(t){(0,hr.checkUnknownRules)(t),VR(t)}function g_(t,e){if(t.opts.jtd)return u_(t,[],!1,e);let r=(0,a_.getSchemaTypes)(t.schema),n=(0,a_.coerceAndCheckDataType)(t,r);u_(t,r,!n,e)}function VR(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,hr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function WR(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,hr.checkStrictMode)(t,"default is ignored in the schema root")}function GR(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,LR.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function JR(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function y_({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,U._)`${J.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,U.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,U._)`${J.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function KR(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,U._)`${J.default.errors} === 0`,()=>e.return(J.default.data),()=>e.throw((0,U._)`new ${s}(${J.default.vErrors})`)):(e.assign((0,U._)`${n}.errors`,J.default.vErrors),o.unevaluated&&XR(t),e.return((0,U._)`${J.default.errors} === 0`))}function XR({gen:t,evaluated:e,props:r,items:n}){r instanceof U.Name&&t.assign((0,U._)`${e}.props`,r),n instanceof U.Name&&t.assign((0,U._)`${e}.items`,n)}function u_(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,hr.schemaHasRulesButRef)(o,l))){s.block(()=>b_(t,"$ref",l.all.$ref.definition));return}c.jtd||YR(t,e),s.block(()=>{for(let f of l.rules)d(f);d(l.post)});function d(f){(0,Jd.shouldUseGroup)(o,f)&&(f.type?(s.if((0,pa.checkDataType)(f.type,i,c.strictNumbers)),l_(t,f),e.length===1&&e[0]===f.type&&r&&(s.else(),(0,pa.reportTypeError)(t)),s.endIf()):l_(t,f),a||s.if((0,U._)`${J.default.errors} === ${n||0}`))}}function l_(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,MR.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,Jd.shouldUseRule)(n,o)&&b_(t,o.keyword,o.definition,e.type)})}function YR(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(QR(t,e),t.opts.allowUnionTypes||eP(t,e),tP(t,t.dataTypes))}function QR(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{__(t.dataTypes,r)||Kd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),nP(t,e)}}function eP(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Kd(t,"use allowUnionTypes to allow union type keyword")}function tP(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,Jd.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>rP(e,i))&&Kd(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function rP(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function __(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function nP(t,e){let r=[];for(let n of t.dataTypes)__(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Kd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,hr.checkStrictMode)(t,e,t.opts.strictTypes)}var fa=class{constructor(e,r,n){if((0,xo.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,hr.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",v_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,xo.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",J.default.errors))}result(e,r,n){this.failResult((0,U.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,U.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,U._)`${r} !== undefined && (${(0,U.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?vo.reportExtraError:vo.reportError)(this,this.def.error,r)}$dataError(){(0,vo.reportError)(this,this.def.$dataError||vo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,vo.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=U.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=U.nil,r=U.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,U.or)((0,U._)`${s} === undefined`,r)),e!==U.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==U.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,U.or)(i(),a());function i(){if(n.length){if(!(r instanceof U.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,U._)`${(0,pa.checkDataTypes)(c,r,o.opts.strictNumbers,pa.DataType.Wrong)}`}return U.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,U._)`!${c}(${r})`}return U.nil}}subschema(e,r){let n=(0,Gd.getSubschema)(this.it,e);(0,Gd.extendSubschemaData)(n,this.it,e),(0,Gd.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return BR(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=hr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=hr.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,U.Name)),!0}};Dr.KeywordCxt=fa;function b_(t,e,r,n){let s=new fa(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,xo.funcKeywordCode)(s,r):"macro"in r?(0,xo.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,xo.funcKeywordCode)(s,r)}var sP=/^\/(?:[^~]|~0|~1)*$/,oP=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function v_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return J.default.rootData;if(t[0]==="/"){if(!sP.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=J.default.rootData}else{let u=oP.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(s=u[2],s==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(o=r[e-l],!s)return o}let i=o,a=s.split("/");for(let u of a)u&&(o=(0,U._)`${o}${(0,U.getProperty)((0,hr.unescapeJsonPointer)(u))}`,i=(0,U._)`${i} && ${o}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Dr.getData=v_});var ma=O(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var Xd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Yd.default=Xd});var wo=O(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var Qd=bo(),ep=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Qd.resolveUrl)(e,r,n),this.missingSchema=(0,Qd.normalizeId)((0,Qd.getFullPath)(e,this.missingRef))}};tp.default=ep});var ga=O($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.resolveSchema=$t.getCompilingSchema=$t.resolveRef=$t.compileSchema=$t.SchemaEnv=void 0;var Mt=Q(),iP=ma(),xn=mr(),Lt=bo(),x_=ce(),aP=So(),cs=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,Lt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};$t.SchemaEnv=cs;function np(t){let e=S_.call(this,t);if(e)return e;let r=(0,Lt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new Mt.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:iP.default,code:(0,Mt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:xn.default.data,parentData:xn.default.parentData,parentDataProperty:xn.default.parentDataProperty,dataNames:[xn.default.data],dataPathArr:[Mt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Mt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Mt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Mt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,aP.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(xn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let h=new Function(`${xn.default.self}`,`${xn.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 Mt.Name?void 0:p,items:m instanceof Mt.Name?void 0:m,dynamicProps:p instanceof Mt.Name,dynamicItems:m instanceof Mt.Name},h.source&&(h.source.evaluated=(0,Mt.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)}}$t.compileSchema=np;function cP(t,e,r){var n;r=(0,Lt.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=dP.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new cs({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=uP.call(this,o)}$t.resolveRef=cP;function uP(t){return(0,Lt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:np.call(this,t)}function S_(t){for(let e of this._compilations)if(lP(e,t))return e}$t.getCompilingSchema=S_;function lP(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function dP(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ha.call(this,t,e)}function ha(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Lt._getFullPath)(this.opts.uriResolver,r),s=(0,Lt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return rp.call(this,r,t);let o=(0,Lt.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=ha.call(this,t,i);return typeof a?.schema!="object"?void 0:rp.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||np.call(this,i),o===(0,Lt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,Lt.resolveUrl)(this.opts.uriResolver,s,u)),new cs({schema:a,schemaId:c,root:t,baseId:s})}return rp.call(this,r,i)}}$t.resolveSchema=ha;var pP=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function rp(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,x_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!pP.has(a)&&u&&(e=(0,Lt.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,x_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Lt.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=ha.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new cs({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var w_=O((LZ,fP)=>{fP.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 up=O((jZ,C_)=>{"use strict";var mP=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),op=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),hP=RegExp.prototype.test.bind(/^\d*$/u),Sn=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),ip=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),k_=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),ap=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),gP=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),dt=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)dt[e]="%"+t[e>>4]+t[e&15]}function Xe(t){return t<2048?dt[192|t>>6]+dt[128|t&63]:t<65536?dt[224|t>>12]+dt[128|t>>6&63]+dt[128|t&63]:dt[240|t>>18]+dt[128|t>>12&63]+dt[128|t>>6&63]+dt[128|t&63]}function yP(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 _P=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),bP=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),vP=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),xP=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function SP(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!vP(t[e])){if(t[e]==="%"&&e+2<t.length&&Sn(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function E_(t){let e=-1,r=0,n=-1,s=0;for(let a=0;a<t.length;a++)t[a]==="0"?(n===-1&&(n=a),s++,s>r&&(r=s,e=n)):(n=-1,s=0);if(r<2)return t.join(":");let o=t.slice(0,e).join(":"),i=t.slice(e+r).join(":");return o+"::"+i}function wP(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let r=e===-1?t.split(":"):t.slice(0,e).split(":"),n=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let s=r.concat(n),o=0;for(let a=0;a<s.length;a++){let c=s[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==s.length-1||e!==-1&&n.length===0||!op(c))return;o+=2;continue}if(!_P(c))return;s[a]=parseInt(c,16).toString(16),o++}if(e===-1)return o!==8?void 0:E_(s);if(o>=8)return;let i=s.slice(0,r.length);for(let a=o;a<8;a++)i.push("0");for(let a=r.length;a<s.length;a++)i.push(s[a]);return E_(i)}function sp(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let n=e?t.slice(1,-1):t;if(e&&bP(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(EP(n,":")<2)return{host:t,isIPV6:!1,error:e};let s="",o=n.indexOf("%");if(o!==-1){let a=n.slice(o,o+3).toLowerCase()==="%25"?3:1;if(s=n.slice(o+a),!SP(s))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,o)}let i=wP(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(s?"%"+s:""),escapedHost:i+(s?"%25"+s:""),isIPV6:!0}}function EP(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function kP(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(s===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var TP={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},$P=/[@/?#:]/g,RP=/[@/?#]/g;function T_(t,e){let r=e?RP:$P;return r.lastIndex=0,t.replace(r,n=>TP[n])}function $_(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let s=t.slice(n+1,n+3);if(Sn(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&ip(i)?r+=i:r+="%"+o,n+=2;continue}}r+=t[n]}return r}function PP(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let s=t.slice(r+1,r+3);if(Sn(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&ip(i)?e+=i:e+="%"+o,r+=2;continue}}if(k_(n))e+=n;else{let s=t.charCodeAt(r);if(s<128)e+=P_(s)?n:dt[s];else if(s<55296||s>57343)e+=Xe(s);else if(s<=56319&&r+1<t.length){let o=t.charCodeAt(r+1);o>=56320&&o<=57343?(e+=Xe(65536+(s-55296<<10)+(o-56320)),r++):e+=Xe(65533)}else e+=Xe(65533)}}return e}function CP(t,e=!1){let r="",n=e&&t[0]!=="/";for(let s=0;s<t.length;s++){let o=t[s];if(o==="%"&&s+2<t.length){let i=t.slice(s+1,s+3);if(Sn(i)){r+="%"+i.toUpperCase(),s+=2;continue}}if(o==="/"&&(n=!1),k_(o)&&(o!==":"||!n))r+=o;else{let i=t.charCodeAt(s);if(i<128)r+=dt[i];else if(i<55296||i>57343)r+=Xe(i);else if(i<=56319&&s+1<t.length){let a=t.charCodeAt(s+1);a>=56320&&a<=57343?(r+=Xe(65536+(i-55296<<10)+(a-56320)),s++):r+=Xe(65533)}else r+=Xe(65533)}}return r}function cp(t,e){let r="";for(let n=0;n<t.length;n++){let s=t[n];if(s==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Sn(o)){r+="%"+o.toUpperCase(),n+=2;continue}}if(e(s))r+=s;else{let o=t.charCodeAt(n);if(o<128)r+=dt[o];else if(o<55296||o>57343)r+=Xe(o);else if(o<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=Xe(65536+(o-55296<<10)+(i-56320)),n++):r+=Xe(65533)}else r+=Xe(65533)}}return r}function R_(t){return cp(t,gP)}function IP(t){return cp(t,ap)}function OP(t){return cp(t,ap)}function P_(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function AP(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let s=t.slice(r+1,r+3);if(Sn(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));ip(i)?e+=i:e+="%"+o,r+=2;continue}}if(ap(n))e+=n;else{let s=t.charCodeAt(r);if(s<128)e+=P_(s)?n:dt[s];else if(s<55296||s>57343)e+=Xe(s);else if(s<=56319&&r+1<t.length){let o=t.charCodeAt(r+1);o>=56320&&o<=57343?(e+=Xe(65536+(s-55296<<10)+(o-56320)),r++):e+=Xe(65533)}else e+=Xe(65533)}}return e}function NP(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Sn(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function DP(t){let e=[];if(t.userinfo!==void 0&&(e.push(R_(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!op(r)){let n=sp(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=$_(r,!0),n=sp(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=T_(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!hP(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}C_.exports={nonSimpleDomain:xP,recomposeAuthority:DP,reescapeHostDelimiters:T_,normalizePercentEncoding:$_,normalizePathEncoding:PP,serializePathEncoding:CP,normalizeQueryFragmentEncoding:AP,encodeUserinfo:R_,encodeQuery:IP,encodeFragment:OP,escapePreservingEscapes:NP,removeDotSegments:kP,isIPv4:op,isUUID:mP,normalizeIPv6:sp,stringArrayToHexStripped:yP}});var D_=O((FZ,N_)=>{"use strict";var{isUUID:zP}=up(),MP=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,LP=["http","https","ws","wss","urn","urn:uuid"];function jP(t){return LP.indexOf(t)!==-1}function lp(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 I_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function O_(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 FP(t){return t.secure=lp(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function ZP(t){if((t.port===(lp(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=t.resourceName.indexOf("?"),r=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=r&&r!=="/"?r:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function UP(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(MP);if(r&&r[0]===t.path){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=dp(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function qP(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),s=`${r}:${e.nid||n}`,o=dp(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function BP(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!zP(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function HP(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var A_={scheme:"http",domainHost:!0,parse:I_,serialize:O_},VP={scheme:"https",domainHost:A_.domainHost,parse:I_,serialize:O_},ya={scheme:"ws",domainHost:!0,parse:FP,serialize:ZP},WP={scheme:"wss",domainHost:ya.domainHost,parse:ya.parse,serialize:ya.serialize},GP={scheme:"urn",parse:UP,serialize:qP,skipNormalize:!0},JP={scheme:"urn:uuid",parse:BP,serialize:HP,skipNormalize:!0},_a={http:A_,https:VP,ws:ya,wss:WP,urn:GP,"urn:uuid":JP};Object.setPrototypeOf(_a,null);function dp(t){return t&&(_a[t]||_a[t.toLowerCase()])||void 0}N_.exports={wsIsSecure:lp,SCHEMES:_a,isValidSchemeName:jP,getSchemeHandler:dp}});var J_=O((ZZ,xa)=>{"use strict";var{normalizeIPv6:F_,removeDotSegments:ko,recomposeAuthority:KP,normalizePercentEncoding:Z_,normalizePathEncoding:XP,serializePathEncoding:z_,normalizeQueryFragmentEncoding:M_,encodeQuery:YP,encodeFragment:QP,reescapeHostDelimiters:eC,isIPv4:U_,nonSimpleDomain:tC}=up(),{SCHEMES:q_,getSchemeHandler:pp}=D_(),B_=/^[A-Za-z][A-Za-z0-9+.-]*$/u,H_="URI scheme is malformed.";function L_(t){let e=unescape(String(t));if(!B_.test(e))throw new TypeError(H_);return e}function rC(t,e){return typeof t=="string"?t=lC(t,e):typeof t=="object"&&(t=va(wn(t,e),e)),t}function nC(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:u}=ba(t,n),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:f,malformedSchemeSpecific:h,malformedHost:p,malformedScheme:m}=ba(e,n);if(o||d||i||f||a||h||c||p||u||m)throw new Error(s.error||l.error||"URI is malformed.");let g=V_(s,l,n,!0),y=pp(r&&r.scheme||g.scheme),b=g.host,_=b!==void 0&&b!==""&&(U_(b)||F_(b).isIPV6);W_(g,r||{},y,_);let x=b&&b.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(b);if(g.error&&!x)throw new Error(g.error);return n.skipEscape=!0,wn(g,n)}function V_(t,e,r,n){let s={};return n||(t=va(wn(t,r),r),e=va(wn(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=ko(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=ko(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=ko(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=ko(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function sC(t,e,r){let n=j_(t,r),s=j_(e,r);return n!==void 0&&s!==void 0&&n===s}function wn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),s=[];r.scheme&&(r.scheme=L_(r.scheme));let o=pp(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=!n.skipEscape&&r.scheme===void 0&&!i;r.path!==void 0&&(n.skipEscape?r.path=Z_(r.path):r.path=z_(r.path,a)),n.reference!=="suffix"&&r.scheme&&(r.scheme=L_(r.scheme),s.push(r.scheme,":"));let c=KP(r);if(c!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(c),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let u=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(u=ko(u)),a&&(u=z_(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),s.push(u)}return r.query!==void 0&&s.push("?",YP(r.query)),r.fragment!==void 0&&s.push("#",QP(r.fragment)),s.join("")}var oC=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,iC=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,aC=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function cC(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Eo(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function fp(t){return t[0]==="["&&t[t.length-1]==="]"}function uC(t){let e=t[4];return Eo(t[3])||e!==void 0&&!fp(e)&&Eo(e)||Eo(t[6])||Eo(t[7])||Eo(t[8])}function W_(t,e,r,n){if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!fp(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&tC(t.host))try{t.host=new URL("http://"+t.host).hostname}catch(s){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+s,!0}return!1}function ba(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1,o=!1,i=!1,a=!1,c=!1,u=!1,l=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let d=t.match(iC);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",s=!0);let f=t.match(aC);if(f!==null){let p=f[1],m=p.replace(/[\t\n\r]/g,"");m.length>=2&&(m.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",s=!0):p.length!==m.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",s=!0))}let h=t.match(oC);if(h){if(n.scheme=h[1],n.userinfo=h[3],n.host=h[4],n.port=parseInt(h[5],10),n.path=h[6]||"",n.query=h[7],n.fragment=h[8],n.scheme!==void 0){let g=unescape(n.scheme);B_.test(g)?n.scheme=g.toLowerCase():(n.error=n.error||H_,u=!0)}o=uC(h),o&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=h[5]);let p=cC(n,h);if(p!==void 0&&(n.error=n.error||p,s=!0),n.host)if(U_(n.host)===!1){let y=fp(n.host),b=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,_=F_(n.host);l=_.isIPV6||_.isIPVFuture===!0,c=b&&(!y||_.error===!0),n.host=l?_.host:_.host.toLowerCase(),c&&(n.error=n.error||"URI host is malformed.",s=!0)}else l=!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 m=pp(r.scheme||n.scheme);if(c||(a=W_(n,r,m,l)),!m||m&&!m.skipNormalize){if(t.indexOf("%")!==-1&&n.host!==void 0&&!c){let g=l?n.host:Z_(n.host,!0);n.host=eC(g,l)}n.path&&(n.path=XP(n.path)),n.query&&(n.query=M_(n.query)),n.fragment&&(n.fragment=M_(n.fragment))}m&&m.parse&&(m.parse(n,r),m===q_.urn&&n.nid===void 0&&(i=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:u}}function va(t,e){return ba(t,e).parsed}function lC(t,e){return G_(t,e).normalized}function G_(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:i,malformedScheme:a}=ba(t,e);return{normalized:n||s||o||i||a?t:wn(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:i,malformedScheme:a}}function j_(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:wn(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=G_(r,e);return s||o||i||a||c?void 0:n}var mp={SCHEMES:q_,normalize:rC,resolve:nC,resolveComponent:V_,equal:sC,serialize:wn,parse:va};xa.exports=mp;xa.exports.default=mp;xa.exports.fastUri=mp});var X_=O(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var K_=J_();K_.code='require("ajv/dist/runtime/uri").default';hp.default=K_});var ob=O(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.CodeGen=qe.Name=qe.nil=qe.stringify=qe.str=qe._=qe.KeywordCxt=void 0;var dC=So();Object.defineProperty(qe,"KeywordCxt",{enumerable:!0,get:function(){return dC.KeywordCxt}});var us=Q();Object.defineProperty(qe,"_",{enumerable:!0,get:function(){return us._}});Object.defineProperty(qe,"str",{enumerable:!0,get:function(){return us.str}});Object.defineProperty(qe,"stringify",{enumerable:!0,get:function(){return us.stringify}});Object.defineProperty(qe,"nil",{enumerable:!0,get:function(){return us.nil}});Object.defineProperty(qe,"Name",{enumerable:!0,get:function(){return us.Name}});Object.defineProperty(qe,"CodeGen",{enumerable:!0,get:function(){return us.CodeGen}});var pC=ma(),rb=wo(),fC=Ld(),To=ga(),mC=Q(),$o=bo(),Sa=_o(),yp=ce(),Y_=w_(),hC=X_(),nb=(t,e)=>new RegExp(t,e);nb.code="new RegExp";var gC=["removeAdditional","useDefaults","coerceTypes"],yC=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_C={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."},bC={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Q_=200;function vC(t){var e,r,n,s,o,i,a,c,u,l,d,f,h,p,m,g,y,b,_,x,w,I,R,M,z;let V=t.strict,$=(e=t.code)===null||e===void 0?void 0:e.optimize,T=$===!0||$===void 0?1:$||0,F=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:nb,de=(s=t.uriResolver)!==null&&s!==void 0?s:hC.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o: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=(h=t.strictRequired)!==null&&h!==void 0?h:V)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:T,regExp:F}:{optimize:T,regExp:F},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:Q_,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:Q_,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:(w=t.addUsedSchema)!==null&&w!==void 0?w:!0,validateSchema:(I=t.validateSchema)!==null&&I!==void 0?I:!0,validateFormats:(R=t.validateFormats)!==null&&R!==void 0?R:!0,unicodeRegExp:(M=t.unicodeRegExp)!==null&&M!==void 0?M:!0,int32range:(z=t.int32range)!==null&&z!==void 0?z:!0,uriResolver:de}}var Ro=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,...vC(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new mC.ValueScope({scope:{},prefixes:yC,es5:r,lines:n}),this.logger=TC(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,fC.getRules)(),eb.call(this,_C,e,"NOT SUPPORTED"),eb.call(this,bC,e,"DEPRECATED","warn"),this._metaOpts=EC.call(this),e.formats&&SC.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&wC.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),xC.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Y_;n==="id"&&(s={...Y_},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let s=n(r);return"$async"in n||(this.errors=n.errors),s}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,r);async function s(l,d){await o.call(this,l.$schema);let f=this._addSchema(l,d);return f.validate||i.call(this,f)}async function o(l){l&&!this.getSchema(l)&&await s.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof rb.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 o.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,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,$o.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=tb.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new To.SchemaEnv({schema:{},schemaId:n});if(r=To.resolveSchema.call(this,s,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=tb.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,$o.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(RC.call(this,n,r),!r)return(0,yp.eachItem)(n,o=>gp.call(this,o)),this;CC.call(this,r);let s={...r,type:(0,Sa.getJSONTypes)(r.type),schemaType:(0,Sa.getJSONTypes)(r.schemaType)};return(0,yp.eachItem)(n,s.type.length===0?o=>gp.call(this,o,s):o=>s.type.forEach(i=>gp.call(this,o,s,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=sb(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,$o.normalizeId)(i||n);let u=$o.getSchemaRefs.call(this,e,n);return c=new To.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):To.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{To.compileSchema.call(this,e)}finally{this.opts=r}}};Ro.ValidationError=pC.default;Ro.MissingRefError=rb.default;qe.default=Ro;function eb(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function tb(t){return t=(0,$o.normalizeId)(t),this.schemas[t]||this.refs[t]}function xC(){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 SC(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function wC(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 EC(){let t={...this.opts};for(let e of gC)delete t[e];return t}var kC={log(){},warn(){},error(){}};function TC(t){if(t===!1)return kC;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 $C=/^[a-z_$][a-z0-9_$:-]*$/i;function RC(t,e){let{RULES:r}=this;if((0,yp.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!$C.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 gp(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Sa.getJSONTypes)(e.type),schemaType:(0,Sa.getJSONTypes)(e.schemaType)}};e.before?PC.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function PC(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function CC(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=sb(e)),t.validateSchema=this.compile(e,!0))}var IC={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function sb(t){return{anyOf:[t,IC]}}});var ib=O(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});var OC={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};_p.default=OC});var lb=O(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.callRef=En.getValidate=void 0;var AC=wo(),ab=Tt(),pt=Q(),ls=mr(),cb=ga(),wa=ce(),NC={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return d();let l=cb.resolveRef.call(c,u,s,r);if(l===void 0)throw new AC.default(n.opts.uriResolver,s,r);if(l instanceof cb.SchemaEnv)return f(l);return h(l);function d(){if(o===u)return Ea(t,i,o,o.$async);let p=e.scopeValue("root",{ref:u});return Ea(t,(0,pt._)`${p}.validate`,u,u.$async)}function f(p){let m=ub(t,p);Ea(t,m,p,p.$async)}function h(p){let m=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,pt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:pt.nil,topSchemaRef:m,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function ub(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,pt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}En.getValidate=ub;function Ea(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?ls.default.this:pt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=s.let("valid");s.try(()=>{s.code((0,pt._)`await ${(0,ab.callValidateCode)(t,e,u)}`),h(e),i||s.assign(p,!0)},m=>{s.if((0,pt._)`!(${m} instanceof ${o.ValidationError})`,()=>s.throw(m)),f(m),i||s.assign(p,!1)}),t.ok(p)}function d(){t.result((0,ab.callValidateCode)(t,e,u),()=>h(e),()=>f(e))}function f(p){let m=(0,pt._)`${p}.errors`;s.assign(ls.default.vErrors,(0,pt._)`${ls.default.vErrors} === null ? ${m} : ${ls.default.vErrors}.concat(${m})`),s.assign(ls.default.errors,(0,pt._)`${ls.default.vErrors}.length`)}function h(p){var m;if(!o.opts.unevaluated)return;let g=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=wa.mergeEvaluated.props(s,g.props,o.props));else{let y=s.var("props",(0,pt._)`${p}.evaluated.props`);o.props=wa.mergeEvaluated.props(s,y,o.props,pt.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=wa.mergeEvaluated.items(s,g.items,o.items));else{let y=s.var("items",(0,pt._)`${p}.evaluated.items`);o.items=wa.mergeEvaluated.items(s,y,o.items,pt.Name)}}}En.callRef=Ea;En.default=NC});var db=O(bp=>{"use strict";Object.defineProperty(bp,"__esModule",{value:!0});var DC=ib(),zC=lb(),MC=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",DC.default,zC.default];bp.default=MC});var pb=O(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});var ka=Q(),zr=ka.operators,Ta={maximum:{okStr:"<=",ok:zr.LTE,fail:zr.GT},minimum:{okStr:">=",ok:zr.GTE,fail:zr.LT},exclusiveMaximum:{okStr:"<",ok:zr.LT,fail:zr.GTE},exclusiveMinimum:{okStr:">",ok:zr.GT,fail:zr.LTE}},LC={message:({keyword:t,schemaCode:e})=>(0,ka.str)`must be ${Ta[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ka._)`{comparison: ${Ta[t].okStr}, limit: ${e}}`},jC={keyword:Object.keys(Ta),type:"number",schemaType:"number",$data:!0,error:LC,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ka._)`${r} ${Ta[e].fail} ${n} || isNaN(${r})`)}};vp.default=jC});var fb=O(xp=>{"use strict";Object.defineProperty(xp,"__esModule",{value:!0});var Po=Q(),FC={message:({schemaCode:t})=>(0,Po.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Po._)`{multipleOf: ${t}}`},ZC={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:FC,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Po._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Po._)`${i} !== parseInt(${i})`;t.fail$data((0,Po._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};xp.default=ZC});var hb=O(Sp=>{"use strict";Object.defineProperty(Sp,"__esModule",{value:!0});function mb(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}Sp.default=mb;mb.code='require("ajv/dist/runtime/ucs2length").default'});var gb=O(wp=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});var kn=Q(),UC=ce(),qC=hb(),BC={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}}`},HC={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:BC,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?kn.operators.GT:kn.operators.LT,i=s.opts.unicode===!1?(0,kn._)`${r}.length`:(0,kn._)`${(0,UC.useFunc)(t.gen,qC.default)}(${r})`;t.fail$data((0,kn._)`${i} ${o} ${n}`)}};wp.default=HC});var yb=O(Ep=>{"use strict";Object.defineProperty(Ep,"__esModule",{value:!0});var VC=Tt(),WC=ce(),ds=Q(),GC={message:({schemaCode:t})=>(0,ds.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ds._)`{pattern: ${t}}`},JC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:GC,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,ds._)`new RegExp`:(0,WC.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ds._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,ds._)`!${l}`)}else{let c=(0,VC.usePattern)(t,s);t.fail$data((0,ds._)`!${c}.test(${r})`)}}};Ep.default=JC});var _b=O(kp=>{"use strict";Object.defineProperty(kp,"__esModule",{value:!0});var Co=Q(),KC={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Co.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Co._)`{limit: ${t}}`},XC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:KC,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Co.operators.GT:Co.operators.LT;t.fail$data((0,Co._)`Object.keys(${r}).length ${s} ${n}`)}};kp.default=XC});var bb=O(Tp=>{"use strict";Object.defineProperty(Tp,"__esModule",{value:!0});var Io=Tt(),Oo=Q(),YC=ce(),QC={message:({params:{missingProperty:t}})=>(0,Oo.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Oo._)`{missingProperty: ${t}}`},eI={keyword:"required",type:"object",schemaType:"array",$data:!0,error:QC,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():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,YC.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(Oo.nil,d);else for(let h of r)(0,Io.checkReportMissingProp)(t,h)}function l(){let h=e.let("missing");if(c||o){let p=e.let("valid",!0);t.block$data(p,()=>f(h,p)),t.ok(p)}else e.if((0,Io.checkMissingProp)(t,r,h)),(0,Io.reportMissingProp)(t,h),e.else()}function d(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,Io.noPropertyInData)(e,s,h,a.ownProperties),()=>t.error())})}function f(h,p){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(p,(0,Io.propertyInData)(e,s,h,a.ownProperties)),e.if((0,Oo.not)(p),()=>{t.error(),e.break()})},Oo.nil)}}};Tp.default=eI});var vb=O($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});var Ao=Q(),tI={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ao.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ao._)`{limit: ${t}}`},rI={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:tI,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Ao.operators.GT:Ao.operators.LT;t.fail$data((0,Ao._)`${r}.length ${s} ${n}`)}};$p.default=rI});var $a=O(Rp=>{"use strict";Object.defineProperty(Rp,"__esModule",{value:!0});var xb=Vd();xb.code='require("ajv/dist/runtime/equal").default';Rp.default=xb});var Sb=O(Cp=>{"use strict";Object.defineProperty(Cp,"__esModule",{value:!0});var Pp=_o(),Be=Q(),nI=ce(),sI=$a(),oI={message:({params:{i:t,j:e}})=>(0,Be.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Be._)`{i: ${t}, j: ${e}}`},iI={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:oI,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let c=e.let("valid"),u=o.items?(0,Pp.getSchemaTypes)(o.items):[];t.block$data(c,l,(0,Be._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,Be._)`${r}.length`),m=e.let("j");t.setParams({i:p,j:m}),e.assign(c,!0),e.if((0,Be._)`${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,Pp.checkDataTypes)(u,g,a.opts.strictNumbers,Pp.DataType.Wrong),b=e.const("indices",(0,Be._)`{}`);e.for((0,Be._)`;${p}--;`,()=>{e.let(g,(0,Be._)`${r}[${p}]`),e.if(y,(0,Be._)`continue`),u.length>1&&e.if((0,Be._)`typeof ${g} == "string"`,(0,Be._)`${g} += "_"`),e.if((0,Be._)`typeof ${b}[${g}] == "number"`,()=>{e.assign(m,(0,Be._)`${b}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,Be._)`${b}[${g}] = ${p}`)})}function h(p,m){let g=(0,nI.useFunc)(e,sI.default),y=e.name("outer");e.label(y).for((0,Be._)`;${p}--;`,()=>e.for((0,Be._)`${m} = ${p}; ${m}--;`,()=>e.if((0,Be._)`${g}(${r}[${p}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Cp.default=iI});var wb=O(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});var Ip=Q(),aI=ce(),cI=$a(),uI={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ip._)`{allowedValue: ${t}}`},lI={keyword:"const",$data:!0,error:uI,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Ip._)`!${(0,aI.useFunc)(e,cI.default)}(${r}, ${s})`):t.fail((0,Ip._)`${o} !== ${r}`)}};Op.default=lI});var Eb=O(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});var No=Q(),dI=ce(),pI=$a(),fI={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,No._)`{allowedValues: ${t}}`},mI={keyword:"enum",schemaType:"array",$data:!0,error:fI,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,dI.useFunc)(e,pI.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let h=e.const("vSchema",o);l=(0,No.or)(...s.map((p,m)=>f(h,m)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",o,h=>e.if((0,No._)`${u()}(${r}, ${h})`,()=>e.assign(l,!0).break()))}function f(h,p){let m=s[p];return typeof m=="object"&&m!==null?(0,No._)`${u()}(${r}, ${h}[${p}])`:(0,No._)`${r} === ${m}`}}};Ap.default=mI});var kb=O(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});var hI=pb(),gI=fb(),yI=gb(),_I=yb(),bI=_b(),vI=bb(),xI=vb(),SI=Sb(),wI=wb(),EI=Eb(),kI=[hI.default,gI.default,yI.default,_I.default,bI.default,vI.default,xI.default,SI.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},wI.default,EI.default];Np.default=kI});var zp=O(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.validateAdditionalItems=void 0;var Tn=Q(),Dp=ce(),TI={message:({params:{len:t}})=>(0,Tn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Tn._)`{limit: ${t}}`},$I={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:TI,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Dp.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Tb(t,n)}};function Tb(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,Tn._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Tn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Dp.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Tn._)`${a} <= ${e.length}`);r.if((0,Tn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:o,dataProp:l,dataPropType:Dp.Type.Num},u),i.allErrors||r.if((0,Tn.not)(u),()=>r.break())})}}Do.validateAdditionalItems=Tb;Do.default=$I});var Mp=O(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.validateTuple=void 0;var $b=Q(),Ra=ce(),RI=Tt(),PI={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Rb(t,"additionalItems",e);r.items=!0,!(0,Ra.alwaysValidSchema)(r,e)&&t.ok((0,RI.validateArray)(t))}};function Rb(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;l(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Ra.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,$b._)`${o}.length`);r.forEach((d,f)=>{(0,Ra.alwaysValidSchema)(a,d)||(n.if((0,$b._)`${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,Ra.checkStrictMode)(a,g,f.strictTuples)}}}zo.validateTuple=Rb;zo.default=PI});var Pb=O(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});var CI=Mp(),II={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,CI.validateTuple)(t,"items")};Lp.default=II});var Ib=O(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var Cb=Q(),OI=ce(),AI=Tt(),NI=zp(),DI={message:({params:{len:t}})=>(0,Cb.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Cb._)`{limit: ${t}}`},zI={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:DI,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,OI.alwaysValidSchema)(n,e)&&(s?(0,NI.validateAdditionalItems)(t,s):t.ok((0,AI.validateArray)(t)))}};jp.default=zI});var Ob=O(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});var Rt=Q(),Pa=ce(),MI={message:({params:{min:t,max:e}})=>e===void 0?(0,Rt.str)`must contain at least ${t} valid item(s)`:(0,Rt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Rt._)`{minContains: ${t}}`:(0,Rt._)`{minContains: ${t}, maxContains: ${e}}`},LI={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:MI,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:c,maxContains:u}=n;o.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,Rt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Pa.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Pa.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Pa.alwaysValidSchema)(o,r)){let m=(0,Rt._)`${l} >= ${i}`;a!==void 0&&(m=(0,Rt._)`${m} && ${l} <= ${a}`),t.pass(m);return}o.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,Rt._)`${s}.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:Pa.Type.Num,compositeRule:!0},m),g()})}function p(m){e.code((0,Rt._)`${m}++`),a===void 0?e.if((0,Rt._)`${m} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Rt._)`${m} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Rt._)`${m} >= ${i}`,()=>e.assign(d,!0)))}}};Fp.default=LI});var Db=O(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.validateSchemaDeps=er.validatePropertyDeps=er.error=void 0;var Zp=Q(),jI=ce(),Mo=Tt();er.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Zp.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Zp._)`{property: ${t},
|
|
7
|
+
missingProperty: ${n},
|
|
8
|
+
depsCount: ${e},
|
|
9
|
+
deps: ${r}}`};var FI={keyword:"dependencies",type:"object",schemaType:"object",error:er.error,code(t){let[e,r]=ZI(t);Ab(t,e),Nb(t,r)}};function ZI({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function Ab(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Mo.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of a)(0,Mo.checkReportMissingProp)(t,u)}):(r.if((0,Zp._)`${c} && (${(0,Mo.checkMissingProp)(t,a,o)})`),(0,Mo.reportMissingProp)(t,o),r.else())}}er.validatePropertyDeps=Ab;function Nb(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,jI.alwaysValidSchema)(o,e[a])||(r.if((0,Mo.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}er.validateSchemaDeps=Nb;er.default=FI});var Mb=O(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});var zb=Q(),UI=ce(),qI={message:"property name must be valid",params:({params:t})=>(0,zb._)`{propertyName: ${t.propertyName}}`},BI={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:qI,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,UI.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,zb.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Up.default=BI});var Bp=O(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});var Ca=Tt(),jt=Q(),HI=mr(),Ia=ce(),VI={message:"must NOT have additional properties",params:({params:t})=>(0,jt._)`{additionalProperty: ${t.additionalProperty}}`},WI={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:VI,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Ia.alwaysValidSchema)(i,r))return;let u=(0,Ca.allSchemaProperties)(n.properties),l=(0,Ca.allSchemaProperties)(n.patternProperties);d(),t.ok((0,jt._)`${o} === ${HI.default.errors}`);function d(){e.forIn("key",s,g=>{!u.length&&!l.length?p(g):e.if(f(g),()=>p(g))})}function f(g){let y;if(u.length>8){let b=(0,Ia.schemaRefOrVal)(i,n.properties,"properties");y=(0,Ca.isOwnProperty)(e,b,g)}else u.length?y=(0,jt.or)(...u.map(b=>(0,jt._)`${g} === ${b}`)):y=jt.nil;return l.length&&(y=(0,jt.or)(y,...l.map(b=>(0,jt._)`${(0,Ca.usePattern)(t,b)}.test(${g})`))),(0,jt.not)(y)}function h(g){e.code((0,jt._)`delete ${s}[${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,Ia.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,jt.not)(y),()=>{t.reset(),h(g)})):(m(g,y),a||e.if((0,jt.not)(y),()=>e.break()))}}function m(g,y,b){let _={keyword:"additionalProperties",dataProp:g,dataPropType:Ia.Type.Str};b===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,y)}}};qp.default=WI});var Fb=O(Vp=>{"use strict";Object.defineProperty(Vp,"__esModule",{value:!0});var GI=So(),Lb=Tt(),Hp=ce(),jb=Bp(),JI={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&jb.default.code(new GI.KeywordCxt(o,jb.default,"additionalProperties"));let i=(0,Lb.allSchemaProperties)(r);for(let d of i)o.definedProperties.add(d);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Hp.mergeEvaluated.props(e,(0,Hp.toHash)(i),o.props));let a=i.filter(d=>!(0,Hp.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,Lb.propertyInData)(e,s,d,o.opts.ownProperties)),l(d),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Vp.default=JI});var Bb=O(Wp=>{"use strict";Object.defineProperty(Wp,"__esModule",{value:!0});var Zb=Tt(),Oa=Q(),Ub=ce(),qb=ce(),KI={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,Zb.allSchemaProperties)(r),c=a.filter(m=>(0,Ub.alwaysValidSchema)(o,r[m]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,l=e.name("valid");o.props!==!0&&!(o.props instanceof Oa.Name)&&(o.props=(0,qb.evaluatedPropsToName)(e,o.props));let{props:d}=o;f();function f(){for(let m of a)u&&h(m),o.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,Ub.checkStrictMode)(o,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,g=>{e.if((0,Oa._)`${(0,Zb.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:qb.Type.Str},l),o.opts.unevaluated&&d!==!0?e.assign((0,Oa._)`${d}[${g}]`,!0):!y&&!o.allErrors&&e.if((0,Oa.not)(l),()=>e.break())})})}}};Wp.default=KI});var Hb=O(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});var XI=ce(),YI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,XI.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Gp.default=YI});var Vb=O(Jp=>{"use strict";Object.defineProperty(Jp,"__esModule",{value:!0});var QI=Tt(),eO={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:QI.validateUnion,error:{message:"must match a schema in anyOf"}};Jp.default=eO});var Wb=O(Kp=>{"use strict";Object.defineProperty(Kp,"__esModule",{value:!0});var Aa=Q(),tO=ce(),rO={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Aa._)`{passingSchemas: ${t.passing}}`},nO={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:rO,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((l,d)=>{let f;(0,tO.alwaysValidSchema)(s,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Aa._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Aa._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,Aa.Name)})})}}};Kp.default=nO});var Gb=O(Xp=>{"use strict";Object.defineProperty(Xp,"__esModule",{value:!0});var sO=ce(),oO={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let s=e.name("valid");r.forEach((o,i)=>{if((0,sO.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Xp.default=oO});var Xb=O(Yp=>{"use strict";Object.defineProperty(Yp,"__esModule",{value:!0});var Na=Q(),Kb=ce(),iO={message:({params:t})=>(0,Na.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Na._)`{failingKeyword: ${t.ifClause}}`},aO={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:iO,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Kb.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=Jb(n,"then"),o=Jb(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),s&&o){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else s?e.if(a,u("then")):e.if((0,Na.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,Na._)`${l}`):t.setParams({ifClause:l})}}}};function Jb(t,e){let r=t.schema[e];return r!==void 0&&!(0,Kb.alwaysValidSchema)(t,r)}Yp.default=aO});var Yb=O(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});var cO=ce(),uO={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,cO.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Qp.default=uO});var Qb=O(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var lO=zp(),dO=Pb(),pO=Mp(),fO=Ib(),mO=Ob(),hO=Db(),gO=Mb(),yO=Bp(),_O=Fb(),bO=Bb(),vO=Hb(),xO=Vb(),SO=Wb(),wO=Gb(),EO=Xb(),kO=Yb();function TO(t=!1){let e=[vO.default,xO.default,SO.default,wO.default,EO.default,kO.default,gO.default,yO.default,hO.default,_O.default,bO.default];return t?e.push(dO.default,fO.default):e.push(lO.default,pO.default),e.push(mO.default),e}ef.default=TO});var ev=O(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var Ce=Q(),$O={message:({schemaCode:t})=>(0,Ce.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ce._)`{format: ${t}}`},RO={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:$O,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;s?f():h();function f(){let p=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=r.const("fDef",(0,Ce._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Ce._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(g,(0,Ce._)`${m}.type || "string"`).assign(y,(0,Ce._)`${m}.validate`),()=>r.assign(g,(0,Ce._)`"string"`).assign(y,m)),t.fail$data((0,Ce.or)(b(),_()));function b(){return c.strictSchema===!1?Ce.nil:(0,Ce._)`${i} && !${y}`}function _(){let x=l.$async?(0,Ce._)`(${m}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Ce._)`${y}(${n})`,w=(0,Ce._)`(typeof ${y} == "function" ? ${x} : ${y}.test(${n}))`;return(0,Ce._)`${y} && ${y} !== true && ${g} === ${e} && !${w}`}}function h(){let p=d.formats[o];if(!p){b();return}if(p===!0)return;let[m,g,y]=_(p);m===e&&t.pass(x());function b(){if(c.strictSchema===!1){d.logger.warn(w());return}throw new Error(w());function w(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function _(w){let I=w instanceof RegExp?(0,Ce.regexpCode)(w):c.code.formats?(0,Ce._)`${c.code.formats}${(0,Ce.getProperty)(o)}`:void 0,R=r.scopeValue("formats",{key:o,ref:w,code:I});return typeof w=="object"&&!(w instanceof RegExp)?[w.type||"string",w.validate,(0,Ce._)`${R}.validate`]:["string",w,R]}function x(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ce._)`await ${y}(${n})`}return typeof g=="function"?(0,Ce._)`${y}(${n})`:(0,Ce._)`${y}.test(${n})`}}}};tf.default=RO});var tv=O(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var PO=ev(),CO=[PO.default];rf.default=CO});var rv=O(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.contentVocabulary=ps.metadataVocabulary=void 0;ps.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ps.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var sv=O(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var IO=db(),OO=kb(),AO=Qb(),NO=tv(),nv=rv(),DO=[IO.default,OO.default,(0,AO.default)(),NO.default,nv.metadataVocabulary,nv.contentVocabulary];nf.default=DO});var iv=O(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.DiscrError=void 0;var ov;(function(t){t.Tag="tag",t.Mapping="mapping"})(ov||(Da.DiscrError=ov={}))});var cv=O(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var fs=Q(),sf=iv(),av=ga(),zO=wo(),MO=ce(),LO={message:({params:{discrError:t,tagName:e}})=>t===sf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,fs._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},jO={keyword:"discriminator",type:"object",schemaType:"object",error:LO,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,fs._)`${r}${(0,fs.getProperty)(a)}`);e.if((0,fs._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:sf.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,fs._)`${u} === ${p}`),e.assign(c,d(h[p]));e.else(),t.error(!1,{discrError:sf.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,fs.Name),p}function f(){var h;let p={},m=y(s),g=!0;for(let x=0;x<i.length;x++){let w=i[x];if(w?.$ref&&!(0,MO.schemaHasRulesButRef)(w,o.self.RULES)){let R=w.$ref;if(w=av.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,R),w instanceof av.SchemaEnv&&(w=w.schema),w===void 0)throw new zO.default(o.opts.uriResolver,o.baseId,R)}let I=(h=w?.properties)===null||h===void 0?void 0:h[a];if(typeof I!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y(w)),b(I,x)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:x}){return Array.isArray(x)&&x.includes(a)}function b(x,w){if(x.const)_(x.const,w);else if(x.enum)for(let I of x.enum)_(I,w);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(x,w){if(typeof x!="string"||x in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[x]=w}}}};of.default=jO});var uv=O((PU,FO)=>{FO.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 cf=O((xe,af)=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.MissingRefError=xe.ValidationError=xe.CodeGen=xe.Name=xe.nil=xe.stringify=xe.str=xe._=xe.KeywordCxt=xe.Ajv=void 0;var ZO=ob(),UO=sv(),qO=cv(),lv=uv(),BO=["/properties"],za="http://json-schema.org/draft-07/schema",ms=class extends ZO.default{_addVocabularies(){super._addVocabularies(),UO.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(qO.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(lv,BO):lv;this.addMetaSchema(e,za,!1),this.refs["http://json-schema.org/schema"]=za}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(za)?za:void 0)}};xe.Ajv=ms;af.exports=xe=ms;af.exports.Ajv=ms;Object.defineProperty(xe,"__esModule",{value:!0});xe.default=ms;var HO=So();Object.defineProperty(xe,"KeywordCxt",{enumerable:!0,get:function(){return HO.KeywordCxt}});var hs=Q();Object.defineProperty(xe,"_",{enumerable:!0,get:function(){return hs._}});Object.defineProperty(xe,"str",{enumerable:!0,get:function(){return hs.str}});Object.defineProperty(xe,"stringify",{enumerable:!0,get:function(){return hs.stringify}});Object.defineProperty(xe,"nil",{enumerable:!0,get:function(){return hs.nil}});Object.defineProperty(xe,"Name",{enumerable:!0,get:function(){return hs.Name}});Object.defineProperty(xe,"CodeGen",{enumerable:!0,get:function(){return hs.CodeGen}});var VO=ma();Object.defineProperty(xe,"ValidationError",{enumerable:!0,get:function(){return VO.default}});var WO=wo();Object.defineProperty(xe,"MissingRefError",{enumerable:!0,get:function(){return WO.default}})});var _v=O(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.formatNames=rr.fastFormats=rr.fullFormats=void 0;function tr(t,e){return{validate:t,compare:e}}rr.fullFormats={date:tr(mv,pf),time:tr(lf(!0),ff),"date-time":tr(dv(!0),gv),"iso-time":tr(lf(),hv),"iso-date-time":tr(dv(),yv),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:QO,"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:iA,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:eA,int32:{type:"number",validate:nA},int64:{type:"number",validate:sA},float:{type:"number",validate:fv},double:{type:"number",validate:fv},password:!0,binary:!0};rr.fastFormats={...rr.fullFormats,date:tr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,pf),time:tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ff),"date-time":tr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,gv),"iso-time":tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,hv),"iso-date-time":tr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,yv),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};rr.formatNames=Object.keys(rr.fullFormats);function GO(t){return t%4===0&&(t%100!==0||t%400===0)}var JO=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,KO=[0,31,28,31,30,31,30,31,31,30,31,30,31];function mv(t){let e=JO.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&GO(r)?29:KO[n])}function pf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var uf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function lf(t){return function(r){let n=uf.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let d=o-l*c,f=s-u*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&i<61}}function ff(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 hv(t,e){if(!(t&&e))return;let r=uf.exec(t),n=uf.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 df=/t|\s/i;function dv(t){let e=lf(t);return function(n){let s=n.split(df);return s.length===2&&mv(s[0])&&e(s[1])}}function gv(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function yv(t,e){if(!(t&&e))return;let[r,n]=t.split(df),[s,o]=e.split(df),i=pf(r,s);if(i!==void 0)return i||ff(n,o)}var XO=/\/|:/,YO=/^(?:[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 QO(t){return XO.test(t)&&YO.test(t)}var pv=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function eA(t){return pv.lastIndex=0,pv.test(t)}var tA=-(2**31),rA=2**31-1;function nA(t){return Number.isInteger(t)&&t<=rA&&t>=tA}function sA(t){return Number.isInteger(t)}function fv(){return!0}var oA=/[^\\]\\Z/;function iA(t){if(oA.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var bv=O(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.formatLimitDefinition=void 0;var aA=cf(),Ft=Q(),Mr=Ft.operators,Ma={formatMaximum:{okStr:"<=",ok:Mr.LTE,fail:Mr.GT},formatMinimum:{okStr:">=",ok:Mr.GTE,fail:Mr.LT},formatExclusiveMaximum:{okStr:"<",ok:Mr.LT,fail:Mr.GTE},formatExclusiveMinimum:{okStr:">",ok:Mr.GT,fail:Mr.LTE}},cA={message:({keyword:t,schemaCode:e})=>(0,Ft.str)`should be ${Ma[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ft._)`{comparison: ${Ma[t].okStr}, limit: ${e}}`};gs.formatLimitDefinition={keyword:Object.keys(Ma),type:"string",schemaType:"string",$data:!0,error:cA,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let c=new aA.KeywordCxt(o,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,Ft._)`${f}[${c.schemaCode}]`);t.fail$data((0,Ft.or)((0,Ft._)`typeof ${h} != "object"`,(0,Ft._)`${h} instanceof RegExp`,(0,Ft._)`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(`"${s}": format "${f}" does not define "compare" function`);let p=e.scopeValue("formats",{key:f,ref:h,code:i.code.formats?(0,Ft._)`${i.code.formats}${(0,Ft.getProperty)(f)}`:void 0});t.fail$data(d(p))}function d(f){return(0,Ft._)`${f}.compare(${r}, ${n}) ${Ma[s].fail} 0`}},dependencies:["format"]};var uA=t=>(t.addKeyword(gs.formatLimitDefinition),t);gs.default=uA});var wv=O((Lo,Sv)=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});var ys=_v(),lA=bv(),mf=Q(),vv=new mf.Name("fullFormats"),dA=new mf.Name("fastFormats"),hf=(t,e={keywords:!0})=>{if(Array.isArray(e))return xv(t,e,ys.fullFormats,vv),t;let[r,n]=e.mode==="fast"?[ys.fastFormats,dA]:[ys.fullFormats,vv],s=e.formats||ys.formatNames;return xv(t,s,r,n),e.keywords&&(0,lA.default)(t),t};hf.get=(t,e="full")=>{let n=(e==="fast"?ys.fastFormats:ys.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function xv(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,mf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Sv.exports=Lo=hf;Object.defineProperty(Lo,"__esModule",{value:!0});Lo.default=hf});var mx,hx=zc(()=>{"use strict";mx={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","antigravity-cli":"antigravity-cli",agy:"antigravity-cli","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","copilot-cli":"copilot-cli","GitHub Copilot CLI":"copilot-cli","github-copilot-cli":"copilot-cli","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code","kimi-code":"kimi",kimi:"kimi","Kimi Code":"kimi"}});var gx={};As(gx,{DshAdapter:()=>zf,parseCodexContextModePluginRoot:()=>Mf});import{resolve as vs}from"node:path";function Mf(t){for(let e of t.split(/\r?\n/)){let r=e.match(/^\s*context-mode@context-mode\s+installed,\s+enabled\s+\S+\s+(.+?)\s*$/);if(r?.[1])return r[1].trim()}return null}var wN,zf,Lf=zc(()=>{"use strict";Pn();wN={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1},zf=class{name="DSH";paradigm="mcp-only";capabilities=wN;platform;constructor(e="pi"){this.platform=e}parsePreToolUseInput(e){throw new Error("DSH routes tool guard decisions through Cordis, not JSON-stdio hooks")}parsePostToolUseInput(e){throw new Error("DSH routes tool results through Cordis, not JSON-stdio hooks")}parsePreCompactInput(e){throw new Error("DSH routes compaction through session events, not JSON-stdio hooks")}parseSessionStartInput(e){throw new Error("DSH injects session context through systemPrompt, not JSON-stdio hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return vs(process.env.CONTEXT_MODE_DIR??"","settings.json")}getConfigDir(e){return e&&e.length>0?vs(e):process.cwd()}getInstructionFiles(){return["AGENTS.md"]}getSessionDir(){let e=Rn(this.platform),r=process.env.CONTEXT_MODE_DIR;return r&&r.length>0?vs(r,"sessions"):e===null?vs(process.cwd(),"sessions"):vs(...e)}getMemoryDir(e){let r=process.env.CONTEXT_MODE_DIR??process.cwd();return vs(r,"memory",e??"")}generateHookConfig(e){return{}}readSettings(){return null}writeSettings(e){}backupSettings(){return null}validateHooks(e){return[{check:"Hook support",status:"pass",message:"DSH integrates context-mode through native Cordis tools, guards, and prompt sections rather than external hook scripts."}]}checkPluginRegistration(){return{check:"DSH plugin registration",status:"pass",message:"context-mode is bridged by the dsh-context-mode plugin."}}getInstalledVersion(){return"standalone"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
|
|
10
|
+
|
|
11
|
+
Use the context-mode tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_index, ctx_search) instead of inline shell or HTTP calls for data-heavy operations.`}}});var Ff={};As(Ff,{PLATFORM_ENV_VARS:()=>xs,__resetClaudeCodePluginCacheForTests:()=>TN,__seedClaudeCodePluginCacheMissForTests:()=>$N,detectPlatform:()=>mt,foreignIdentificationEnv:()=>IN,foreignWorkspaceEnv:()=>CN,getAdapter:()=>ON,getEnvVarNames:()=>PN,getSessionDirSegments:()=>Rn,workspaceEnvVarsFor:()=>jf});import{existsSync as Me,readFileSync as EN}from"node:fs";import{resolve as Re}from"node:path";import{homedir as yx}from"node:os";function kN(){if(Cn!==null)return Cn!=="miss"&&Cn.hasCM;try{let t=Re(yx(),".claude","plugins","installed_plugins.json"),e=EN(t,"utf-8"),r=JSON.parse(e),s=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(o=>o.includes("context-mode"));return Cn={hasCM:s},s}catch{return Cn="miss",!1}}function TN(){Cn=null}function $N(){Cn="miss"}function PN(t){return(xs.get(t)??[]).map(e=>e.name)}function jf(t){return(xs.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function CN(t){let e=new Set;for(let[r,n]of xs)if(r!==t)for(let s of n)s.role==="workspace"&&e.add(s.name);return e}function IN(t){let e=new Set;for(let[r,n]of xs)if(r!==t)for(let s of n)s.role==="identification"&&e.add(s.name);return e}function Rn(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 mt(t){if(t?.name){let o=mx[t.name];if(o)return{platform:o,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[o,i]of xs)if(i.some(a=>a.detect!==!1&&process.env[a.name]))return o==="vscode-copilot"&&kN()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:o,confidence:"high",reason:`${i.filter(a=>a.detect!==!1).map(a=>a.name).join(" or ")} env var set`};let r=yx(),n=(()=>{let o=process.env.COPILOT_HOME;return o&&o.trim()!==""?o.startsWith("~")?Re(r,o.replace(/^~[/\\]?/,"")):Re(o):Re(r,".copilot")})(),s=Me(Re(n,"mcp-config.json"))||Me(Re(n,"hooks","context-mode.json"));return process.env.COPILOT_HOME?.trim()&&s?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in explicit COPILOT_HOME exists (mcp-config.json or hooks/context-mode.json)"}:Me(Re(r,".local","bin","agy"))||Me(Re(r,".gemini","antigravity-cli"))||Me(Re(r,".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)"}:s?{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)"}:Me(Re(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Me(Re(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Me(Re(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Me(Re(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Me(Re(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Me(Re(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Me(Re(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Me(Re(r,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:Me(Re(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Me(Re(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Me(Re(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Me(Re(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Me(Re(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Me(Re(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 ON(t){let{DshAdapter:e}=await Promise.resolve().then(()=>(Lf(),gx));return new e(t??mt().platform)}var Cn,RN,xs,Pn=zc(()=>{"use strict";hx();Cn=null;RN=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"},{name:"PI_CODING_AGENT",role:"identification"}]]],xs=new Map(RN)});var C={};As(C,{BRAND:()=>C0,DIRTY:()=>Br,EMPTY_PATH:()=>c0,INVALID:()=>B,NEVER:()=>fw,OK:()=>We,ParseStatus:()=>je,Schema:()=>Y,ZodAny:()=>Sr,ZodArray:()=>lr,ZodBigInt:()=>Vr,ZodBoolean:()=>Wr,ZodBranded:()=>Ds,ZodCatch:()=>sn,ZodDate:()=>Gr,ZodDefault:()=>nn,ZodDiscriminatedUnion:()=>ui,ZodEffects:()=>St,ZodEnum:()=>tn,ZodError:()=>st,ZodFirstPartyTypeKind:()=>k,ZodFunction:()=>di,ZodIntersection:()=>Yr,ZodIssueCode:()=>E,ZodLazy:()=>Qr,ZodLiteral:()=>en,ZodMap:()=>jn,ZodNaN:()=>Zn,ZodNativeEnum:()=>rn,ZodNever:()=>Ot,ZodNull:()=>Kr,ZodNullable:()=>Jt,ZodNumber:()=>Hr,ZodObject:()=>it,ZodOptional:()=>ot,ZodParsedType:()=>A,ZodPipeline:()=>zs,ZodPromise:()=>wr,ZodReadonly:()=>on,ZodRecord:()=>li,ZodSchema:()=>Y,ZodSet:()=>Fn,ZodString:()=>xr,ZodSymbol:()=>Mn,ZodTransformer:()=>St,ZodTuple:()=>Gt,ZodType:()=>Y,ZodUndefined:()=>Jr,ZodUnion:()=>Xr,ZodUnknown:()=>ur,ZodVoid:()=>Ln,addIssueToContext:()=>P,any:()=>j0,array:()=>q0,bigint:()=>N0,boolean:()=>Fm,coerce:()=>pw,custom:()=>Mm,date:()=>D0,datetimeRegex:()=>Dm,defaultErrorMap:()=>ar,discriminatedUnion:()=>V0,effect:()=>sw,enum:()=>tw,function:()=>Y0,getErrorMap:()=>Nn,getParsedType:()=>Wt,instanceof:()=>O0,intersection:()=>W0,isAborted:()=>ai,isAsync:()=>Dn,isDirty:()=>ci,isValid:()=>vr,late:()=>I0,lazy:()=>Q0,literal:()=>ew,makeIssue:()=>Ns,map:()=>K0,nan:()=>A0,nativeEnum:()=>rw,never:()=>Z0,null:()=>L0,nullable:()=>iw,number:()=>jm,object:()=>Fc,objectUtil:()=>Mc,oboolean:()=>dw,onumber:()=>lw,optional:()=>ow,ostring:()=>uw,pipeline:()=>cw,preprocess:()=>aw,promise:()=>nw,quotelessJson:()=>o0,record:()=>J0,set:()=>X0,setErrorMap:()=>a0,strictObject:()=>B0,string:()=>Lm,symbol:()=>z0,transformer:()=>sw,tuple:()=>G0,undefined:()=>M0,union:()=>H0,unknown:()=>F0,util:()=>ne,void:()=>U0});var ne;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ne||(ne={}));var Mc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Mc||(Mc={}));var A=ne.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Wt=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=ne.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"]),o0=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),st=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ne.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};st.create=t=>new st(t);var i0=(t,e)=>{let r;switch(t.code){case E.invalid_type:t.received===A.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ne.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:r=`Unrecognized key(s) in object: ${ne.joinValues(t.keys,", ")}`;break;case E.invalid_union:r="Invalid input";break;case E.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ne.joinValues(t.options)}`;break;case E.invalid_enum_value:r=`Invalid enum value. Expected ${ne.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:r="Invalid function arguments";break;case E.invalid_return_type:r="Invalid function return type";break;case E.invalid_date:r="Invalid date";break;case E.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}"`:ne.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case E.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 E.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 E.custom:r="Invalid input";break;case E.invalid_intersection_types:r="Intersection results could not be merged";break;case E.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:r="Number must be finite";break;default:r=e.defaultError,ne.assertNever(t)}return{message:r}},ar=i0;var Cm=ar;function a0(t){Cm=t}function Nn(){return Cm}var Ns=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},c0=[];function P(t,e){let r=Nn(),n=Ns({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===ar?void 0:ar].filter(s=>!!s)});t.common.issues.push(n)}var je=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return B;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return B;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},B=Object.freeze({status:"aborted"}),Br=t=>({status:"dirty",value:t}),We=t=>({status:"valid",value:t}),ai=t=>t.status==="aborted",ci=t=>t.status==="dirty",vr=t=>t.status==="valid",Dn=t=>typeof Promise<"u"&&t instanceof Promise;var L;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}));var xt=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Im=(t,e)=>{if(vr(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 st(t.common.issues);return this._error=r,this._error}}};function K(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:s}}var Y=class{get description(){return this._def.description}_getType(e){return Wt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Wt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new je,ctx:{common:e.parent.common,data:e.data,parsedType:Wt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Dn(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:Wt(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Im(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Wt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return vr(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=>vr(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:Wt(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(Dn(s)?s:Promise.resolve(s));return Im(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:E.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new St({schema:this,typeName:k.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ot.create(this,this._def)}nullable(){return Jt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return lr.create(this)}promise(){return wr.create(this,this._def)}or(e){return Xr.create([this,e],this._def)}and(e){return Yr.create(this,e,this._def)}transform(e){return new St({...K(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new nn({...K(this._def),innerType:this,defaultValue:r,typeName:k.ZodDefault})}brand(){return new Ds({typeName:k.ZodBranded,type:this,...K(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new sn({...K(this._def),innerType:this,catchValue:r,typeName:k.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return zs.create(this,e)}readonly(){return on.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},u0=/^c[^\s-]{8,}$/i,l0=/^[0-9a-z]+$/,d0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,p0=/^[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,f0=/^[a-z0-9_-]{21}$/i,m0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,h0=/^[-+]?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)?)??$/,g0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,y0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Lc,_0=/^(?:(?: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])$/,b0=/^(?:(?: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])$/,v0=/^(([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]))$/,x0=/^(([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])$/,S0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,w0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Am="((\\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])))",E0=new RegExp(`^${Am}$`);function Nm(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 k0(t){return new RegExp(`^${Nm(t)}$`)}function Dm(t){let e=`${Am}T${Nm(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 T0(t,e){return!!((e==="v4"||!e)&&_0.test(t)||(e==="v6"||!e)&&v0.test(t))}function $0(t,e){if(!m0.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function R0(t,e){return!!((e==="v4"||!e)&&b0.test(t)||(e==="v6"||!e)&&x0.test(t))}var xr=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==A.string){let o=this._getOrReturnCtx(e);return P(o,{code:E.invalid_type,expected:A.string,received:o.parsedType}),B}let n=new je,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?P(s,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&P(s,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")g0.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"email",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Lc||(Lc=new RegExp(y0,"u")),Lc.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"emoji",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")p0.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"uuid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")f0.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"nanoid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")u0.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"cuid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")l0.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"cuid2",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")d0.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"ulid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),P(s,{validation:"url",code:E.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"regex",code:E.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),P(s,{code:E.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),P(s,{code:E.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),P(s,{code:E.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Dm(o).test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:E.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?E0.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:E.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?k0(o).test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:E.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?h0.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"duration",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?T0(e.data,o.version)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"ip",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?$0(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"jwt",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?R0(e.data,o.version)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"cidr",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?S0.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"base64",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?w0.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"base64url",code:E.invalid_string,message:o.message}),n.dirty()):ne.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:E.invalid_string,...L.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...L.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...L.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...L.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...L.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...L.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...L.errToObj(r)})}nonempty(e){return this.min(1,L.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};xr.create=t=>new xr({checks:[],typeName:k.ZodString,coerce:t?.coerce??!1,...K(t)});function P0(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}var Hr=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)!==A.number){let o=this._getOrReturnCtx(e);return P(o,{code:E.invalid_type,expected:A.number,received:o.parsedType}),B}let n,s=new je;for(let o of this._def.checks)o.kind==="int"?ne.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:E.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:E.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:E.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?P0(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),P(n,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:E.not_finite,message:o.message}),s.dirty()):ne.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ne.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)}};Hr.create=t=>new Hr({checks:[],typeName:k.ZodNumber,coerce:t?.coerce||!1,...K(t)});var Vr=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)!==A.bigint)return this._getInvalidInput(e);let n,s=new je;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:E.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:E.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),P(n,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ne.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return P(r,{code:E.invalid_type,expected:A.bigint,received:r.parsedType}),B}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Vr.create=t=>new Vr({checks:[],typeName:k.ZodBigInt,coerce:t?.coerce??!1,...K(t)});var Wr=class extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==A.boolean){let n=this._getOrReturnCtx(e);return P(n,{code:E.invalid_type,expected:A.boolean,received:n.parsedType}),B}return We(e.data)}};Wr.create=t=>new Wr({typeName:k.ZodBoolean,coerce:t?.coerce||!1,...K(t)});var Gr=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==A.date){let o=this._getOrReturnCtx(e);return P(o,{code:E.invalid_type,expected:A.date,received:o.parsedType}),B}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return P(o,{code:E.invalid_date}),B}let n=new je,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:E.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:E.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ne.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:L.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:L.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Gr.create=t=>new Gr({checks:[],coerce:t?.coerce||!1,typeName:k.ZodDate,...K(t)});var Mn=class extends Y{_parse(e){if(this._getType(e)!==A.symbol){let n=this._getOrReturnCtx(e);return P(n,{code:E.invalid_type,expected:A.symbol,received:n.parsedType}),B}return We(e.data)}};Mn.create=t=>new Mn({typeName:k.ZodSymbol,...K(t)});var Jr=class extends Y{_parse(e){if(this._getType(e)!==A.undefined){let n=this._getOrReturnCtx(e);return P(n,{code:E.invalid_type,expected:A.undefined,received:n.parsedType}),B}return We(e.data)}};Jr.create=t=>new Jr({typeName:k.ZodUndefined,...K(t)});var Kr=class extends Y{_parse(e){if(this._getType(e)!==A.null){let n=this._getOrReturnCtx(e);return P(n,{code:E.invalid_type,expected:A.null,received:n.parsedType}),B}return We(e.data)}};Kr.create=t=>new Kr({typeName:k.ZodNull,...K(t)});var Sr=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return We(e.data)}};Sr.create=t=>new Sr({typeName:k.ZodAny,...K(t)});var ur=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return We(e.data)}};ur.create=t=>new ur({typeName:k.ZodUnknown,...K(t)});var Ot=class extends Y{_parse(e){let r=this._getOrReturnCtx(e);return P(r,{code:E.invalid_type,expected:A.never,received:r.parsedType}),B}};Ot.create=t=>new Ot({typeName:k.ZodNever,...K(t)});var Ln=class extends Y{_parse(e){if(this._getType(e)!==A.undefined){let n=this._getOrReturnCtx(e);return P(n,{code:E.invalid_type,expected:A.void,received:n.parsedType}),B}return We(e.data)}};Ln.create=t=>new Ln({typeName:k.ZodVoid,...K(t)});var lr=class t extends Y{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==A.array)return P(r,{code:E.invalid_type,expected:A.array,received:r.parsedType}),B;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(P(r,{code:i?E.too_big:E.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(P(r,{code:E.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(P(r,{code:E.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new xt(r,i,r.path,a)))).then(i=>je.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new xt(r,i,r.path,a)));return je.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:L.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:L.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:L.toString(r)}})}nonempty(e){return this.min(1,e)}};lr.create=(t,e)=>new lr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...K(e)});function zn(t){if(t instanceof it){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ot.create(zn(n))}return new it({...t._def,shape:()=>e})}else return t instanceof lr?new lr({...t._def,type:zn(t.element)}):t instanceof ot?ot.create(zn(t.unwrap())):t instanceof Jt?Jt.create(zn(t.unwrap())):t instanceof Gt?Gt.create(t.items.map(e=>zn(e))):t}var it=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=ne.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==A.object){let u=this._getOrReturnCtx(e);return P(u,{code:E.invalid_type,expected:A.object,received:u.parsedType}),B}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ot&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=o[u],d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new xt(s,d,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Ot){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(u==="strict")a.length>0&&(P(s,{code:E.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=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new xt(s,d,s.path,l)),alwaysSet:l in s.data})}}return s.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=>je.mergeObjectSync(n,u)):je.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return L.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:L.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:k.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 ne.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 ne.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return zn(this)}partial(e){let r={};for(let n of ne.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ne.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ot;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return zm(ne.objectKeys(this.shape))}};it.create=(t,e)=>new it({shape:()=>t,unknownKeys:"strip",catchall:Ot.create(),typeName:k.ZodObject,...K(e)});it.strictCreate=(t,e)=>new it({shape:()=>t,unknownKeys:"strict",catchall:Ot.create(),typeName:k.ZodObject,...K(e)});it.lazycreate=(t,e)=>new it({shape:t,unknownKeys:"strip",catchall:Ot.create(),typeName:k.ZodObject,...K(e)});var Xr=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new st(a.ctx.common.issues));return P(r,{code:E.invalid_union,unionErrors:i}),B}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new st(c));return P(r,{code:E.invalid_union,unionErrors:a}),B}}get options(){return this._def.options}};Xr.create=(t,e)=>new Xr({options:t,typeName:k.ZodUnion,...K(e)});var cr=t=>t instanceof Qr?cr(t.schema):t instanceof St?cr(t.innerType()):t instanceof en?[t.value]:t instanceof tn?t.options:t instanceof rn?ne.objectValues(t.enum):t instanceof nn?cr(t._def.innerType):t instanceof Jr?[void 0]:t instanceof Kr?[null]:t instanceof ot?[void 0,...cr(t.unwrap())]:t instanceof Jt?[null,...cr(t.unwrap())]:t instanceof Ds||t instanceof on?cr(t.unwrap()):t instanceof sn?cr(t._def.innerType):[],ui=class t extends Y{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==A.object)return P(r,{code:E.invalid_type,expected:A.object,received:r.parsedType}),B;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(P(r,{code:E.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 s=new Map;for(let o of r){let i=cr(o.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:k.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...K(n)})}};function jc(t,e){let r=Wt(t),n=Wt(e);if(t===e)return{valid:!0,data:t};if(r===A.object&&n===A.object){let s=ne.objectKeys(e),o=ne.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=jc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===A.array&&n===A.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=jc(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===A.date&&n===A.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Yr=class extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(ai(o)||ai(i))return B;let a=jc(o.value,i.value);return a.valid?((ci(o)||ci(i))&&r.dirty(),{status:r.value,value:a.data}):(P(n,{code:E.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(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Yr.create=(t,e,r)=>new Yr({left:t,right:e,typeName:k.ZodIntersection,...K(r)});var Gt=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.array)return P(n,{code:E.invalid_type,expected:A.array,received:n.parsedType}),B;if(n.data.length<this._def.items.length)return P(n,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),B;!this._def.rest&&n.data.length>this._def.items.length&&(P(n,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new xt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>je.mergeArray(r,i)):je.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Gt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Gt({items:t,typeName:k.ZodTuple,rest:null,...K(e)})};var li=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!==A.object)return P(n,{code:E.invalid_type,expected:A.object,received:n.parsedType}),B;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new xt(n,a,n.path,a)),value:i._parse(new xt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?je.mergeObjectAsync(r,s):je.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Y?new t({keyType:e,valueType:r,typeName:k.ZodRecord,...K(n)}):new t({keyType:xr.create(),valueType:e,typeName:k.ZodRecord,...K(r)})}},jn=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!==A.map)return P(n,{code:E.invalid_type,expected:A.map,received:n.parsedType}),B;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new xt(n,a,n.path,[u,"key"])),value:o._parse(new xt(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}}}};jn.create=(t,e,r)=>new jn({valueType:e,keyType:t,typeName:k.ZodMap,...K(r)});var Fn=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.set)return P(n,{code:E.invalid_type,expected:A.set,received:n.parsedType}),B;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(P(n,{code:E.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(P(n,{code:E.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let u=new Set;for(let 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)=>o._parse(new xt(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:L.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:L.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Fn.create=(t,e)=>new Fn({valueType:t,minSize:null,maxSize:null,typeName:k.ZodSet,...K(e)});var di=class t extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==A.function)return P(r,{code:E.invalid_type,expected:A.function,received:r.parsedType}),B;function n(a,c){return Ns({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Nn(),ar].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function s(a,c){return Ns({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Nn(),ar].filter(u=>!!u),issueData:{code:E.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof wr){let a=this;return We(async function(...c){let u=new st([]),l=await a._def.args.parseAsync(c,o).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,o).catch(h=>{throw u.addIssue(s(d,h)),u})})}else{let a=this;return We(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new st([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,o);if(!d.success)throw new st([s(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Gt.create(e).rest(ur.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||Gt.create([]).rest(ur.create()),returns:r||ur.create(),typeName:k.ZodFunction,...K(n)})}},Qr=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})}};Qr.create=(t,e)=>new Qr({getter:t,typeName:k.ZodLazy,...K(e)});var en=class extends Y{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return P(r,{received:r.data,code:E.invalid_literal,expected:this._def.value}),B}return{status:"valid",value:e.data}}get value(){return this._def.value}};en.create=(t,e)=>new en({value:t,typeName:k.ZodLiteral,...K(e)});function zm(t,e){return new tn({values:t,typeName:k.ZodEnum,...K(e)})}var tn=class t extends Y{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return P(r,{expected:ne.joinValues(n),received:r.parsedType,code:E.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 P(r,{received:r.data,code:E.invalid_enum_value,options:n}),B}return We(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})}};tn.create=zm;var rn=class extends Y{_parse(e){let r=ne.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==A.string&&n.parsedType!==A.number){let s=ne.objectValues(r);return P(n,{expected:ne.joinValues(s),received:n.parsedType,code:E.invalid_type}),B}if(this._cache||(this._cache=new Set(ne.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ne.objectValues(r);return P(n,{received:n.data,code:E.invalid_enum_value,options:s}),B}return We(e.data)}get enum(){return this._def.values}};rn.create=(t,e)=>new rn({values:t,typeName:k.ZodNativeEnum,...K(e)});var wr=class extends Y{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==A.promise&&r.common.async===!1)return P(r,{code:E.invalid_type,expected:A.promise,received:r.parsedType}),B;let n=r.parsedType===A.promise?r.data:Promise.resolve(r.data);return We(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};wr.create=(t,e)=>new wr({type:t,typeName:k.ZodPromise,...K(e)});var St=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{P(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return B;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?B:c.status==="dirty"?Br(c.value):r.value==="dirty"?Br(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"?Br(a.value):r.value==="dirty"?Br(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?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(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!vr(i))return B;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>vr(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):B);ne.assertNever(s)}};St.create=(t,e,r)=>new St({schema:t,typeName:k.ZodEffects,effect:e,...K(r)});St.createWithPreprocess=(t,e,r)=>new St({schema:e,effect:{type:"preprocess",transform:t},typeName:k.ZodEffects,...K(r)});var ot=class extends Y{_parse(e){return this._getType(e)===A.undefined?We(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ot.create=(t,e)=>new ot({innerType:t,typeName:k.ZodOptional,...K(e)});var Jt=class extends Y{_parse(e){return this._getType(e)===A.null?We(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Jt.create=(t,e)=>new Jt({innerType:t,typeName:k.ZodNullable,...K(e)});var nn=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===A.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};nn.create=(t,e)=>new nn({innerType:t,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...K(e)});var sn=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Dn(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new st(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new st(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};sn.create=(t,e)=>new sn({innerType:t,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...K(e)});var Zn=class extends Y{_parse(e){if(this._getType(e)!==A.nan){let n=this._getOrReturnCtx(e);return P(n,{code:E.invalid_type,expected:A.nan,received:n.parsedType}),B}return{status:"valid",value:e.data}}};Zn.create=t=>new Zn({typeName:k.ZodNaN,...K(t)});var C0=Symbol("zod_brand"),Ds=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}},zs=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?B:o.status==="dirty"?(r.dirty(),Br(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?B:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:k.ZodPipeline})}},on=class extends Y{_parse(e){let r=this._def.innerType._parse(e),n=s=>(vr(s)&&(s.value=Object.freeze(s.value)),s);return Dn(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};on.create=(t,e)=>new on({innerType:t,typeName:k.ZodReadonly,...K(e)});function Om(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Mm(t,e={},r){return t?Sr.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=Om(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=Om(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):Sr.create()}var I0={object:it.lazycreate},k;(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"})(k||(k={}));var O0=(t,e={message:`Input not instance of ${t.name}`})=>Mm(r=>r instanceof t,e),Lm=xr.create,jm=Hr.create,A0=Zn.create,N0=Vr.create,Fm=Wr.create,D0=Gr.create,z0=Mn.create,M0=Jr.create,L0=Kr.create,j0=Sr.create,F0=ur.create,Z0=Ot.create,U0=Ln.create,q0=lr.create,Fc=it.create,B0=it.strictCreate,H0=Xr.create,V0=ui.create,W0=Yr.create,G0=Gt.create,J0=li.create,K0=jn.create,X0=Fn.create,Y0=di.create,Q0=Qr.create,ew=en.create,tw=tn.create,rw=rn.create,nw=wr.create,sw=St.create,ow=ot.create,iw=Jt.create,aw=St.createWithPreprocess,cw=zs.create,uw=()=>Lm().optional(),lw=()=>jm().optional(),dw=()=>Fm().optional(),pw={string:(t=>xr.create({...t,coerce:!0})),number:(t=>Hr.create({...t,coerce:!0})),boolean:(t=>Wr.create({...t,coerce:!0})),bigint:(t=>Vr.create({...t,coerce:!0})),date:(t=>Gr.create({...t,coerce:!0}))};var fw=B;var mw=Object.freeze({status:"aborted"});function S(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 s=r?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function i(a){var c;let u=r?.Parent?new o:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let 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 dr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},pi={};function yt(t){return t&&Object.assign(pi,t),pi}var se={};As(se,{BIGINT_FORMAT_RANGES:()=>Um,Class:()=>Uc,NUMBER_FORMAT_RANGES:()=>Jc,aborted:()=>cn,allowsEval:()=>Vc,assert:()=>bw,assertEqual:()=>hw,assertIs:()=>yw,assertNever:()=>_w,assertNotEqual:()=>gw,assignProp:()=>Hc,cached:()=>js,captureStackTrace:()=>mi,cleanEnum:()=>Ow,cleanRegex:()=>Zs,clone:()=>_t,createTransparentProxy:()=>kw,defineLazy:()=>ge,esc:()=>an,escapeRegex:()=>Er,extend:()=>Rw,finalizeIssue:()=>At,floatSafeRemainder:()=>Bc,getElementAtPath:()=>vw,getEnumValues:()=>Ls,getLengthableOrigin:()=>Us,getParsedType:()=>Ew,getSizableOrigin:()=>qm,isObject:()=>Un,isPlainObject:()=>qn,issue:()=>Kc,joinValues:()=>fi,jsonStringifyReplacer:()=>qc,merge:()=>Pw,normalizeParams:()=>H,nullish:()=>Fs,numKeys:()=>ww,omit:()=>$w,optionalKeys:()=>Gc,partial:()=>Cw,pick:()=>Tw,prefixIssues:()=>Kt,primitiveTypes:()=>Zm,promiseAllObject:()=>xw,propertyKeyTypes:()=>Wc,randomString:()=>Sw,required:()=>Iw,stringifyPrimitive:()=>hi,unwrapMessage:()=>Ms});function hw(t){return t}function gw(t){return t}function yw(t){}function _w(t){throw new Error}function bw(t){}function Ls(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function fi(t,e="|"){return t.map(r=>hi(r)).join(e)}function qc(t,e){return typeof e=="bigint"?e.toString():e}function js(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Fs(t){return t==null}function Zs(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Bc(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function ge(t,e,r){Object.defineProperty(t,e,{get(){{let s=r();return t[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function Hc(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function vw(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function xw(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let s={};for(let o=0;o<e.length;o++)s[e[o]]=n[o];return s})}function Sw(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 mi=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Un(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Vc=js(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function qn(t){if(Un(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Un(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function ww(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var Ew=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}`)}},Wc=new Set(["string","number","symbol"]),Zm=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Er(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _t(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function H(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 kw(t){let e;return new Proxy({},{get(r,n,s){return e??(e=t()),Reflect.get(e,n,s)},set(r,n,s,o){return e??(e=t()),Reflect.set(e,n,s,o)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,s){return e??(e=t()),Reflect.defineProperty(e,n,s)}})}function hi(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Gc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Jc={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]},Um={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Tw(t,e){let r={},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return _t(t,{...t._zod.def,shape:r,checks:[]})}function $w(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return _t(t,{...t._zod.def,shape:r,checks:[]})}function Rw(t,e){if(!qn(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 Hc(this,"shape",n),n},checks:[]};return _t(t,r)}function Pw(t,e){return _t(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Hc(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function Cw(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=t?new t({type:"optional",innerType:n[o]}):n[o])}else for(let o in n)s[o]=t?new t({type:"optional",innerType:n[o]}):n[o];return _t(e,{...e._zod.def,shape:s,checks:[]})}function Iw(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:n[o]}))}else for(let o in n)s[o]=new t({type:"nonoptional",innerType:n[o]});return _t(e,{...e._zod.def,shape:s,checks:[]})}function cn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Kt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ms(t){return typeof t=="string"?t:t?.message}function At(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=Ms(t.inst?._zod.def?.error?.(t))??Ms(e?.error?.(t))??Ms(r.customError?.(t))??Ms(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function qm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Us(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Kc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Ow(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Uc=class{constructor(...e){}};var Bm=(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,qc,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},gi=S("$ZodError",Bm),qs=S("$ZodError",Bm,{Parent:Error});function Xc(t,e=r=>r.message){let r={},n=[];for(let s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function Yc(t,e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>s({issues:a}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(t),n}var Qc=t=>(e,r,n,s)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new dr;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>At(c,o,yt())));throw mi(a,s?.callee),a}return i.value},eu=Qc(qs),tu=t=>async(e,r,n,s)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>At(c,o,yt())));throw mi(a,s?.callee),a}return i.value},ru=tu(qs),nu=t=>(e,r,n)=>{let s=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new dr;return o.issues.length?{success:!1,error:new(t??gi)(o.issues.map(i=>At(i,s,yt())))}:{success:!0,data:o.value}},un=nu(qs),su=t=>async(e,r,n)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(i=>At(i,s,yt())))}:{success:!0,data:o.value}},ln=su(qs);var Hm=/^[cC][^\s-]{8,}$/,Vm=/^[0-9a-z]+$/,Wm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Gm=/^[0-9a-vA-V]{20}$/,Jm=/^[A-Za-z0-9]{27}$/,Km=/^[a-zA-Z0-9_-]{21}$/,Xm=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Ym=/^([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})$/,ou=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 Qm=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Nw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function eh(){return new RegExp(Nw,"u")}var th=/^(?:(?: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])$/,rh=/^(([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})$/,nh=/^((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])$/,sh=/^(([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])$/,oh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,iu=/^[A-Za-z0-9_-]*$/,ih=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var ah=/^\+(?:[0-9]){6,14}[0-9]$/,ch="(?:(?:\\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])))",uh=new RegExp(`^${ch}$`);function lh(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 dh(t){return new RegExp(`^${lh(t)}$`)}function ph(t){let e=lh({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(`^${ch}T(?:${n})$`)}var fh=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var mh=/^\d+$/,hh=/^-?\d+(?:\.\d+)?/i,gh=/true|false/i,yh=/null/i;var _h=/^[^A-Z]*$/,bh=/^[^a-z]*$/;var Fe=S("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),vh={number:"number",bigint:"bigint",object:"date"},au=S("$ZodCheckLessThan",(t,e)=>{Fe.init(t,e);let r=vh[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),cu=S("$ZodCheckGreaterThan",(t,e)=>{Fe.init(t,e);let r=vh[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),xh=S("$ZodCheckMultipleOf",(t,e)=>{Fe.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):Bc(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})}}),Sh=S("$ZodCheckNumberFormat",(t,e)=>{Fe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,o]=Jc[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=s,a.maximum=o,r&&(a.pattern=mh)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<s&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),a>o&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:t})}});var wh=S("$ZodCheckMaxLength",(t,e)=>{var r;Fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Fs(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let s=n.value;if(s.length<=e.maximum)return;let i=Us(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Eh=S("$ZodCheckMinLength",(t,e)=>{var r;Fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Fs(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let s=n.value;if(s.length>=e.minimum)return;let i=Us(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),kh=S("$ZodCheckLengthEquals",(t,e)=>{var r;Fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Fs(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{let s=n.value,o=s.length;if(o===e.length)return;let i=Us(s),a=o>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Bs=S("$ZodCheckStringFormat",(t,e)=>{var r,n;Fe.init(t,e),t._zod.onattach.push(s=>{let o=s._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Th=S("$ZodCheckRegex",(t,e)=>{Bs.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})}}),$h=S("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=_h),Bs.init(t,e)}),Rh=S("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=bh),Bs.init(t,e)}),Ph=S("$ZodCheckIncludes",(t,e)=>{Fe.init(t,e);let r=Er(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{let o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),Ch=S("$ZodCheckStartsWith",(t,e)=>{Fe.init(t,e);let r=new RegExp(`^${Er(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Ih=S("$ZodCheckEndsWith",(t,e)=>{Fe.init(t,e);let r=new RegExp(`.*${Er(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var Oh=S("$ZodCheckOverwrite",(t,e)=>{Fe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var _i=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(`
|
|
12
|
+
`).filter(i=>i),s=Math.min(...n.map(i=>i.length-i.trimStart().length)),o=n.map(i=>i.slice(s)).map(i=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,r=this?.args,s=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,s.join(`
|
|
13
|
+
`))}};var Nh={major:4,minor:0,patch:0};var fe=S("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Nh;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let s of n)for(let o of s._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let s=(o,i,a)=>{let c=cn(o),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(o))continue}else if(c)continue;let d=o.issues.length,f=l._zod.check(o);if(f instanceof Promise&&a?.async===!1)throw new dr;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,o.issues.length!==d&&(c||(c=cn(o,d)))});else{if(o.issues.length===d)continue;c||(c=cn(o,d))}}return u?u.then(()=>o):o};t._zod.run=(o,i)=>{let a=t._zod.parse(o,i);if(a instanceof Promise){if(i.async===!1)throw new dr;return a.then(c=>s(c,n,i))}return s(a,n,i)}}t["~standard"]={validate:s=>{try{let o=un(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return ln(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Hs=S("$ZodString",(t,e)=>{fe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??fh(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),ye=S("$ZodStringFormat",(t,e)=>{Bs.init(t,e),Hs.init(t,e)}),lu=S("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Ym),ye.init(t,e)}),du=S("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=ou(n))}else e.pattern??(e.pattern=ou());ye.init(t,e)}),pu=S("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Qm),ye.init(t,e)}),fu=S("$ZodURL",(t,e)=>{ye.init(t,e),t._zod.check=r=>{try{let n=r.value,s=new URL(n),o=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:ih.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),mu=S("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=eh()),ye.init(t,e)}),hu=S("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Km),ye.init(t,e)}),gu=S("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Hm),ye.init(t,e)}),yu=S("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Vm),ye.init(t,e)}),_u=S("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Wm),ye.init(t,e)}),bu=S("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Gm),ye.init(t,e)}),vu=S("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Jm),ye.init(t,e)}),Bh=S("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=ph(e)),ye.init(t,e)}),Hh=S("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=uh),ye.init(t,e)}),Vh=S("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=dh(e)),ye.init(t,e)}),Wh=S("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Xm),ye.init(t,e)}),xu=S("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=th),ye.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Su=S("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=rh),ye.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),wu=S("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=nh),ye.init(t,e)}),Eu=S("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=sh),ye.init(t,e),t._zod.check=r=>{let[n,s]=r.value.split("/");try{if(!s)throw new Error;let o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Gh(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var ku=S("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=oh),ye.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Gh(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Dw(t){if(!iu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Gh(r)}var Tu=S("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=iu),ye.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Dw(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),$u=S("$ZodE164",(t,e)=>{e.pattern??(e.pattern=ah),ye.init(t,e)});function zw(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let s=JSON.parse(atob(n));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}var Ru=S("$ZodJWT",(t,e)=>{ye.init(t,e),t._zod.check=r=>{zw(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var vi=S("$ZodNumber",(t,e)=>{fe.init(t,e),t._zod.pattern=t._zod.bag.pattern??hh,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let s=r.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return r;let o=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...o?{received:o}:{}}),r}}),Pu=S("$ZodNumber",(t,e)=>{Sh.init(t,e),vi.init(t,e)}),Cu=S("$ZodBoolean",(t,e)=>{fe.init(t,e),t._zod.pattern=gh,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let s=r.value;return typeof s=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),r}});var Iu=S("$ZodNull",(t,e)=>{fe.init(t,e),t._zod.pattern=yh,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let s=r.value;return s===null||r.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),r}});var Ou=S("$ZodUnknown",(t,e)=>{fe.init(t,e),t._zod.parse=r=>r}),Au=S("$ZodNever",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Dh(t,e,r){t.issues.length&&e.issues.push(...Kt(r,t.issues)),e.value[r]=t.value}var Nu=S("$ZodArray",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),r;r.value=Array(s.length);let o=[];for(let i=0;i<s.length;i++){let a=s[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?o.push(c.then(u=>Dh(u,r,i))):Dh(c,r,i)}return o.length?Promise.all(o).then(()=>r):r}});function bi(t,e,r){t.issues.length&&e.issues.push(...Kt(r,t.issues)),e.value[r]=t.value}function zh(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Kt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var xi=S("$ZodObject",(t,e)=>{fe.init(t,e);let r=js(()=>{let d=Object.keys(e.shape);for(let h of d)if(!(e.shape[h]instanceof fe))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let f=Gc(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});ge(t._zod,"propValues",()=>{let d=e.shape,f={};for(let h in d){let p=d[h]._zod;if(p.values){f[h]??(f[h]=new Set);for(let m of p.values)f[h].add(m)}}return f});let n=d=>{let f=new _i(["shape","payload","ctx"]),h=r.value,p=b=>{let _=an(b);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};f.write("const input = payload.value;");let m=Object.create(null),g=0;for(let b of h.keys)m[b]=`key_${g++}`;f.write("const newResult = {}");for(let b of h.keys)if(h.optionalKeys.has(b)){let _=m[b];f.write(`const ${_} = ${p(b)};`);let x=an(b);f.write(`
|
|
14
|
+
if (${_}.issues.length) {
|
|
15
|
+
if (input[${x}] === undefined) {
|
|
16
|
+
if (${x} in input) {
|
|
17
|
+
newResult[${x}] = undefined;
|
|
18
|
+
}
|
|
19
|
+
} else {
|
|
20
|
+
payload.issues = payload.issues.concat(
|
|
21
|
+
${_}.issues.map((iss) => ({
|
|
22
|
+
...iss,
|
|
23
|
+
path: iss.path ? [${x}, ...iss.path] : [${x}],
|
|
24
|
+
}))
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
} else if (${_}.value === undefined) {
|
|
28
|
+
if (${x} in input) newResult[${x}] = undefined;
|
|
29
|
+
} else {
|
|
30
|
+
newResult[${x}] = ${_}.value;
|
|
31
|
+
}
|
|
32
|
+
`)}else{let _=m[b];f.write(`const ${_} = ${p(b)};`),f.write(`
|
|
33
|
+
if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
|
|
34
|
+
...iss,
|
|
35
|
+
path: iss.path ? [${an(b)}, ...iss.path] : [${an(b)}]
|
|
36
|
+
})));`),f.write(`newResult[${an(b)}] = ${_}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(b,_)=>y(d,b,_)},s,o=Un,i=!pi.jitless,c=i&&Vc.value,u=e.catchall,l;t._zod.parse=(d,f)=>{l??(l=r.value);let h=d.value;if(!o(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)s||(s=n(e.shape)),d=s(d,f);else{d.value={};let _=l.shape;for(let x of l.keys){let w=_[x],I=w._zod.run({value:h[x],issues:[]},f),R=w._zod.optin==="optional"&&w._zod.optout==="optional";I instanceof Promise?p.push(I.then(M=>R?zh(M,d,x,h):bi(M,d,x))):R?zh(I,d,x,h):bi(I,d,x)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;let m=[],g=l.keySet,y=u._zod,b=y.def.type;for(let _ of Object.keys(h)){if(g.has(_))continue;if(b==="never"){m.push(_);continue}let x=y.run({value:h[_],issues:[]},f);x instanceof Promise?p.push(x.then(w=>bi(w,d,_))):bi(x,d,_)}return m.length&&d.issues.push({code:"unrecognized_keys",keys:m,input:h,inst:t}),p.length?Promise.all(p).then(()=>d):d}});function Mh(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(o=>At(o,n,yt())))}),e}var Si=S("$ZodUnion",(t,e)=>{fe.init(t,e),ge(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ge(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ge(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ge(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=>Zs(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1,o=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)o.push(a),s=!0;else{if(a.issues.length===0)return a;o.push(a)}}return s?Promise.all(o).then(i=>Mh(i,r,t,n)):Mh(o,r,t,n)}}),Du=S("$ZodDiscriminatedUnion",(t,e)=>{Si.init(t,e);let r=t._zod.parse;ge(t._zod,"propValues",()=>{let s={};for(let o of e.options){let i=o._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[a,c]of Object.entries(i)){s[a]||(s[a]=new Set);for(let u of c)s[a].add(u)}}return s});let n=js(()=>{let s=e.options,o=new Map;for(let i of s){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,i)}}return o});t._zod.parse=(s,o)=>{let i=s.value;if(!Un(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),s;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(s,o):e.unionFallback?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),s)}}),zu=S("$ZodIntersection",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value,o=e.left._zod.run({value:s,issues:[]},n),i=e.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([c,u])=>Lh(r,c,u)):Lh(r,o,i)}});function uu(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(qn(t)&&qn(e)){let r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),s={...t,...e};for(let o of n){let i=uu(t[o],e[o]);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};s[o]=i.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let s=t[n],o=e[n],i=uu(s,o);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Lh(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),cn(t))return t;let n=uu(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 Mu=S("$ZodRecord",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!qn(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;let o=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:s[c],issues:[]},n);u instanceof Promise?o.push(u.then(l=>{l.issues.length&&r.issues.push(...Kt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Kt(c,u.issues)),r.value[c]=u.value)}let a;for(let c in s)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(s)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>At(u,n,yt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:s[i],issues:[]},n);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&r.issues.push(...Kt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Kt(i,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}});var Lu=S("$ZodEnum",(t,e)=>{fe.init(t,e);let r=Ls(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Wc.has(typeof n)).map(n=>typeof n=="string"?Er(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:t}),n}}),ju=S("$ZodLiteral",(t,e)=>{fe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Er(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}});var Fu=S("$ZodTransform",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(r.value=i,r));if(s instanceof Promise)throw new dr;return r.value=s,r}}),Zu=S("$ZodOptional",(t,e)=>{fe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ge(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ge(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Zs(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)}),Uu=S("$ZodNullable",(t,e)=>{fe.init(t,e),ge(t._zod,"optin",()=>e.innerType._zod.optin),ge(t._zod,"optout",()=>e.innerType._zod.optout),ge(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Zs(r.source)}|null)$`):void 0}),ge(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)}),qu=S("$ZodDefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",ge(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>jh(o,e)):jh(s,e)}});function jh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Bu=S("$ZodPrefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",ge(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))}),Hu=S("$ZodNonOptional",(t,e)=>{fe.init(t,e),ge(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Fh(o,t)):Fh(s,t)}});function Fh(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 Vu=S("$ZodCatch",(t,e)=>{fe.init(t,e),t._zod.optin="optional",ge(t._zod,"optout",()=>e.innerType._zod.optout),ge(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(i=>At(i,n,yt()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>At(o,n,yt()))},input:r.value}),r.issues=[]),r)}});var Wu=S("$ZodPipe",(t,e)=>{fe.init(t,e),ge(t._zod,"values",()=>e.in._zod.values),ge(t._zod,"optin",()=>e.in._zod.optin),ge(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>Zh(o,e,n)):Zh(s,e,n)}});function Zh(t,e,r){return cn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Gu=S("$ZodReadonly",(t,e)=>{fe.init(t,e),ge(t._zod,"propValues",()=>e.innerType._zod.propValues),ge(t._zod,"values",()=>e.innerType._zod.values),ge(t._zod,"optin",()=>e.innerType._zod.optin),ge(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(Uh):Uh(s)}});function Uh(t){return t.value=Object.freeze(t.value),t}var Ju=S("$ZodCustom",(t,e)=>{Fe.init(t,e),fe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(o=>qh(o,r,n,t));qh(s,r,n,t)}});function qh(t,e,r,n){if(!t){let s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push(Kc(s))}}var Mw=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},Lw=()=>{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 ${Mw(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${hi(n.values[0])}`:`Invalid option: expected one of ${fi(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",o=e(n.origin);return o?`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",o=e(n.origin);return o?`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${o.unit}`:`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${fi(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 Jh(){return{localeError:Lw()}}var Vs=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 Kh(){return new Vs}var kr=Kh();function Ku(t,e){return new t({type:"string",...H(e)})}function Xu(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...H(e)})}function wi(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...H(e)})}function Yu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...H(e)})}function Qu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...H(e)})}function el(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...H(e)})}function tl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...H(e)})}function rl(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...H(e)})}function nl(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...H(e)})}function sl(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...H(e)})}function ol(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...H(e)})}function il(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...H(e)})}function al(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...H(e)})}function cl(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...H(e)})}function ul(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...H(e)})}function ll(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...H(e)})}function dl(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...H(e)})}function pl(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...H(e)})}function fl(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...H(e)})}function ml(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...H(e)})}function hl(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...H(e)})}function gl(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...H(e)})}function yl(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...H(e)})}function Xh(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...H(e)})}function Yh(t,e){return new t({type:"string",format:"date",check:"string_format",...H(e)})}function Qh(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...H(e)})}function eg(t,e){return new t({type:"string",format:"duration",check:"string_format",...H(e)})}function _l(t,e){return new t({type:"number",checks:[],...H(e)})}function bl(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...H(e)})}function vl(t,e){return new t({type:"boolean",...H(e)})}function xl(t,e){return new t({type:"null",...H(e)})}function Sl(t){return new t({type:"unknown"})}function wl(t,e){return new t({type:"never",...H(e)})}function Ei(t,e){return new au({check:"less_than",...H(e),value:t,inclusive:!1})}function Ws(t,e){return new au({check:"less_than",...H(e),value:t,inclusive:!0})}function ki(t,e){return new cu({check:"greater_than",...H(e),value:t,inclusive:!1})}function Gs(t,e){return new cu({check:"greater_than",...H(e),value:t,inclusive:!0})}function Ti(t,e){return new xh({check:"multiple_of",...H(e),value:t})}function $i(t,e){return new wh({check:"max_length",...H(e),maximum:t})}function Bn(t,e){return new Eh({check:"min_length",...H(e),minimum:t})}function Ri(t,e){return new kh({check:"length_equals",...H(e),length:t})}function El(t,e){return new Th({check:"string_format",format:"regex",...H(e),pattern:t})}function kl(t){return new $h({check:"string_format",format:"lowercase",...H(t)})}function Tl(t){return new Rh({check:"string_format",format:"uppercase",...H(t)})}function $l(t,e){return new Ph({check:"string_format",format:"includes",...H(e),includes:t})}function Rl(t,e){return new Ch({check:"string_format",format:"starts_with",...H(e),prefix:t})}function Pl(t,e){return new Ih({check:"string_format",format:"ends_with",...H(e),suffix:t})}function dn(t){return new Oh({check:"overwrite",tx:t})}function Cl(t){return dn(e=>e.normalize(t))}function Il(){return dn(t=>t.trim())}function Ol(){return dn(t=>t.toLowerCase())}function Al(){return dn(t=>t.toUpperCase())}function tg(t,e,r){return new t({type:"array",element:e,...H(r)})}function Nl(t,e,r){let n=H(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Dl(t,e,r){return new t({type:"custom",check:"custom",fn:e,...H(r)})}var Pi=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??kr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let s=e._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let 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(s.type){case"string":{let p=h;p.type="string";let{minimum:m,maximum:g,format:y,patterns:b,contentEncoding:_}=e._zod.bag;if(typeof m=="number"&&(p.minLength=m),typeof g=="number"&&(p.maxLength=g),y&&(p.format=o[y]??y,p.format===""&&delete p.format),_&&(p.contentEncoding=_),b&&b.size>0){let x=[...b];x.length===1?p.pattern=x[0].source:x.length>1&&(a.schema.allOf=[...x.map(w=>({...this.target==="draft-7"?{type:"string"}:{},pattern:w.source}))])}break}case"number":{let p=h,{minimum:m,maximum:g,format:y,multipleOf:b,exclusiveMaximum:_,exclusiveMinimum:x}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof x=="number"&&(p.exclusiveMinimum=x),typeof m=="number"&&(p.minimum=m,typeof x=="number"&&(x>=m?delete p.minimum:delete p.exclusiveMinimum)),typeof _=="number"&&(p.exclusiveMaximum=_),typeof g=="number"&&(p.maximum=g,typeof _=="number"&&(_<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof b=="number"&&(p.multipleOf=b);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(s.element,{...d,path:[...d.path,"items"]});break}case"object":{let p=h;p.type="object",p.properties={};let m=s.shape;for(let b in m)p.properties[b]=this.process(m[b],{...d,path:[...d.path,"properties",b]});let g=new Set(Object.keys(m)),y=new Set([...g].filter(b=>{let _=s.shape[b]._zod;return this.io==="input"?_.optin===void 0:_.optout===void 0}));y.size>0&&(p.required=Array.from(y)),s.catchall?._zod.def.type==="never"?p.additionalProperties=!1:s.catchall?s.catchall&&(p.additionalProperties=this.process(s.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=h;p.anyOf=s.options.map((m,g)=>this.process(m,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let p=h,m=this.process(s.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(s.right,{...d,path:[...d.path,"allOf",1]}),y=_=>"allOf"in _&&Object.keys(_).length===1,b=[...y(m)?m.allOf:[m],...y(g)?g.allOf:[g]];p.allOf=b;break}case"tuple":{let p=h;p.type="array";let m=s.items.map((b,_)=>this.process(b,{...d,path:[...d.path,"prefixItems",_]}));if(this.target==="draft-2020-12"?p.prefixItems=m:p.items=m,s.rest){let b=this.process(s.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=b:p.additionalItems=b}s.rest&&(p.items=this.process(s.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(s.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(s.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=Ls(s.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 s.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");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:b}=e._zod.bag;g!==void 0&&(m.minLength=g),y!==void 0&&(m.maxLength=y),b?b.length===1?(m.contentMediaType=b[0],Object.assign(p,m)):p.anyOf=b.map(_=>({...m,contentMediaType:_})):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(s.innerType,d);h.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,d),a.ref=s.innerType;break}case"success":{let p=h;p.type="boolean";break}case"default":{this.process(s.innerType,d),a.ref=s.innerType,h.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,d),a.ref=s.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,d),a.ref=s.innerType;let p;try{p=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}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"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(p,d),a.ref=p;break}case"readonly":{this.process(s.innerType,d),a.ref=s.innerType,h.readOnly=!0;break}case"promise":{this.process(s.innerType,d),a.ref=s.innerType;break}case"optional":{this.process(s.innerType,d),a.ref=s.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"&&Ne(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=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??(b=>b);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]===s)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}=o(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>
|
|
37
|
+
|
|
38
|
+
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,s.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 zl(t,e){if(t instanceof Vs){let n=new Pi(e),s={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let o={},i={registry:t,uri:e?.uri,defs:s};for(let a of t._idmap.entries()){let[c,u]=a;o[c]=n.emit(u,{...e,external:i})}if(Object.keys(s).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[a]:s}}return{schemas:o}}let r=new Pi(e);return r.process(t),r.emit(t,e)}function Ne(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let s=t._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ne(s.element,r);case"object":{for(let o in s.shape)if(Ne(s.shape[o],r))return!0;return!1}case"union":{for(let o of s.options)if(Ne(o,r))return!0;return!1}case"intersection":return Ne(s.left,r)||Ne(s.right,r);case"tuple":{for(let o of s.items)if(Ne(o,r))return!0;return!!(s.rest&&Ne(s.rest,r))}case"record":return Ne(s.keyType,r)||Ne(s.valueType,r);case"map":return Ne(s.keyType,r)||Ne(s.valueType,r);case"set":return Ne(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ne(s.innerType,r);case"lazy":return Ne(s.getter(),r);case"default":return Ne(s.innerType,r);case"prefault":return Ne(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ne(s.in,r)||Ne(s.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${s.type}`)}var bE=S("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");fe.init(t,e),t.def=e,t.parse=(r,n)=>eu(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>un(t,r,n),t.parseAsync=async(r,n)=>ru(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>ln(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)=>_t(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var vE=S("ZodMiniObject",(t,e)=>{xi.init(t,e),bE.init(t,e),se.defineLazy(t,"shape",()=>e.shape)});function Ml(t,e){let r={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new vE(r)}function Xt(t){return!!t._zod}function fn(t){let e=Object.values(t);if(e.length===0)return Ml({});let r=e.every(Xt),n=e.every(s=>!Xt(s));if(r)return Ml(t);if(n)return Fc(t);throw new Error("Mixed Zod versions detected in object shape.")}function Tr(t,e){return Xt(t)?un(t,e):t.safeParse(e)}async function Ci(t,e){return Xt(t)?await ln(t,e):await t.safeParseAsync(e)}function $r(t){if(!t)return;let e;if(Xt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Hn(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return fn(t)}}if(Xt(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 SE(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Ii(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${SE(e.path)}`:e.message).join(`
|
|
39
|
+
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function ng(t){return t.description}function sg(t){if(Xt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Vn(t){if(Xt(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Js={};As(Js,{ZodISODate:()=>ig,ZodISODateTime:()=>og,ZodISODuration:()=>cg,ZodISOTime:()=>ag,date:()=>jl,datetime:()=>Ll,duration:()=>Zl,time:()=>Fl});var og=S("ZodISODateTime",(t,e)=>{Bh.init(t,e),we.init(t,e)});function Ll(t){return Xh(og,t)}var ig=S("ZodISODate",(t,e)=>{Hh.init(t,e),we.init(t,e)});function jl(t){return Yh(ig,t)}var ag=S("ZodISOTime",(t,e)=>{Vh.init(t,e),we.init(t,e)});function Fl(t){return Qh(ag,t)}var cg=S("ZodISODuration",(t,e)=>{Wh.init(t,e),we.init(t,e)});function Zl(t){return eg(cg,t)}var ug=(t,e)=>{gi.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Yc(t,r)},flatten:{value:r=>Xc(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},H1=S("ZodError",ug),Ks=S("ZodError",ug,{Parent:Error});var lg=Qc(Ks),dg=tu(Ks),pg=nu(Ks),fg=su(Ks);var $e=S("ZodType",(t,e)=>(fe.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)=>_t(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>lg(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>pg(t,r,n),t.parseAsync=async(r,n)=>dg(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>fg(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(_k(r,n)),t.superRefine=r=>t.check(bk(r)),t.overwrite=r=>t.check(dn(r)),t.optional=()=>ke(t),t.nullable=()=>gg(t),t.nullish=()=>ke(gg(t)),t.nonoptional=r=>dk(t,r),t.array=()=>oe(t),t.or=r=>be([t,r]),t.and=r=>Ai(t,r),t.transform=r=>ql(t,Sg(r)),t.default=r=>ck(t,r),t.prefault=r=>lk(t,r),t.catch=r=>fk(t,r),t.pipe=r=>ql(t,r),t.readonly=()=>gk(t),t.describe=r=>{let n=t.clone();return kr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return kr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return kr.get(t);let n=t.clone();return kr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),yg=S("_ZodString",(t,e)=>{Hs.init(t,e),$e.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(El(...n)),t.includes=(...n)=>t.check($l(...n)),t.startsWith=(...n)=>t.check(Rl(...n)),t.endsWith=(...n)=>t.check(Pl(...n)),t.min=(...n)=>t.check(Bn(...n)),t.max=(...n)=>t.check($i(...n)),t.length=(...n)=>t.check(Ri(...n)),t.nonempty=(...n)=>t.check(Bn(1,...n)),t.lowercase=n=>t.check(kl(n)),t.uppercase=n=>t.check(Tl(n)),t.trim=()=>t.check(Il()),t.normalize=(...n)=>t.check(Cl(...n)),t.toLowerCase=()=>t.check(Ol()),t.toUpperCase=()=>t.check(Al())}),CE=S("ZodString",(t,e)=>{Hs.init(t,e),yg.init(t,e),t.email=r=>t.check(Xu(IE,r)),t.url=r=>t.check(rl(OE,r)),t.jwt=r=>t.check(yl(WE,r)),t.emoji=r=>t.check(nl(AE,r)),t.guid=r=>t.check(wi(mg,r)),t.uuid=r=>t.check(Yu(Oi,r)),t.uuidv4=r=>t.check(Qu(Oi,r)),t.uuidv6=r=>t.check(el(Oi,r)),t.uuidv7=r=>t.check(tl(Oi,r)),t.nanoid=r=>t.check(sl(NE,r)),t.guid=r=>t.check(wi(mg,r)),t.cuid=r=>t.check(ol(DE,r)),t.cuid2=r=>t.check(il(zE,r)),t.ulid=r=>t.check(al(ME,r)),t.base64=r=>t.check(ml(BE,r)),t.base64url=r=>t.check(hl(HE,r)),t.xid=r=>t.check(cl(LE,r)),t.ksuid=r=>t.check(ul(jE,r)),t.ipv4=r=>t.check(ll(FE,r)),t.ipv6=r=>t.check(dl(ZE,r)),t.cidrv4=r=>t.check(pl(UE,r)),t.cidrv6=r=>t.check(fl(qE,r)),t.e164=r=>t.check(gl(VE,r)),t.datetime=r=>t.check(Ll(r)),t.date=r=>t.check(jl(r)),t.time=r=>t.check(Fl(r)),t.duration=r=>t.check(Zl(r))});function v(t){return Ku(CE,t)}var we=S("ZodStringFormat",(t,e)=>{ye.init(t,e),yg.init(t,e)}),IE=S("ZodEmail",(t,e)=>{pu.init(t,e),we.init(t,e)});var mg=S("ZodGUID",(t,e)=>{lu.init(t,e),we.init(t,e)});var Oi=S("ZodUUID",(t,e)=>{du.init(t,e),we.init(t,e)});var OE=S("ZodURL",(t,e)=>{fu.init(t,e),we.init(t,e)});var AE=S("ZodEmoji",(t,e)=>{mu.init(t,e),we.init(t,e)});var NE=S("ZodNanoID",(t,e)=>{hu.init(t,e),we.init(t,e)});var DE=S("ZodCUID",(t,e)=>{gu.init(t,e),we.init(t,e)});var zE=S("ZodCUID2",(t,e)=>{yu.init(t,e),we.init(t,e)});var ME=S("ZodULID",(t,e)=>{_u.init(t,e),we.init(t,e)});var LE=S("ZodXID",(t,e)=>{bu.init(t,e),we.init(t,e)});var jE=S("ZodKSUID",(t,e)=>{vu.init(t,e),we.init(t,e)});var FE=S("ZodIPv4",(t,e)=>{xu.init(t,e),we.init(t,e)});var ZE=S("ZodIPv6",(t,e)=>{Su.init(t,e),we.init(t,e)});var UE=S("ZodCIDRv4",(t,e)=>{wu.init(t,e),we.init(t,e)});var qE=S("ZodCIDRv6",(t,e)=>{Eu.init(t,e),we.init(t,e)});var BE=S("ZodBase64",(t,e)=>{ku.init(t,e),we.init(t,e)});var HE=S("ZodBase64URL",(t,e)=>{Tu.init(t,e),we.init(t,e)});var VE=S("ZodE164",(t,e)=>{$u.init(t,e),we.init(t,e)});var WE=S("ZodJWT",(t,e)=>{Ru.init(t,e),we.init(t,e)});var _g=S("ZodNumber",(t,e)=>{vi.init(t,e),$e.init(t,e),t.gt=(n,s)=>t.check(ki(n,s)),t.gte=(n,s)=>t.check(Gs(n,s)),t.min=(n,s)=>t.check(Gs(n,s)),t.lt=(n,s)=>t.check(Ei(n,s)),t.lte=(n,s)=>t.check(Ws(n,s)),t.max=(n,s)=>t.check(Ws(n,s)),t.int=n=>t.check(hg(n)),t.safe=n=>t.check(hg(n)),t.positive=n=>t.check(ki(0,n)),t.nonnegative=n=>t.check(Gs(0,n)),t.negative=n=>t.check(Ei(0,n)),t.nonpositive=n=>t.check(Ws(0,n)),t.multipleOf=(n,s)=>t.check(Ti(n,s)),t.step=(n,s)=>t.check(Ti(n,s)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function pe(t){return _l(_g,t)}var GE=S("ZodNumberFormat",(t,e)=>{Pu.init(t,e),_g.init(t,e)});function hg(t){return bl(GE,t)}var JE=S("ZodBoolean",(t,e)=>{Cu.init(t,e),$e.init(t,e)});function Le(t){return vl(JE,t)}var KE=S("ZodNull",(t,e)=>{Iu.init(t,e),$e.init(t,e)});function bg(t){return xl(KE,t)}var XE=S("ZodUnknown",(t,e)=>{Ou.init(t,e),$e.init(t,e)});function Ee(){return Sl(XE)}var YE=S("ZodNever",(t,e)=>{Au.init(t,e),$e.init(t,e)});function QE(t){return wl(YE,t)}var ek=S("ZodArray",(t,e)=>{Nu.init(t,e),$e.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Bn(r,n)),t.nonempty=r=>t.check(Bn(1,r)),t.max=(r,n)=>t.check($i(r,n)),t.length=(r,n)=>t.check(Ri(r,n)),t.unwrap=()=>t.element});function oe(t,e){return tg(ek,t,e)}var vg=S("ZodObject",(t,e)=>{xi.init(t,e),$e.init(t,e),se.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>at(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ee()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ee()}),t.strict=()=>t.clone({...t._zod.def,catchall:QE()}),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(wg,t,r[0]),t.required=(...r)=>se.required(Eg,t,r[0])});function N(t,e){let r={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new vg(r)}function Ye(t,e){return new vg({type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},catchall:Ee(),...se.normalizeParams(e)})}var xg=S("ZodUnion",(t,e)=>{Si.init(t,e),$e.init(t,e),t.options=e.options});function be(t,e){return new xg({type:"union",options:t,...se.normalizeParams(e)})}var tk=S("ZodDiscriminatedUnion",(t,e)=>{xg.init(t,e),Du.init(t,e)});function Bl(t,e,r){return new tk({type:"union",options:e,discriminator:t,...se.normalizeParams(r)})}var rk=S("ZodIntersection",(t,e)=>{zu.init(t,e),$e.init(t,e)});function Ai(t,e){return new rk({type:"intersection",left:t,right:e})}var nk=S("ZodRecord",(t,e)=>{Mu.init(t,e),$e.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function _e(t,e,r){return new nk({type:"record",keyType:t,valueType:e,...se.normalizeParams(r)})}var Ul=S("ZodEnum",(t,e)=>{Lu.init(t,e),$e.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ul({...e,checks:[],...se.normalizeParams(s),entries:o})},t.exclude=(n,s)=>{let o={...e.entries};for(let i of n)if(r.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new Ul({...e,checks:[],...se.normalizeParams(s),entries:o})}});function at(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Ul({type:"enum",entries:r,...se.normalizeParams(e)})}var sk=S("ZodLiteral",(t,e)=>{ju.init(t,e),$e.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 Z(t,e){return new sk({type:"literal",values:Array.isArray(t)?t:[t],...se.normalizeParams(e)})}var ok=S("ZodTransform",(t,e)=>{Fu.init(t,e),$e.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(se.issue(o,r.value,e));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(se.issue(i))}};let s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});function Sg(t){return new ok({type:"transform",transform:t})}var wg=S("ZodOptional",(t,e)=>{Zu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ke(t){return new wg({type:"optional",innerType:t})}var ik=S("ZodNullable",(t,e)=>{Uu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});function gg(t){return new ik({type:"nullable",innerType:t})}var ak=S("ZodDefault",(t,e)=>{qu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function ck(t,e){return new ak({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var uk=S("ZodPrefault",(t,e)=>{Bu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});function lk(t,e){return new uk({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Eg=S("ZodNonOptional",(t,e)=>{Hu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType});function dk(t,e){return new Eg({type:"nonoptional",innerType:t,...se.normalizeParams(e)})}var pk=S("ZodCatch",(t,e)=>{Vu.init(t,e),$e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function fk(t,e){return new pk({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var mk=S("ZodPipe",(t,e)=>{Wu.init(t,e),$e.init(t,e),t.in=e.in,t.out=e.out});function ql(t,e){return new mk({type:"pipe",in:t,out:e})}var hk=S("ZodReadonly",(t,e)=>{Gu.init(t,e),$e.init(t,e)});function gk(t){return new hk({type:"readonly",innerType:t})}var kg=S("ZodCustom",(t,e)=>{Ju.init(t,e),$e.init(t,e)});function yk(t){let e=new Fe({check:"custom"});return e._zod.check=t,e}function Tg(t,e){return Nl(kg,t??(()=>!0),e)}function _k(t,e={}){return Dl(kg,t,e)}function bk(t){let e=yk(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(se.issue(n,r.value,e._zod.def));else{let s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(se.issue(s))}},t(r.value,r)));return e}function Hl(t,e){return ql(Sg(t),e)}yt(Jh());var Wl="2025-11-25";var $g=[Wl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Rr="io.modelcontextprotocol/related-task",Di="2.0",De=Tg(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Rg=be([v(),pe().int()]),Pg=v(),oL=Ye({ttl:pe().optional(),pollInterval:pe().optional()}),vk=N({ttl:pe().optional()}),xk=N({taskId:v()}),Gl=Ye({progressToken:Rg.optional(),[Rr]:xk.optional()}),bt=N({_meta:Gl.optional()}),Xs=bt.extend({task:vk.optional()}),Cg=t=>Xs.safeParse(t).success,Ze=N({method:v(),params:bt.loose().optional()}),wt=N({_meta:Gl.optional()}),Et=N({method:v(),params:wt.loose().optional()}),Ue=Ye({_meta:Gl.optional()}),zi=be([v(),pe().int()]),Ig=N({jsonrpc:Z(Di),id:zi,...Ze.shape}).strict(),Jl=t=>Ig.safeParse(t).success,Og=N({jsonrpc:Z(Di),...Et.shape}).strict(),Ag=t=>Og.safeParse(t).success,Kl=N({jsonrpc:Z(Di),id:zi,result:Ue}).strict(),Ys=t=>Kl.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 Xl=N({jsonrpc:Z(Di),id:zi.optional(),error:N({code:pe().int(),message:v(),data:Ee().optional()})}).strict();var Ng=t=>Xl.safeParse(t).success;var Dg=be([Ig,Og,Kl,Xl]),iL=be([Kl,Xl]),Mi=Ue.strict(),Sk=wt.extend({requestId:zi.optional(),reason:v().optional()}),Li=Et.extend({method:Z("notifications/cancelled"),params:Sk}),wk=N({src:v(),mimeType:v().optional(),sizes:oe(v()).optional(),theme:at(["light","dark"]).optional()}),Qs=N({icons:oe(wk).optional()}),Wn=N({name:v(),title:v().optional()}),zg=Wn.extend({...Wn.shape,...Qs.shape,version:v(),websiteUrl:v().optional(),description:v().optional()}),Ek=Ai(N({applyDefaults:Le().optional()}),_e(v(),Ee())),kk=Hl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ai(N({form:Ek.optional(),url:De.optional()}),_e(v(),Ee()).optional())),Tk=Ye({list:De.optional(),cancel:De.optional(),requests:Ye({sampling:Ye({createMessage:De.optional()}).optional(),elicitation:Ye({create:De.optional()}).optional()}).optional()}),$k=Ye({list:De.optional(),cancel:De.optional(),requests:Ye({tools:Ye({call:De.optional()}).optional()}).optional()}),Rk=N({experimental:_e(v(),De).optional(),sampling:N({context:De.optional(),tools:De.optional()}).optional(),elicitation:kk.optional(),roots:N({listChanged:Le().optional()}).optional(),tasks:Tk.optional(),extensions:_e(v(),De).optional()}),Pk=bt.extend({protocolVersion:v(),capabilities:Rk,clientInfo:zg}),Yl=Ze.extend({method:Z("initialize"),params:Pk});var Ck=N({experimental:_e(v(),De).optional(),logging:De.optional(),completions:De.optional(),prompts:N({listChanged:Le().optional()}).optional(),resources:N({subscribe:Le().optional(),listChanged:Le().optional()}).optional(),tools:N({listChanged:Le().optional()}).optional(),tasks:$k.optional(),extensions:_e(v(),De).optional()}),Ik=Ue.extend({protocolVersion:v(),capabilities:Ck,serverInfo:zg,instructions:v().optional()}),Ql=Et.extend({method:Z("notifications/initialized"),params:wt.optional()});var ji=Ze.extend({method:Z("ping"),params:bt.optional()}),Ok=N({progress:pe(),total:ke(pe()),message:ke(v())}),Ak=N({...wt.shape,...Ok.shape,progressToken:Rg}),Fi=Et.extend({method:Z("notifications/progress"),params:Ak}),Nk=bt.extend({cursor:Pg.optional()}),eo=Ze.extend({params:Nk.optional()}),to=Ue.extend({nextCursor:Pg.optional()}),Dk=at(["working","input_required","completed","failed","cancelled"]),ro=N({taskId:v(),status:Dk,ttl:be([pe(),bg()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:ke(pe()),statusMessage:ke(v())}),Gn=Ue.extend({task:ro}),zk=wt.merge(ro),no=Et.extend({method:Z("notifications/tasks/status"),params:zk}),Zi=Ze.extend({method:Z("tasks/get"),params:bt.extend({taskId:v()})}),Ui=Ue.merge(ro),qi=Ze.extend({method:Z("tasks/result"),params:bt.extend({taskId:v()})}),aL=Ue.loose(),Bi=eo.extend({method:Z("tasks/list")}),Hi=to.extend({tasks:oe(ro)}),Vi=Ze.extend({method:Z("tasks/cancel"),params:bt.extend({taskId:v()})}),Mg=Ue.merge(ro),Lg=N({uri:v(),mimeType:ke(v()),_meta:_e(v(),Ee()).optional()}),jg=Lg.extend({text:v()}),ed=v().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Fg=Lg.extend({blob:ed}),so=at(["user","assistant"]),Jn=N({audience:oe(so).optional(),priority:pe().min(0).max(1).optional(),lastModified:Js.datetime({offset:!0}).optional()}),Zg=N({...Wn.shape,...Qs.shape,uri:v(),description:ke(v()),mimeType:ke(v()),size:ke(pe()),annotations:Jn.optional(),_meta:ke(Ye({}))}),Mk=N({...Wn.shape,...Qs.shape,uriTemplate:v(),description:ke(v()),mimeType:ke(v()),annotations:Jn.optional(),_meta:ke(Ye({}))}),Kn=eo.extend({method:Z("resources/list")}),Lk=to.extend({resources:oe(Zg)}),Xn=eo.extend({method:Z("resources/templates/list")}),jk=to.extend({resourceTemplates:oe(Mk)}),td=bt.extend({uri:v()}),Fk=td,Wi=Ze.extend({method:Z("resources/read"),params:Fk}),Zk=Ue.extend({contents:oe(be([jg,Fg]))}),Uk=Et.extend({method:Z("notifications/resources/list_changed"),params:wt.optional()}),qk=td,Bk=Ze.extend({method:Z("resources/subscribe"),params:qk}),Hk=td,Vk=Ze.extend({method:Z("resources/unsubscribe"),params:Hk}),Wk=wt.extend({uri:v()}),Gk=Et.extend({method:Z("notifications/resources/updated"),params:Wk}),Jk=N({name:v(),description:ke(v()),required:ke(Le())}),Kk=N({...Wn.shape,...Qs.shape,description:ke(v()),arguments:ke(oe(Jk)),_meta:ke(Ye({}))}),Yn=eo.extend({method:Z("prompts/list")}),Xk=to.extend({prompts:oe(Kk)}),Yk=bt.extend({name:v(),arguments:_e(v(),v()).optional()}),Gi=Ze.extend({method:Z("prompts/get"),params:Yk}),rd=N({type:Z("text"),text:v(),annotations:Jn.optional(),_meta:_e(v(),Ee()).optional()}),nd=N({type:Z("image"),data:ed,mimeType:v(),annotations:Jn.optional(),_meta:_e(v(),Ee()).optional()}),sd=N({type:Z("audio"),data:ed,mimeType:v(),annotations:Jn.optional(),_meta:_e(v(),Ee()).optional()}),Qk=N({type:Z("tool_use"),name:v(),id:v(),input:_e(v(),Ee()),_meta:_e(v(),Ee()).optional()}),eT=N({type:Z("resource"),resource:be([jg,Fg]),annotations:Jn.optional(),_meta:_e(v(),Ee()).optional()}),tT=Zg.extend({type:Z("resource_link")}),od=be([rd,nd,sd,tT,eT]),rT=N({role:so,content:od}),nT=Ue.extend({description:v().optional(),messages:oe(rT)}),sT=Et.extend({method:Z("notifications/prompts/list_changed"),params:wt.optional()}),oT=N({title:v().optional(),readOnlyHint:Le().optional(),destructiveHint:Le().optional(),idempotentHint:Le().optional(),openWorldHint:Le().optional()}),iT=N({taskSupport:at(["required","optional","forbidden"]).optional()}),Ug=N({...Wn.shape,...Qs.shape,description:v().optional(),inputSchema:N({type:Z("object"),properties:_e(v(),De).optional(),required:oe(v()).optional()}).catchall(Ee()),outputSchema:N({type:Z("object"),properties:_e(v(),De).optional(),required:oe(v()).optional()}).catchall(Ee()).optional(),annotations:oT.optional(),execution:iT.optional(),_meta:_e(v(),Ee()).optional()}),mn=eo.extend({method:Z("tools/list")}),aT=to.extend({tools:oe(Ug)}),Ji=Ue.extend({content:oe(od).default([]),structuredContent:_e(v(),Ee()).optional(),isError:Le().optional()}),cL=Ji.or(Ue.extend({toolResult:Ee()})),cT=Xs.extend({name:v(),arguments:_e(v(),Ee()).optional()}),Qn=Ze.extend({method:Z("tools/call"),params:cT}),uT=Et.extend({method:Z("notifications/tools/list_changed"),params:wt.optional()}),uL=N({autoRefresh:Le().default(!0),debounceMs:pe().int().nonnegative().default(300)}),oo=at(["debug","info","notice","warning","error","critical","alert","emergency"]),lT=bt.extend({level:oo}),id=Ze.extend({method:Z("logging/setLevel"),params:lT}),dT=wt.extend({level:oo,logger:v().optional(),data:Ee()}),pT=Et.extend({method:Z("notifications/message"),params:dT}),fT=N({name:v().optional()}),mT=N({hints:oe(fT).optional(),costPriority:pe().min(0).max(1).optional(),speedPriority:pe().min(0).max(1).optional(),intelligencePriority:pe().min(0).max(1).optional()}),hT=N({mode:at(["auto","required","none"]).optional()}),gT=N({type:Z("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:oe(od).default([]),structuredContent:N({}).loose().optional(),isError:Le().optional(),_meta:_e(v(),Ee()).optional()}),yT=Bl("type",[rd,nd,sd]),Ni=Bl("type",[rd,nd,sd,Qk,gT]),_T=N({role:so,content:be([Ni,oe(Ni)]),_meta:_e(v(),Ee()).optional()}),bT=Xs.extend({messages:oe(_T),modelPreferences:mT.optional(),systemPrompt:v().optional(),includeContext:at(["none","thisServer","allServers"]).optional(),temperature:pe().optional(),maxTokens:pe().int(),stopSequences:oe(v()).optional(),metadata:De.optional(),tools:oe(Ug).optional(),toolChoice:hT.optional()}),vT=Ze.extend({method:Z("sampling/createMessage"),params:bT}),io=Ue.extend({model:v(),stopReason:ke(at(["endTurn","stopSequence","maxTokens"]).or(v())),role:so,content:yT}),ad=Ue.extend({model:v(),stopReason:ke(at(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:so,content:be([Ni,oe(Ni)])}),xT=N({type:Z("boolean"),title:v().optional(),description:v().optional(),default:Le().optional()}),ST=N({type:Z("string"),title:v().optional(),description:v().optional(),minLength:pe().optional(),maxLength:pe().optional(),format:at(["email","uri","date","date-time"]).optional(),default:v().optional()}),wT=N({type:at(["number","integer"]),title:v().optional(),description:v().optional(),minimum:pe().optional(),maximum:pe().optional(),default:pe().optional()}),ET=N({type:Z("string"),title:v().optional(),description:v().optional(),enum:oe(v()),default:v().optional()}),kT=N({type:Z("string"),title:v().optional(),description:v().optional(),oneOf:oe(N({const:v(),title:v()})),default:v().optional()}),TT=N({type:Z("string"),title:v().optional(),description:v().optional(),enum:oe(v()),enumNames:oe(v()).optional(),default:v().optional()}),$T=be([ET,kT]),RT=N({type:Z("array"),title:v().optional(),description:v().optional(),minItems:pe().optional(),maxItems:pe().optional(),items:N({type:Z("string"),enum:oe(v())}),default:oe(v()).optional()}),PT=N({type:Z("array"),title:v().optional(),description:v().optional(),minItems:pe().optional(),maxItems:pe().optional(),items:N({anyOf:oe(N({const:v(),title:v()}))}),default:oe(v()).optional()}),CT=be([RT,PT]),IT=be([TT,$T,CT]),OT=be([IT,xT,ST,wT]),AT=Xs.extend({mode:Z("form").optional(),message:v(),requestedSchema:N({type:Z("object"),properties:_e(v(),OT),required:oe(v()).optional()})}),NT=Xs.extend({mode:Z("url"),message:v(),elicitationId:v(),url:v().url()}),DT=be([AT,NT]),zT=Ze.extend({method:Z("elicitation/create"),params:DT}),MT=wt.extend({elicitationId:v()}),LT=Et.extend({method:Z("notifications/elicitation/complete"),params:MT}),es=Ue.extend({action:at(["accept","decline","cancel"]),content:Hl(t=>t===null?void 0:t,_e(v(),be([v(),pe(),Le(),oe(v())])).optional())}),jT=N({type:Z("ref/resource"),uri:v()});var FT=N({type:Z("ref/prompt"),name:v()}),ZT=bt.extend({ref:be([FT,jT]),argument:N({name:v(),value:v()}),context:N({arguments:_e(v(),v()).optional()}).optional()}),Ki=Ze.extend({method:Z("completion/complete"),params:ZT});function qg(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Bg(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var UT=Ue.extend({completion:Ye({values:oe(v()).max(100),total:ke(pe().int()),hasMore:ke(Le())})}),qT=N({uri:v().startsWith("file://"),name:v().optional(),_meta:_e(v(),Ee()).optional()}),BT=Ze.extend({method:Z("roots/list"),params:bt.optional()}),cd=Ue.extend({roots:oe(qT)}),HT=Et.extend({method:Z("notifications/roots/list_changed"),params:wt.optional()}),lL=be([ji,Yl,Ki,id,Gi,Yn,Kn,Xn,Wi,Bk,Vk,Qn,mn,Zi,qi,Bi,Vi]),dL=be([Li,Fi,Ql,HT,no]),pL=be([Mi,io,ad,es,cd,Ui,Hi,Gn]),fL=be([ji,vT,zT,BT,Zi,qi,Bi,Vi]),mL=be([Li,Fi,pT,Gk,Uk,uT,sT,no,LT]),hL=be([Mi,Ik,UT,nT,Xk,Lk,jk,Zk,Ji,aT,Ui,Hi,Gn]),j=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===q.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new Vl(s.elicitations,r)}return new t(e,r,n)}},Vl=class extends j{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(q.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Pr(t){return t==="completed"||t==="failed"||t==="cancelled"}var Vg=Symbol("Let zodToJsonSchema decide on which parser to use");var Hg={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"},Wg=t=>typeof t=="string"?{...Hg,name:t}:{...Hg,...t};var Gg=t=>{let e=Wg(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ud(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ie(t,e,r,n,s){t[e]=r,ud(t,e,n,s)}var Xi=(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 Te(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Xi(e,t.currentPath):e.join("/")}}function Jg(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==k.ZodAny&&(r.items=G(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ie(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ie(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ie(r,"minItems",t.exactLength.value,t.exactLength.message,e),ie(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Kg(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?ie(r,"minimum",n.value,n.message,e):ie(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,e):ie(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,e));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,e);break}return r}function Xg(){return{type:"boolean"}}function Yi(t,e){return G(t.type._def,e)}var Yg=(t,e)=>G(t.innerType._def,e);function ld(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>ld(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return VT(t,e)}}var VT=(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":ie(r,"minimum",n.value,n.message,e);break;case"max":ie(r,"maximum",n.value,n.message,e);break}return r};function Qg(t,e){return{...G(t.innerType._def,e),default:t.defaultValue()}}function ey(t,e){return e.effectStrategy==="input"?G(t.schema._def,e):Te(e)}function ty(t){return{type:"string",enum:Array.from(t.values)}}var WT=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function ry(t,e){let r=[G(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),G(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(o=>{if(WT(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}function ny(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 dd,Nt={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:()=>(dd===void 0&&(dd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),dd),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 Qi(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ie(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ie(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":Dt(r,"email",n.message,e);break;case"format:idn-email":Dt(r,"idn-email",n.message,e);break;case"pattern:zod":Qe(r,Nt.email,n.message,e);break}break;case"url":Dt(r,"uri",n.message,e);break;case"uuid":Dt(r,"uuid",n.message,e);break;case"regex":Qe(r,n.regex,n.message,e);break;case"cuid":Qe(r,Nt.cuid,n.message,e);break;case"cuid2":Qe(r,Nt.cuid2,n.message,e);break;case"startsWith":Qe(r,RegExp(`^${pd(n.value,e)}`),n.message,e);break;case"endsWith":Qe(r,RegExp(`${pd(n.value,e)}$`),n.message,e);break;case"datetime":Dt(r,"date-time",n.message,e);break;case"date":Dt(r,"date",n.message,e);break;case"time":Dt(r,"time",n.message,e);break;case"duration":Dt(r,"duration",n.message,e);break;case"length":ie(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ie(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Qe(r,RegExp(pd(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Dt(r,"ipv4",n.message,e),n.version!=="v4"&&Dt(r,"ipv6",n.message,e);break}case"base64url":Qe(r,Nt.base64url,n.message,e);break;case"jwt":Qe(r,Nt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Qe(r,Nt.ipv4Cidr,n.message,e),n.version!=="v4"&&Qe(r,Nt.ipv6Cidr,n.message,e);break}case"emoji":Qe(r,Nt.emoji(),n.message,e);break;case"ulid":{Qe(r,Nt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Dt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ie(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Qe(r,Nt.base64,n.message,e);break}}break}case"nanoid":Qe(r,Nt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function pd(t,e){return e.patternStrategy==="escape"?JT(t):t}var GT=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function JT(t){let e="";for(let r=0;r<t.length;r++)GT.has(t[r])||(e+="\\"),e+=t[r];return e}function Dt(t,e,r,n){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ie(t,"format",e,r,n)}function Qe(t,e,r,n){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:sy(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ie(t,"pattern",sy(e,n),r,n)}function sy(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,s="",o=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],a=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
|
40
|
+
]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
|
|
41
|
+
]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
|
|
42
|
+
`:`[${n[c]}\r
|
|
43
|
+
]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function ea(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===k.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??Te(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===k.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=Qi(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===k.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===k.ZodBranded&&t.keyType._def.type._def.typeName===k.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=Yi(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function oy(t,e){if(e.mapStrategy==="record")return ea(t,e);let r=G(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Te(e),n=G(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Te(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function iy(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function ay(t){return t.target==="openAi"?void 0:{not:Te({...t,currentPath:[...t.currentPath,"not"]})}}function cy(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ao={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ly(t,e){if(e.target==="openApi3")return uy(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ao&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=ao[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return uy(t,e)}var uy=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>G(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function dy(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:ao[t.innerType._def.typeName],nullable:!0}:{type:[ao[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=G(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=G(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function py(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",ud(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ie(r,"minimum",n.value,n.message,e):ie(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,e):ie(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,e));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,e);break}return r}function fy(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let u=XT(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=G(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||s.push(a))}s.length&&(n.required=s);let i=KT(t,e);return i!==void 0&&(n.additionalProperties=i),n}function KT(t,e){if(t.catchall._def.typeName!=="ZodNever")return G(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 XT(t){try{return t.isOptional()}catch{return!0}}var my=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return G(t.innerType._def,e);let r=G(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Te(e)},r]}:Te(e)};var hy=(t,e)=>{if(e.pipeStrategy==="input")return G(t.in._def,e);if(e.pipeStrategy==="output")return G(t.out._def,e);let r=G(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=G(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function gy(t,e){return G(t.type._def,e)}function yy(t,e){let n={type:"array",uniqueItems:!0,items:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ie(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ie(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function _y(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>G(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:G(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>G(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function by(t){return{not:Te(t)}}function vy(t){return Te(t)}var xy=(t,e)=>G(t.innerType._def,e);var Sy=(t,e,r)=>{switch(e){case k.ZodString:return Qi(t,r);case k.ZodNumber:return py(t,r);case k.ZodObject:return fy(t,r);case k.ZodBigInt:return Kg(t,r);case k.ZodBoolean:return Xg();case k.ZodDate:return ld(t,r);case k.ZodUndefined:return by(r);case k.ZodNull:return cy(r);case k.ZodArray:return Jg(t,r);case k.ZodUnion:case k.ZodDiscriminatedUnion:return ly(t,r);case k.ZodIntersection:return ry(t,r);case k.ZodTuple:return _y(t,r);case k.ZodRecord:return ea(t,r);case k.ZodLiteral:return ny(t,r);case k.ZodEnum:return ty(t);case k.ZodNativeEnum:return iy(t);case k.ZodNullable:return dy(t,r);case k.ZodOptional:return my(t,r);case k.ZodMap:return oy(t,r);case k.ZodSet:return yy(t,r);case k.ZodLazy:return()=>t.getter()._def;case k.ZodPromise:return gy(t,r);case k.ZodNaN:case k.ZodNever:return ay(r);case k.ZodEffects:return ey(t,r);case k.ZodAny:return Te(r);case k.ZodUnknown:return vy(r);case k.ZodDefault:return Qg(t,r);case k.ZodBranded:return Yi(t,r);case k.ZodReadonly:return xy(t,r);case k.ZodCatch:return Yg(t,r);case k.ZodPipeline:return hy(t,r);case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:return;default:return(n=>{})(e)}};function G(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Vg)return a}if(n&&!r){let a=YT(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=Sy(t,t.typeName,e),i=typeof o=="function"?G(o(),e):o;if(i&&QT(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var YT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Xi(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`),Te(e)):e.$refStrategy==="seen"?Te(e):void 0}},QT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var fd=(t,e)=>{let r=Gg(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:G(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Te(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=G(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??Te(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function e$(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function md(t,e){return Xt(t)?zl(t,{target:e$(e?.target),io:e?.pipeStrategy??"input"}):fd(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function hd(t){let r=$r(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Vn(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function gd(t,e){let r=Tr(t,e);if(!r.success)throw r.error;return r.data}var t$=6e4,ta=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(Li,r=>{this._oncancel(r)}),this.setNotificationHandler(Fi,r=>{this._onprogress(r)}),this.setRequestHandler(ji,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Zi,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new j(q.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(qi,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,f=new j(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(o,n.sessionId);if(!i)throw new j(q.InvalidParams,`Task not found: ${o}`);if(!Pr(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(Pr(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Rr]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(Bi,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new j(q.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Vi,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new j(q.InvalidParams,`Task not found: ${r.params.taskId}`);if(Pr(s.status))throw new j(q.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new j(q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof j?s:new j(q.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),j.fromError(q.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),Ys(o)||Ng(o)?this._onresponse(o):Jl(o)?this._onrequest(o,i):Ag(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=j.fromError(q.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[Rr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:q.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},s?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):s?.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=Cg(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(i.signal.aborted)throw new j(q.ConnectionClosed,"Request was cancelled");let h={...f,relatedRequestId:e.id};o&&!h.relatedTask&&(h.relatedTask={taskId:o});let p=h.relatedTask?.taskId??o;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:o,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},s?.sessionId):await s?.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}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId):await s?.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,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Ys(e))n(e);else{let i=new j(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Ys(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),Ys(e))s(e);else{let i=j.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof j?i:new j(q.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Gn,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new j(q.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},Pr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new j(q.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new j(q.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof j?i:new j(q.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=b=>{l(b)};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(b){d(b);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||{},[Rr]:c}});let p=b=>{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(b)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let _=b instanceof j?b:new j(q.RequestTimeout,String(b));l(_)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return l(b);try{let _=Tr(r,b.result);_.success?u(_.data):l(_.error)}catch(_){l(_)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let m=n?.timeout??t$,g=()=>p(j.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 b=_=>{let x=this._responseHandlers.get(f);x?x(_):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(y,{type:"request",message:h,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(f),l(_)})}else this._transport.send(h,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(f),l(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ui,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},Hi,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Mg,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||{},[Rr]: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||{},[Rr]: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||{},[Rr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=hd(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=gd(e,s);return Promise.resolve(r(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=hd(e);this._notificationHandlers.set(n,s=>{let o=gd(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&Jl(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new j(q.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new j(q.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new j(q.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new j(q.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let a=await n.getTask(s,r);if(a){let c=no.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Pr(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let a=await n.getTask(s,r);if(!a)throw new j(q.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Pr(a.status))throw new j(q.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let c=await n.getTask(s,r);if(c){let u=no.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Pr(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function wy(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ey(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];wy(i)&&wy(o)?r[s]={...i,...o}:r[s]=o}return r}var Ev=Pm(cf(),1),kv=Pm(wv(),1);function pA(){let t=new Ev.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,kv.default)(t),t}var La=class{constructor(e){this._ajv=e??pA()}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 ja=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(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(o.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(o.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},io,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},es,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 Tv(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 $v(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 Fa=class extends ta{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(oo.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new La,this.setRequestHandler(Yl,n=>this._oninitialize(n)),this.setNotificationHandler(Ql,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(id,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=oo.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ja(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ey(this._capabilities,e)}setRequestHandler(e,r){let s=$r(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=Vn(s);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(c,u)=>{let l=Tr(Qn,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new j(q.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let p=Tr(Gn,f);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new j(q.InvalidParams,`Invalid task creation result: ${m}`)}return p.data}let h=Tr(Ji,f);if(!h.success){let p=h.error instanceof Error?h.error.message:String(h.error);throw new j(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){$v(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Tv(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:$g.includes(r)?r:Wl,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"},Mi)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],o=s.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(o){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(s.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},ad,r):this.request({method:"sampling/createMessage",params:e},io,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},es,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},es,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new j(q.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof j?i:new j(q.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},cd,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 Pv=Symbol.for("mcp.completable");function gf(t){return!!t&&typeof t=="object"&&Pv in t}function Cv(t){return t[Pv]?.complete}var Rv;(function(t){t.Completable="McpCompletable"})(Rv||(Rv={}));var fA=/^[A-Za-z0-9._-]{1,128}$/;function mA(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"),!fA.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function hA(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 yf(t){let e=mA(t);return hA(t,e.warnings),e.isValid}var Za=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let s={taskSupport:"required",...r.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,s,r._meta,n)}};var Ua=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 Fa(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Za(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Lr(mn)),this.server.assertCanSetRequestHandler(Lr(Qn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(mn,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let s=Hn(r.inputSchema);return s?md(s,{strictUnions:!0,pipeStrategy:"input"}):gA})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=Hn(r.outputSchema);s&&(n.outputSchema=md(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Qn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new j(q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new j(q.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=n.execution?.taskSupport,i="createTask"in n.handler;if((o==="required"||o==="optional")&&!i)throw new j(q.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new j(q.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return s||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof j&&n.code===q.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let o=Hn(e.inputSchema)??e.inputSchema,i=await Ci(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ii(a);throw new j(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 j(q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=Hn(e.outputSchema),o=await Ci(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=Ii(i);throw new j(q.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(r,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(r,n))}else{let i=s;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let s=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,i={...n,taskStore:n.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),c=a.task.taskId,u=a.task,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 j(q.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Lr(Ki)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ki,async e=>{switch(e.params.ref.type){case"ref/prompt":return qg(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Bg(e),this.handleResourceCompletion(e,e.params.ref);default:throw new j(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 j(q.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new j(q.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return jo;let o=$r(n.argsSchema)?.[e.params.argument.name];if(!gf(o))return jo;let i=Cv(o);if(!i)return jo;let a=await i(e.params.argument.value,e.params.context);return Ov(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 jo;throw new j(q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return jo;let o=await s(e.params.argument.value,e.params.context);return Ov(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Lr(Kn)),this.server.assertCanSetRequestHandler(Lr(Xn)),this.server.assertCanSetRequestHandler(Lr(Wi)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Kn,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(r);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...n,...s]}}),this.server.setRequestHandler(Xn,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Wi,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new j(q.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(n.toString());if(i)return o.readCallback(n,i,r)}throw new j(q.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Lr(Yn)),this.server.assertCanSetRequestHandler(Lr(Gi)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Yn,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?yA(r.argsSchema):void 0}))})),this.server.setRequestHandler(Gi,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new j(q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new j(q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=Hn(n.argsSchema),o=await Ci(s,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=Ii(c);throw new j(q.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=o.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());let o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){let i={name:e,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,s,o){let i={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,s,o){let i={title:r,description:n,argsSchema:s===void 0?void 0:fn(s),callback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=fn(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,s&&Object.values(s).some(c=>{let u=c instanceof ot?c._def?.innerType:c;return gf(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,c,u){yf(e);let l={title:r,description:n,inputSchema:Iv(s),outputSchema:Iv(o),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"&&yf(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=fn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=fn(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,s,o,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(_f(c))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!_f(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,s,o,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());let o=r[0],i=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=r,a=this._createRegisteredPrompt(e,s,o,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var gA={type:"object",properties:{}};function Av(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Nv(t){return"_def"in t||"_zod"in t||Av(t)}function _f(t){return typeof t!="object"||t===null||Nv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Av)}function Iv(t){if(t){if(_f(t))return fn(t);if(!Nv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function yA(t){let e=$r(t);return e?Object.entries(e).map(([r,n])=>{let s=ng(n),o=sg(n);return{name:r,description:s,required:!o}}):[]}function Lr(t){let r=$r(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Vn(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Ov(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var jo={completion:{values:[],hasMore:!1}};import zv from"node:process";var _A=10*1024*1024,qa=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??_A}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
44
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),bA(r)}clear(){this._buffer=void 0}};function bA(t){return Dg.parse(JSON.parse(t))}function Dv(t){return JSON.stringify(t)+`
|
|
45
|
+
`}var Ba=class{constructor(e=zv.stdin,r=zv.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=s=>{try{this._readBuffer.append(s),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=s=>{this.onerror?.(s)},this._readBuffer=new qa({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Dv(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{createRequire as IS}from"node:module";import{existsSync as Ie,unlinkSync as Cs,readdirSync as OS,readFileSync as oi,writeFileSync as Ec,writeSync as XD,renameSync as YD,rmSync as AS,mkdirSync as QD,statSync as NS,symlinkSync as ez,lstatSync as DS,realpathSync as zS}from"node:fs";import{spawnSync as kc}from"node:child_process";import{join as gt,dirname as Os,resolve as rt,sep as tz,isAbsolute as rz}from"node:path";import{fileURLToPath as nz}from"node:url";import{homedir as Is,tmpdir as gm,cpus as sz}from"node:os";import{request as oz}from"node:https";import{AsyncLocalStorage as iz}from"node:async_hooks";import{spawn as Vv,execSync as PA,execFileSync as Kv}from"node:child_process";import{mkdtempSync as CA,writeFileSync as Wv,rmSync as IA,existsSync as Gv}from"node:fs";import{join as Ga,resolve as Xv}from"node:path";import{tmpdir as OA}from"node:os";import{execFileSync as jv,execSync as Fo}from"node:child_process";import{existsSync as Uo}from"node:fs";function Ha(t,e){let r=process.execPath.replace(/\\/g,"/");if(vf(e?.platform)){let s=r.split("/").pop().replace(/\.exe$/i,"");bf.has(s)||(r=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let n=t.replace(/\\/g,"/");return`"${r}" "${n}"`}function Mv(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}var bf=new Set(["node","bun","deno"]),vA=new Set(["opencode","kilo"]);function vf(t){return!!t&&vA.has(t)}var xA=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,Lv=/^bun(\.exe)?$/i;function Sf(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function SA(t){return xA.test(Sf(t))}function wA(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function EA(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\cmd\.exe$/.test(e)}var Zo=process.platform==="win32";function ze(t){try{let e=Zo?`where ${t}`:`command -v ${t}`;return Fo(e,{stdio:"pipe"}),!0}catch{return!1}}function xf(t){if(Zo)try{let r=Fo(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(s=>s.trim()).filter(Boolean);if(r.length===0||r.filter(s=>!/\\Microsoft\\WindowsApps\\/i.test(s)).length===0)return!1}catch{return!1}else if(!ze(t))return!1;try{return Zo?Fo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):jv(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function Fv(){if(ze("bun"))return!0;for(let t of Zv())if(Uo(t))return!0;return!1}function kA(){for(let e of Zv())if(Uo(e))return e;if(ze("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Zo?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Zv(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Zo){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`]:[]}var TA=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];function Uv(){let t;try{t=Fo("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(r=>r.trim()).filter(Boolean)}catch{return null}for(let e of t){let r=e.toLowerCase();if(!(r.includes("system32")||r.includes("windowsapps"))){for(let n of TA)if(Uo(n))return n;return e}}return null}function $A(t=Uv()){return t??(ze("sh")?"sh":ze("pwsh")?"pwsh":ze("powershell")?"powershell":"cmd.exe")}function Pt(t,e=["--version"]){try{if(process.platform==="win32"){let r=[t,...e].map(n=>/[\s"&|<>^()%!]/.test(n)?JSON.stringify(n):n).join(" ");return Fo(r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return jv(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function RA(t,e={}){if(t)return t;let r=e.execPath??process.execPath,n=e.commandExists??ze,s=r.split(/[\\/]/).pop().replace(/\.exe$/i,"");return bf.has(s)&&Uo(r)?r:n("node")?"node":null}function Va(){let e=Fv()?kA():null,r=process.env.SHELL,n=process.platform==="win32",s=n?Uv():null,o=r&&Uo(r)&&SA(r)&&!(n&&wA(r))&&!(n&&s&&EA(r))?r:null;return{javascript:RA(e),typescript:e||(ze("tsx")?"tsx":ze("ts-node")?"ts-node":null),python:xf("python3")?"python3":xf("python")?"python":xf("py")?"py":null,shell:o??(n?$A(s):ze("bash")?"bash":"sh"),ruby:ze("ruby")?"ruby":null,go:ze("go")?"go":null,rust:ze("rustc")?"rustc":null,php:ze("php")?"php":null,perl:ze("perl")?"perl":null,r:ze("Rscript")?"Rscript":ze("r")?"r":null,elixir:ze("elixir")?"elixir":null,csharp:ze("dotnet-script")?"dotnet-script":null}}function Wa(){return Fv()}function qv(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${Pt(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} (${Pt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Pt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Pt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Pt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Pt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Pt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Pt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Pt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Pt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Pt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Pt(t.csharp)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
|
|
46
|
+
`)}function Bv(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 Hv(t,e,r){switch(e){case"javascript":if(!t.javascript)throw new Error("No JavaScript runtime available. Install Node.js or Bun on PATH (the host process is not itself a JS runtime).");return Lv.test(Sf(t.javascript))?[t.javascript,"run",r]:[t.javascript,r];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return Lv.test(Sf(t.typescript))?[t.typescript,"run",r]:t.typescript==="tsx"?["tsx",r]:["ts-node",r];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,r];case"shell":{if(process.platform==="win32"){let s=t.shell.toLowerCase();if(s.includes("bash")||s.endsWith("/sh")||s.endsWith("\\sh.exe")){let i=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${i}'`]}if(s.includes("powershell")||s.includes("pwsh"))return[t.shell,"-NoProfile","-ExecutionPolicy","Bypass","-File",r];let o=s.split(/[\\/]/).pop()??s;if(o==="cmd"||o==="cmd.exe")return[t.shell,"/d","/s","/c",r]}return[t.shell,r]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,r];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",r];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",r]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",r];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",r];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,r];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",r];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,r]}}var ft=process.platform==="win32",AA={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 NA(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";if(n.includes("powershell")||n.includes("pwsh"))return"script.ps1";let s=n.split(/[\\/]/).pop()??n;return s==="cmd"||s==="cmd.exe"?"script.cmd":"script"}return`script.${AA[t]}`}function DA(t){return{windowsHide:t==="win32"}}function zA(t){return`'${t.replace(/'/g,"'\\''")}'`}function MA(t,e,r){return r==="win32"||!e?t:`export PATH=${zA(e)}
|
|
47
|
+
${t}`}function LA(t){let e=t?.toLowerCase()??"";return e.includes("powershell")||e.includes("pwsh")}function jA(t){return["\uFEFF[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()","[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()","$OutputEncoding = [System.Text.UTF8Encoding]::new()",t].join(`
|
|
48
|
+
`)}var FA=(()=>{if(ft)return process.env.TEMP??process.env.TMP??OA();try{let t=Kv(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:Xv(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();function ZA(t,e){if(e!=="win32")return t;let r=new Set([";","&","|","(",`
|
|
49
|
+
`]),n="",s=!0,o=0;for(;o<t.length;){let i=t[o];if(s&&(i===" "||i===" ")){n+=i,o++;continue}if(s&&t.startsWith("mvn",o)){let a=t[o+3];if(a===void 0||a===" "||a===" "||a===`
|
|
50
|
+
`){n+="mvn.cmd",o+=3,s=!1;continue}}n+=i,s=r.has(i),o++}return n}function Jv(t){try{IA(t,{recursive:!0,force:!0,maxRetries:ft?8:2,retryDelay:100})}catch{}}function wf(t){if(ft&&t.pid)try{PA(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var qo=class{#e;#t;#r;#s=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let r=e?.projectRoot;typeof r=="function"?this.#t=r:typeof r=="string"?this.#t=()=>r:this.#t=()=>process.cwd(),this.#r=e?.runtimes??Va()}get#o(){return this.#t()}get runtimes(){return{...this.#r}}cleanupBackgrounded(){for(let e of this.#s)try{process.kill(ft?e:-e,"SIGTERM")}catch{}this.#s.clear()}async execute(e){let{language:r,code:n,timeout:s,background:o=!1,cwd:i}=e,a=CA(Ga(FA,".ctx-mode-"));try{let c=this.#a(a,n,r),u=Hv(this.#r,r,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,s);let l=i??this.#o,d=await this.#i(u,l,a,s,o);return d.backgrounded||Jv(a),d}catch(c){throw Jv(a),c}}async executeFile(e){let{path:r,language:n,code:s,timeout:o}=e,i=Xv(this.#o,r),a=this.#l(i,n,s);return this.execute({language:n,code:a,timeout:o})}#a(e,r,n){n==="go"&&!r.includes("package ")&&(r=`package main
|
|
51
|
+
|
|
52
|
+
import "fmt"
|
|
53
|
+
|
|
54
|
+
func main() {
|
|
55
|
+
${r}
|
|
56
|
+
}
|
|
57
|
+
`),n==="php"&&!r.trimStart().startsWith("<?")&&(r=`<?php
|
|
58
|
+
${r}`),n==="elixir"&&Gv(Ga(this.#o,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify(Ga(this.#o,"_build/dev/lib"))}, "*/ebin"))
|
|
59
|
+
|> Enum.each(&Code.prepend_path/1)
|
|
60
|
+
|
|
61
|
+
${r}`);let s=Ga(e,NA(n,process.platform,n==="shell"?this.#r.shell:null));if(n==="shell"){let o=this.#r.shell,i=ZA(r,process.platform),a=ft&&LA(o)?jA(i):i;Wv(s,MA(a,process.env.PATH,process.platform),{encoding:"utf-8",mode:448})}else Wv(s,r,"utf-8");return s}async#c(e,r,n){let s=ft?".exe":"",o=e.replace(/\.rs$/,"")+s;try{Kv("rustc",[e,"-o",o],{cwd:r,timeout:n===void 0?6e4:Math.min(n,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
|
|
62
|
+
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([o],r,r,n)}async#i(e,r,n,s,o=!1){return new Promise(i=>{let a=ft&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;ft&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=ft?e.slice(1).map(_=>_.replace(/\\/g,"/")):e.slice(1);let l={cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),detached:!ft,...DA(process.platform)},d;if(a){let _=[c,...u].map(x=>/\s/.test(x)?JSON.stringify(x):x).join(" ");d=Vv(_,[],{...l,shell:!0})}else d=Vv(c,u,{...l,shell:!1});let f=!1,h=!1,p=s===void 0?void 0:setTimeout(()=>{if(f=!0,o){h=!0,d.pid&&this.#s.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 _=Buffer.concat(m).toString("utf-8"),x=Buffer.concat(g).toString("utf-8");i({stdout:_,stderr:x,exitCode:0,timedOut:!0,backgrounded:!0})}else wf(d)},s),m=[],g=[],y=0,b=!1;d.stdout.on("data",_=>{y+=_.length,y<=this.#e?m.push(_):b||(b=!0,wf(d))}),d.stderr.on("data",_=>{y+=_.length,y<=this.#e?g.push(_):b||(b=!0,wf(d))}),d.on("close",_=>{if(clearTimeout(p),h)return;let x=Buffer.concat(m).toString("utf-8"),w=Buffer.concat(g).toString("utf-8");b&&(w+=`
|
|
63
|
+
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:x,stderr:w,exitCode:f?1:_??1,timedOut:f})}),d.on("error",_=>{clearTimeout(p),!h&&i({stdout:"",stderr:_.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","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"]),s={};for(let[o,i]of Object.entries(process.env))i!==void 0&&!n.has(o)&&!o.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(o)&&(s[o]=i);if(s.TMPDIR=e,s.HOME=r,s.LANG="en_US.UTF-8",s.PYTHONDONTWRITEBYTECODE="1",s.PYTHONUNBUFFERED="1",s.PYTHONUTF8="1",s.NO_COLOR="1",ft&&!s.PATH&&s.Path&&(s.PATH=s.Path,delete s.Path),s.PATH||(s.PATH=ft?"":"/usr/local/bin:/usr/bin:/bin"),ft){for(let a of Object.keys(s)){let c=a.toUpperCase();(c==="MSYS_NO_PATHCONV"||c==="MSYS2_ARG_CONV_EXCL")&&delete s[a]}let o="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";s.PATH.includes(o)||(s.PATH=`${o};${i};${s.PATH}`)}if(!s.SSL_CERT_FILE){let o=ft?[]:["/etc/ssl/cert.pem","/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"];for(let i of o)if(Gv(i)){s.SSL_CERT_FILE=i;break}}return s}#l(e,r,n){let s=JSON.stringify(e);switch(r){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${s};
|
|
64
|
+
const file_path = FILE_CONTENT_PATH;
|
|
65
|
+
const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
|
|
66
|
+
${n}`;case"python":return`FILE_CONTENT_PATH = ${s}
|
|
67
|
+
file_path = FILE_CONTENT_PATH
|
|
68
|
+
with open(FILE_CONTENT_PATH, "r", encoding="utf-8") as _f:
|
|
69
|
+
FILE_CONTENT = _f.read()
|
|
70
|
+
${n}`;case"shell":{let o="'"+e.replace(/'/g,"'\\''")+"'";return`FILE_CONTENT_PATH=${o}
|
|
71
|
+
file_path=${o}
|
|
72
|
+
FILE_CONTENT=$(cat ${o})
|
|
73
|
+
${n}`}case"ruby":return`FILE_CONTENT_PATH = ${s}
|
|
74
|
+
file_path = FILE_CONTENT_PATH
|
|
75
|
+
FILE_CONTENT = File.read(FILE_CONTENT_PATH, encoding: "utf-8")
|
|
76
|
+
${n}`;case"go":return`package main
|
|
77
|
+
|
|
78
|
+
import (
|
|
79
|
+
"fmt"
|
|
80
|
+
"os"
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
var FILE_CONTENT_PATH = ${s}
|
|
84
|
+
var file_path = FILE_CONTENT_PATH
|
|
85
|
+
|
|
86
|
+
func main() {
|
|
87
|
+
b, _ := os.ReadFile(FILE_CONTENT_PATH)
|
|
88
|
+
FILE_CONTENT := string(b)
|
|
89
|
+
_ = FILE_CONTENT
|
|
90
|
+
_ = fmt.Sprint()
|
|
91
|
+
${n}
|
|
92
|
+
}
|
|
93
|
+
`;case"rust":return`#![allow(unused_variables)]
|
|
94
|
+
use std::fs;
|
|
95
|
+
|
|
96
|
+
fn main() {
|
|
97
|
+
let file_content_path = ${s};
|
|
98
|
+
let file_path = file_content_path;
|
|
99
|
+
let file_content = fs::read_to_string(file_content_path).unwrap();
|
|
100
|
+
${n}
|
|
101
|
+
}
|
|
102
|
+
`;case"php":return`<?php
|
|
103
|
+
$FILE_CONTENT_PATH = ${s};
|
|
104
|
+
$file_path = $FILE_CONTENT_PATH;
|
|
105
|
+
$FILE_CONTENT = file_get_contents($FILE_CONTENT_PATH);
|
|
106
|
+
${n}`;case"perl":return`my $FILE_CONTENT_PATH = ${s};
|
|
107
|
+
my $file_path = $FILE_CONTENT_PATH;
|
|
108
|
+
open(my $fh, '<:encoding(UTF-8)', $FILE_CONTENT_PATH) or die "Cannot open: $!";
|
|
109
|
+
my $FILE_CONTENT = do { local $/; <$fh> };
|
|
110
|
+
close($fh);
|
|
111
|
+
${n}`;case"r":return`FILE_CONTENT_PATH <- ${s}
|
|
112
|
+
file_path <- FILE_CONTENT_PATH
|
|
113
|
+
FILE_CONTENT <- readLines(FILE_CONTENT_PATH, warn=FALSE, encoding="UTF-8")
|
|
114
|
+
FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
|
|
115
|
+
${n}`;case"elixir":return`file_content_path = ${s}
|
|
116
|
+
file_path = file_content_path
|
|
117
|
+
file_content = File.read!(file_content_path)
|
|
118
|
+
${n}`;case"csharp":return`var FILE_CONTENT_PATH = ${s};
|
|
119
|
+
var file_path = FILE_CONTENT_PATH;
|
|
120
|
+
var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
|
|
121
|
+
${n}`}}};import{cpus as UA}from"node:os";async function Ef(t,e){let{concurrency:r,capByCpuCount:n=!1,onSettled:s}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let o=Math.max(1,r),i=n?Math.max(1,UA().length):o,a=Math.min(o,i,t.length),c=a<o,u=new Array(t.length),l=0;async function d(){for(;;){let h=l++;if(h>=t.length)return;try{let p=await t[h].run();u[h]={status:"fulfilled",value:p}}catch(p){u[h]={status:"rejected",reason:p}}s?.(h,u[h])}}let f=[];for(let h=0;h<a;h++)f.push(d());return await Promise.allSettled(f),{settled:u,effectiveConcurrency:a,capped:c}}import{createRequire as qA}from"node:module";import{existsSync as BA,unlinkSync as Yv,renameSync as HA}from"node:fs";import{tmpdir as VA}from"node:os";import{join as WA}from"node:path";var Tf=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let s=Object.values(n[0]);return s.length===1?s[0]:n[0]}exec(e){let r="",n=null;for(let o=0;o<e.length;o++){let i=e[o];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let s=r.trim();return s&&this.#e.prepare(s).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let s=r.get(...n);return s===null?void 0:s},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},$f=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let s=Object.values(n[0]);return s.length===1?s[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},_s=null;function GA(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 JA(t,e){let r=e!==void 0?e:globalThis.Bun;if(typeof r<"u"&&r!==null)return!0;let n=t??process.versions,[s,o]=(n.node??"0.0.0").split("."),i=Number(s),a=Number(o);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function He(){if(!_s){let t=qA(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;_s=function(n,s){let o=new e(n,{readonly:s?.readonly,create:!0}),i=new Tf(o);return s?.timeout&&i.pragma(`busy_timeout = ${s.timeout}`),i}}else if(JA()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&GA(e)?_s=function(n,s){let o=new e(n,{readOnly:s?.readonly??!1}),i=new $f(o);return s?.timeout&&i.pragma(`busy_timeout = ${s.timeout}`),i}:_s=t("better-sqlite3")}else _s=t("better-sqlite3")}return _s}function Ho(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function Vo(t){if(!BA(t))for(let e of["-wal","-shm"])try{Yv(t+e)}catch{}}function Rf(t){for(let e of["","-wal","-shm"])try{Yv(t+e)}catch{}}function Wo(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function Qv(t="context-mode"){return WA(VA(),`${t}-${process.pid}.db`)}function $n(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(s){let o=s instanceof Error?s.message:String(s);if(!o.includes("SQLITE_BUSY")&&!o.includes("database is locked"))throw s;if(r=s instanceof Error?s:new Error(o),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function Pf(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 KA(t){let e=Date.now();for(let r of["","-wal","-shm"])try{HA(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var Bo=Symbol.for("__context_mode_live_dbs_v3__"),kf=(()=>{let t=globalThis;return t[Bo]||(t[Bo]=new Set,process.on("exit",()=>{for(let e of t[Bo])Wo(e);t[Bo].clear()})),t[Bo]})(),Ja=class{#e;#t;constructor(e){let r=He();this.#e=e,Vo(e);let n;try{n=new r(e,{timeout:3e4}),Ho(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(Pf(o)){KA(e),Vo(e);try{n=new r(e,{timeout:3e4}),Ho(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw s}this.#t=n,kf.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){kf.delete(this.#t),Wo(this.#t)}withRetry(e){return $n(e)}cleanup(){kf.delete(this.#t),Wo(this.#t),Rf(this.#e)}};import{readFileSync as ox,readdirSync as dx,unlinkSync as If,existsSync as Cf,statSync as Xa,openSync as ix,fstatSync as ax,closeSync as cx}from"node:fs";import{createHash as ux}from"node:crypto";import{tmpdir as px}from"node:os";import{join as Of}from"node:path";import{readdirSync as XA,statSync as YA,lstatSync as QA,realpathSync as ex,existsSync as eN,readFileSync as tN}from"node:fs";import{join as rx,extname as rN,relative as nx,sep as nN,resolve as sN}from"node:path";var oN=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],iN=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],aN=5,cN=200;function uN(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];n==="*"?t[r+1]==="*"?(e+=".*",r++):e+="[^/]*":n==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(n)?e+="\\"+n:e+=n}return new RegExp(`^${e}$`)}function tx(t,e){if(e.length===0)return!1;let r=t.split("/").pop()??t;for(let n of e){if(!n.includes("/")&&!n.includes("*")){if(r===n||t.split("/").includes(n))return!0;continue}let s=uN(n);if(s.test(t)||s.test(r))return!0}return!1}function lN(t){let e=rx(t,".gitignore");if(!eN(e))return[];try{return tN(e,"utf-8").split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function dN(t,e){return nx(t,e).split(nN).join("/")}function sx(t,e={}){let{include:r,exclude:n,maxDepth:s=aN,maxFiles:o=cN,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=ex(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:iN).map(b=>(b.startsWith(".")?b:"."+b).toLowerCase()),d=[...oN,...n??[],...a?lN(u):[]],f=r??[],h=[],p=new Set([u]),m=0,g=!1;function y(b,_){if(g||_>s)return;let x;try{x=XA(b,{withFileTypes:!0})}catch{return}for(let w of x){if(g)return;let I=rx(b,w.name),R=dN(u,I);if(tx(R,d))continue;let M=w.isDirectory(),z=w.isFile(),V=!1;try{V=QA(I).isSymbolicLink()}catch{continue}if(V){if(!c)continue;let T;try{T=ex(I)}catch{continue}let F=nx(u,T);if((F.startsWith("..")||sN(F)===T)&&F.startsWith("..")||p.has(T))continue;p.add(T);try{let de=YA(T);M=de.isDirectory(),z=de.isFile()}catch{continue}}if(M){y(I,_+1);continue}if(!z)continue;let $=rN(I).toLowerCase();if(l.includes($)&&!(f.length>0&&!tx(R,f))){if(m++,h.length>=o){g=!0;return}h.push(I)}}}return y(u,0),{files:h,capped:g,totalSeen:m}}var bs=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);function fx(t){let e=new Set,r=[];for(let n of t){let s=n.toLowerCase();e.has(s)||(e.add(s),r.push(n))}return r}function pN(t,e="AND"){let r=fx(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(o=>o.length>0&&!["AND","OR","NOT","NEAR"].includes(o.toUpperCase())));if(r.length===0)return'""';let n=r.filter(o=>!bs.has(o.toLowerCase()));return(n.length>0?n:r).map(o=>`"${o}"`).join(e==="OR"?" OR ":" ")}function fN(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=fx(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let s=n.filter(i=>!bs.has(i.toLowerCase()));return(s.length>0?s:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function mN(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,s)=>s);for(let n=1;n<=t.length;n++){let s=[n];for(let o=1;o<=e.length;o++)s[o]=t[n-1]===e[o-1]?r[o-1]:1+Math.min(r[o],s[o-1],r[o-1]);r=s}return r[e.length]}function hN(t){return t<=4?1:t<=12?2:3}var Ka=4096,gN=3,yN=200,_N=5e3,lx=80,bN=.5;function Af(){let t=px(),e=0;try{let r=dx(t);for(let n of r){let s=n.match(/^context-mode-(\d+)\.db$/);if(!s)continue;let o=parseInt(s[1],10);if(o!==process.pid)try{process.kill(o,0)}catch{let i=Of(t,n);for(let a of["","-wal","-shm"])try{If(i+a)}catch{}e++}}}catch{}return e}function Nf(t,e){let r=0;try{if(!Cf(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=dx(t).filter(o=>o.endsWith(".db"));for(let o of s)try{let i=Of(t,o),c=Xa(i).mtimeMs<n;if(!c){let u=i+"-wal";if(Cf(u))try{let l=Xa(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{If(i+u)}catch{}r++}}catch{}}catch{}return r}function vN(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function xN(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,s=Math.min(t.length,e.length)-1;for(let o=0;o<s;o++){let i=t[o],a=t[o+1],c=e[o].length,u=0;for(let l of i){let d=l+c,f=d+r;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=f&&(n++,u++)}}return n}function SN(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t,r=new Array(e.length).fill(0),n=1/0;for(;;){let s=1/0,o=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<s&&(s=u,i=c),u>o&&(o=u)}let a=o-s;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var Ya=class t{#e;#t;#r;#s;#o;#a;#c;#i;#u;#l;#m;#h;#g;#y;#_;#b;#v;#x;#S;#w;#E;#k;#T;#$;#R;#P;#C;#I;#O;#A;#N;#D;#z;#M=0;static OPTIMIZE_EVERY=50;#n=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=He();this.#t=e??Of(px(),`context-mode-${process.pid}.db`),Vo(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),Ho(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(Pf(o)){Rf(this.#t),Vo(this.#t);try{n=new r(this.#t,{timeout:3e4}),Ho(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw s}this.#e=n,this.#q(),this.#B()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{If(this.#t+e)}catch{}}#q(){this.#e.exec(`
|
|
122
|
+
CREATE TABLE IF NOT EXISTS sources (
|
|
123
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
124
|
+
label TEXT NOT NULL,
|
|
125
|
+
chunk_count INTEGER NOT NULL DEFAULT 0,
|
|
126
|
+
code_chunk_count INTEGER NOT NULL DEFAULT 0,
|
|
127
|
+
indexed_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
128
|
+
file_path TEXT,
|
|
129
|
+
content_hash TEXT
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
|
|
133
|
+
title,
|
|
134
|
+
content,
|
|
135
|
+
source_id UNINDEXED,
|
|
136
|
+
content_type UNINDEXED,
|
|
137
|
+
source_category UNINDEXED,
|
|
138
|
+
session_id UNINDEXED,
|
|
139
|
+
event_id UNINDEXED,
|
|
140
|
+
timestamp UNINDEXED,
|
|
141
|
+
tokenize='porter unicode61'
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS chunks_trigram USING fts5(
|
|
145
|
+
title,
|
|
146
|
+
content,
|
|
147
|
+
source_id UNINDEXED,
|
|
148
|
+
content_type UNINDEXED,
|
|
149
|
+
source_category UNINDEXED,
|
|
150
|
+
session_id UNINDEXED,
|
|
151
|
+
event_id UNINDEXED,
|
|
152
|
+
timestamp UNINDEXED,
|
|
153
|
+
tokenize='trigram'
|
|
154
|
+
);
|
|
155
|
+
|
|
156
|
+
CREATE TABLE IF NOT EXISTS vocabulary (
|
|
157
|
+
word TEXT PRIMARY KEY
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
CREATE INDEX IF NOT EXISTS idx_sources_label ON sources(label);
|
|
161
|
+
`);try{let e=this.#e.prepare("SELECT name FROM pragma_table_xinfo('chunks')").all(),r=new Set(e.map(n=>n.name));e.length>0&&!r.has("source_category")&&(this.#e.exec("DROP TABLE IF EXISTS chunks"),this.#e.exec("DROP TABLE IF EXISTS chunks_trigram"),this.#e.exec(`
|
|
162
|
+
CREATE VIRTUAL TABLE chunks USING fts5(
|
|
163
|
+
title,
|
|
164
|
+
content,
|
|
165
|
+
source_id UNINDEXED,
|
|
166
|
+
content_type UNINDEXED,
|
|
167
|
+
source_category UNINDEXED,
|
|
168
|
+
session_id UNINDEXED,
|
|
169
|
+
event_id UNINDEXED,
|
|
170
|
+
timestamp UNINDEXED,
|
|
171
|
+
tokenize='porter unicode61'
|
|
172
|
+
);
|
|
173
|
+
CREATE VIRTUAL TABLE chunks_trigram USING fts5(
|
|
174
|
+
title,
|
|
175
|
+
content,
|
|
176
|
+
source_id UNINDEXED,
|
|
177
|
+
content_type UNINDEXED,
|
|
178
|
+
source_category UNINDEXED,
|
|
179
|
+
session_id UNINDEXED,
|
|
180
|
+
event_id UNINDEXED,
|
|
181
|
+
timestamp UNINDEXED,
|
|
182
|
+
tokenize='trigram'
|
|
183
|
+
);
|
|
184
|
+
`))}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.#s=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, 0, 0, ?, ?)"),this.#o=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(`
|
|
185
|
+
SELECT
|
|
186
|
+
chunks.title,
|
|
187
|
+
chunks.content,
|
|
188
|
+
chunks.content_type,
|
|
189
|
+
chunks.timestamp,
|
|
190
|
+
sources.label,
|
|
191
|
+
bm25(chunks, 5.0, 1.0) AS rank,
|
|
192
|
+
highlight(chunks, 1, char(2), char(3)) AS highlighted,
|
|
193
|
+
chunks.session_id
|
|
194
|
+
FROM chunks
|
|
195
|
+
JOIN sources ON sources.id = chunks.source_id
|
|
196
|
+
WHERE chunks MATCH ?
|
|
197
|
+
ORDER BY rank
|
|
198
|
+
LIMIT ?
|
|
199
|
+
`),this.#g=this.#e.prepare(`
|
|
200
|
+
SELECT
|
|
201
|
+
chunks.title,
|
|
202
|
+
chunks.content,
|
|
203
|
+
chunks.content_type,
|
|
204
|
+
chunks.timestamp,
|
|
205
|
+
sources.label,
|
|
206
|
+
bm25(chunks, 5.0, 1.0) AS rank,
|
|
207
|
+
highlight(chunks, 1, char(2), char(3)) AS highlighted,
|
|
208
|
+
chunks.session_id
|
|
209
|
+
FROM chunks
|
|
210
|
+
JOIN sources ON sources.id = chunks.source_id
|
|
211
|
+
WHERE chunks MATCH ? AND sources.label LIKE ? ESCAPE '\\'
|
|
212
|
+
ORDER BY rank
|
|
213
|
+
LIMIT ?
|
|
214
|
+
`),this.#y=this.#e.prepare(`
|
|
215
|
+
SELECT
|
|
216
|
+
chunks.title,
|
|
217
|
+
chunks.content,
|
|
218
|
+
chunks.content_type,
|
|
219
|
+
chunks.timestamp,
|
|
220
|
+
sources.label,
|
|
221
|
+
bm25(chunks, 5.0, 1.0) AS rank,
|
|
222
|
+
highlight(chunks, 1, char(2), char(3)) AS highlighted,
|
|
223
|
+
chunks.session_id
|
|
224
|
+
FROM chunks
|
|
225
|
+
JOIN sources ON sources.id = chunks.source_id
|
|
226
|
+
WHERE chunks MATCH ? AND sources.label = ?
|
|
227
|
+
ORDER BY rank
|
|
228
|
+
LIMIT ?
|
|
229
|
+
`),this.#_=this.#e.prepare(`
|
|
230
|
+
SELECT
|
|
231
|
+
chunks_trigram.title,
|
|
232
|
+
chunks_trigram.content,
|
|
233
|
+
chunks_trigram.content_type,
|
|
234
|
+
chunks_trigram.timestamp,
|
|
235
|
+
sources.label,
|
|
236
|
+
bm25(chunks_trigram, 5.0, 1.0) AS rank,
|
|
237
|
+
highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
|
|
238
|
+
chunks_trigram.session_id
|
|
239
|
+
FROM chunks_trigram
|
|
240
|
+
JOIN sources ON sources.id = chunks_trigram.source_id
|
|
241
|
+
WHERE chunks_trigram MATCH ?
|
|
242
|
+
ORDER BY rank
|
|
243
|
+
LIMIT ?
|
|
244
|
+
`),this.#b=this.#e.prepare(`
|
|
245
|
+
SELECT
|
|
246
|
+
chunks_trigram.title,
|
|
247
|
+
chunks_trigram.content,
|
|
248
|
+
chunks_trigram.content_type,
|
|
249
|
+
chunks_trigram.timestamp,
|
|
250
|
+
sources.label,
|
|
251
|
+
bm25(chunks_trigram, 5.0, 1.0) AS rank,
|
|
252
|
+
highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
|
|
253
|
+
chunks_trigram.session_id
|
|
254
|
+
FROM chunks_trigram
|
|
255
|
+
JOIN sources ON sources.id = chunks_trigram.source_id
|
|
256
|
+
WHERE chunks_trigram MATCH ? AND sources.label LIKE ? ESCAPE '\\'
|
|
257
|
+
ORDER BY rank
|
|
258
|
+
LIMIT ?
|
|
259
|
+
`),this.#v=this.#e.prepare(`
|
|
260
|
+
SELECT
|
|
261
|
+
chunks_trigram.title,
|
|
262
|
+
chunks_trigram.content,
|
|
263
|
+
chunks_trigram.content_type,
|
|
264
|
+
chunks_trigram.timestamp,
|
|
265
|
+
sources.label,
|
|
266
|
+
bm25(chunks_trigram, 5.0, 1.0) AS rank,
|
|
267
|
+
highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
|
|
268
|
+
chunks_trigram.session_id
|
|
269
|
+
FROM chunks_trigram
|
|
270
|
+
JOIN sources ON sources.id = chunks_trigram.source_id
|
|
271
|
+
WHERE chunks_trigram MATCH ? AND sources.label = ?
|
|
272
|
+
ORDER BY rank
|
|
273
|
+
LIMIT ?
|
|
274
|
+
`),this.#S=this.#e.prepare(`
|
|
275
|
+
SELECT
|
|
276
|
+
chunks.title,
|
|
277
|
+
chunks.content,
|
|
278
|
+
chunks.content_type,
|
|
279
|
+
chunks.timestamp,
|
|
280
|
+
sources.label,
|
|
281
|
+
bm25(chunks, 5.0, 1.0) AS rank,
|
|
282
|
+
highlight(chunks, 1, char(2), char(3)) AS highlighted,
|
|
283
|
+
chunks.session_id
|
|
284
|
+
FROM chunks
|
|
285
|
+
JOIN sources ON sources.id = chunks.source_id
|
|
286
|
+
WHERE chunks MATCH ? AND chunks.content_type = ?
|
|
287
|
+
ORDER BY rank
|
|
288
|
+
LIMIT ?
|
|
289
|
+
`),this.#w=this.#e.prepare(`
|
|
290
|
+
SELECT
|
|
291
|
+
chunks.title,
|
|
292
|
+
chunks.content,
|
|
293
|
+
chunks.content_type,
|
|
294
|
+
chunks.timestamp,
|
|
295
|
+
sources.label,
|
|
296
|
+
bm25(chunks, 5.0, 1.0) AS rank,
|
|
297
|
+
highlight(chunks, 1, char(2), char(3)) AS highlighted,
|
|
298
|
+
chunks.session_id
|
|
299
|
+
FROM chunks
|
|
300
|
+
JOIN sources ON sources.id = chunks.source_id
|
|
301
|
+
WHERE chunks MATCH ? AND sources.label LIKE ? ESCAPE '\\' AND chunks.content_type = ?
|
|
302
|
+
ORDER BY rank
|
|
303
|
+
LIMIT ?
|
|
304
|
+
`),this.#E=this.#e.prepare(`
|
|
305
|
+
SELECT
|
|
306
|
+
chunks.title,
|
|
307
|
+
chunks.content,
|
|
308
|
+
chunks.content_type,
|
|
309
|
+
chunks.timestamp,
|
|
310
|
+
sources.label,
|
|
311
|
+
bm25(chunks, 5.0, 1.0) AS rank,
|
|
312
|
+
highlight(chunks, 1, char(2), char(3)) AS highlighted,
|
|
313
|
+
chunks.session_id
|
|
314
|
+
FROM chunks
|
|
315
|
+
JOIN sources ON sources.id = chunks.source_id
|
|
316
|
+
WHERE chunks MATCH ? AND sources.label = ? AND chunks.content_type = ?
|
|
317
|
+
ORDER BY rank
|
|
318
|
+
LIMIT ?
|
|
319
|
+
`),this.#k=this.#e.prepare(`
|
|
320
|
+
SELECT
|
|
321
|
+
chunks_trigram.title,
|
|
322
|
+
chunks_trigram.content,
|
|
323
|
+
chunks_trigram.content_type,
|
|
324
|
+
chunks_trigram.timestamp,
|
|
325
|
+
sources.label,
|
|
326
|
+
bm25(chunks_trigram, 5.0, 1.0) AS rank,
|
|
327
|
+
highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
|
|
328
|
+
chunks_trigram.session_id
|
|
329
|
+
FROM chunks_trigram
|
|
330
|
+
JOIN sources ON sources.id = chunks_trigram.source_id
|
|
331
|
+
WHERE chunks_trigram MATCH ? AND chunks_trigram.content_type = ?
|
|
332
|
+
ORDER BY rank
|
|
333
|
+
LIMIT ?
|
|
334
|
+
`),this.#T=this.#e.prepare(`
|
|
335
|
+
SELECT
|
|
336
|
+
chunks_trigram.title,
|
|
337
|
+
chunks_trigram.content,
|
|
338
|
+
chunks_trigram.content_type,
|
|
339
|
+
chunks_trigram.timestamp,
|
|
340
|
+
sources.label,
|
|
341
|
+
bm25(chunks_trigram, 5.0, 1.0) AS rank,
|
|
342
|
+
highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
|
|
343
|
+
chunks_trigram.session_id
|
|
344
|
+
FROM chunks_trigram
|
|
345
|
+
JOIN sources ON sources.id = chunks_trigram.source_id
|
|
346
|
+
WHERE chunks_trigram MATCH ? AND sources.label LIKE ? ESCAPE '\\' AND chunks_trigram.content_type = ?
|
|
347
|
+
ORDER BY rank
|
|
348
|
+
LIMIT ?
|
|
349
|
+
`),this.#$=this.#e.prepare(`
|
|
350
|
+
SELECT
|
|
351
|
+
chunks_trigram.title,
|
|
352
|
+
chunks_trigram.content,
|
|
353
|
+
chunks_trigram.content_type,
|
|
354
|
+
chunks_trigram.timestamp,
|
|
355
|
+
sources.label,
|
|
356
|
+
bm25(chunks_trigram, 5.0, 1.0) AS rank,
|
|
357
|
+
highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
|
|
358
|
+
chunks_trigram.session_id
|
|
359
|
+
FROM chunks_trigram
|
|
360
|
+
JOIN sources ON sources.id = chunks_trigram.source_id
|
|
361
|
+
WHERE chunks_trigram MATCH ? AND sources.label = ? AND chunks_trigram.content_type = ?
|
|
362
|
+
ORDER BY rank
|
|
363
|
+
LIMIT ?
|
|
364
|
+
`),this.#x=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.#P=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label
|
|
365
|
+
FROM chunks c
|
|
366
|
+
JOIN sources s ON s.id = c.source_id
|
|
367
|
+
WHERE c.source_id = ?
|
|
368
|
+
ORDER BY c.rowid`),this.#C=this.#e.prepare("SELECT chunk_count FROM sources WHERE id = ?"),this.#I=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.#O=this.#e.prepare(`
|
|
369
|
+
SELECT
|
|
370
|
+
(SELECT COUNT(*) FROM sources) AS sources,
|
|
371
|
+
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
372
|
+
(SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
|
|
373
|
+
`),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.#z=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#r=e}index(e){let{content:r,path:n,source:s,attribution:o}=e,i=typeof r=="string"&&r.length>0;if(!i&&!n)throw new Error("Either content or path must be provided");let a;if(i)a=r;else{let f=ix(n,"r");try{if(!ax(f).isFile())throw new Error(`refusing to index ${n}: not a regular file`);a=ox(f,"utf-8")}finally{cx(f)}}let c=s??n??"untitled",u=this.#G(a),l=n??void 0,d=l?ux("sha256").update(a).digest("hex"):void 0;return $n(()=>this.#d(u,c,a,l,d,o))}indexDirectory(e){let{path:r,source:n,attribution:s,perFileDeny:o,...i}=e,a=sx(r,i),c=0,u=0,l=0,d=0;for(let f of a.files){if(o&&o(f)){l++;continue}try{let h=n?`${n}:${f}`:f,p=this.index({path:f,source:h,attribution:s});c++,u+=p.totalChunks}catch{d++}}return{filesIndexed:c,totalChunks:u,capped:a.capped,totalSeen:a.totalSeen,denied:l,failed:d,label:n??r}}indexPlainText(e,r,n=20,s,o=Ka){if(!e||e.trim().length===0)return this.#d([],r,"",void 0,void 0,s);let i=this.#K(e,n,o);return $n(()=>this.#d(i.map(a=>({...a,hasCode:!1})),r,e,void 0,void 0,s))}indexJSON(e,r,n=Ka,s){if(!e||e.trim().length===0)return this.indexPlainText("",r,void 0,s,n);let o;try{o=JSON.parse(e)}catch{return this.indexPlainText(e,r,void 0,s,n)}let i=[];return this.#U(o,[],i,n),i.length===0?this.indexPlainText(e,r,void 0,s,n):$n(()=>this.#d(i,r,e,void 0,void 0,s))}#d(e,r,n,s,o,i){let a=e.filter(f=>f.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",d=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#m.run(r),e.length===0){let m=this.#s.run(r,s??null,o??null);return Number(m.lastInsertRowid)}let f=this.#o.run(r,e.length,a,s??null,o??null),h=Number(f.lastInsertRowid),p=new Date().toISOString();for(let m of e){let g=m.hasCode?"code":"prose";this.#a.run(m.title,m.content,h,g,null,c,u,p),this.#c.run(m.title,m.content,h,g,null,c,u,p)}return h})();return n&&this.#W(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#Z(),{sourceId:d,label:r,totalChunks:e.length,codeChunks:a}}#L(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0,sessionId:r.session_id??""}))}#p(e,r){return r==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,r=3,n,s="AND",o,i="like"){let a=pN(e,s),c,u;return n&&o?(c=i==="exact"?this.#E:this.#w,u=[a,this.#p(n,i),o,r]):n?(c=i==="exact"?this.#y:this.#g,u=[a,this.#p(n,i),r]):o?(c=this.#S,u=[a,o,r]):(c=this.#h,u=[a,r]),$n(()=>this.#L(c.all(...u)))}searchTrigram(e,r=3,n,s="AND",o,i="like"){let a=fN(e,s);if(!a)return[];let c,u;return n&&o?(c=i==="exact"?this.#$:this.#T,u=[a,this.#p(n,i),o,r]):n?(c=i==="exact"?this.#v:this.#b,u=[a,this.#p(n,i),r]):o?(c=this.#k,u=[a,o,r]):(c=this.#_,u=[a,r]),$n(()=>this.#L(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;if(this.#n.has(r)){let u=this.#n.get(r)??null;return this.#n.delete(r),this.#n.set(r,u),u}let n=hN(r.length),s=this.#x.all(r.length-n,r.length+n),o=null,i=n+1,a=!1;for(let{word:u}of s){if(u===r){a=!0;break}let l=mN(r,u);l<i&&(i=l,o=u)}let c=a?null:i<=n?o:null;if(this.#n.size>=t.FUZZY_CACHE_SIZE){let u=this.#n.keys().next().value;u!==void 0&&this.#n.delete(u)}return this.#n.set(r,c),c}#j(e,r,n,s,o="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",s,o),u=this.searchTrigram(e,a,n,"OR",s,o),l=new Map,d=f=>`${f.source}::${f.title}`;for(let[f,h]of c.entries()){let p=d(h),m=l.get(p);m?m.score+=1/(60+f+1):l.set(p,{result:h,score:1/(60+f+1)})}for(let[f,h]of u.entries()){let p=d(h),m=l.get(p);m?m.score+=1/(60+f+1):l.set(p,{result:h,score:1/(60+f+1)})}return Array.from(l.values()).sort((f,h)=>h.score-f.score).slice(0,r).map(({result:f,score:h})=>({...f,rank:-h}))}#F(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),s=n.filter(i=>!bs.has(i)),o=s.length>0?s:n;return e.map(i=>{let a=i.title.toLowerCase(),c=o.filter(h=>a.includes(h)).length,u=i.contentType==="code"?.6:.3,l=c>0?u*(c/o.length):0,d=0,f=0;if(o.length>=2){let h=i.content.toLowerCase(),p=o.map(m=>vN(h,m));if(!p.some(m=>m.length===0)){d=1/(1+SN(p)/Math.max(h.length,1));let g=xN(p,o);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,r=3,n,s,o="like",i){this.#V();let a=i?Math.max(r*8,40):r,c=this.#H(i),u=this.#j(e,a,n,s,o),l=c?u.filter(c):u;if(l.length>0)return this.#F(l.slice(0,r),e).map(g=>({...g,matchLayer:"rrf"}));let d=e.toLowerCase().trim().split(/\s+/).filter(m=>m.length>=3&&!bs.has(m)),f=d.join(" "),p=d.map(m=>this.fuzzyCorrect(m)??m).join(" ");if(p!==f){let m=this.#j(p,a,n,s,o),g=c?m.filter(c):m;if(g.length>0)return this.#F(g.slice(0,r),p).map(b=>({...b,matchLayer:"rrf-fuzzy"}))}return[]}#H(e){return e?r=>{let n=r.sessionId??"";return n===""||e.has(n)}: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 r of e)try{if(!Cf(r.file_path)||this.#r&&this.#r(r.file_path))continue;let n=Xa(r.file_path).mtime,s=new Date(r.indexed_at+"Z");if(n<=s)continue;let o=ix(r.file_path,"r"),i;try{if(!ax(o).isFile())continue;i=ox(o,"utf-8")}finally{cx(o)}if(ux("sha256").update(i).digest("hex")===r.content_hash)continue;this.index({content:i,path:r.file_path,source:r.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let r=this.#A.get(e);return r?{label:r.label,chunkCount:r.chunk_count,codeChunkCount:r.code_chunk_count,indexedAt:r.indexed_at,filePath:r.file_path??null,contentHash:r.content_hash??null}:null}listSources(){return this.#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.#P.all(e).map(n=>({title:n.title,content:n.content,source:n.label,rank:0,contentType:n.content_type}))}getDistinctiveTerms(e,r=40){let n=this.#C.get(e);if(!n||n.chunk_count<3)return[];let s=n.chunk_count,o=2,i=Math.max(3,Math.ceil(s*.4)),a=new Map;for(let l of this.#I.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(f=>f.length>=3&&!bs.has(f)));for(let f of d)a.set(f,(a.get(f)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=o&&l<=i).map(([l,d])=>{let f=Math.log(s/d),h=Math.min(l.length/20,.5),p=/[_]/.test(l),m=l.length>=12,g=p?1.5:m?.8:0;return{word:l,score:f+h+g}}).sort((l,d)=>d.score-l.score).slice(0,r).map(l=>l.word)}getStats(){let e=this.#O.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(s=>(this.#N.run(s),this.#D.run(s),this.#z.run(s)))(e).changes}getDBSizeBytes(){try{return Xa(this.#t).size}catch{return 0}}#Z(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#Z(),Wo(this.#e)}#W(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(o=>o.length>=3&&!bs.has(o)),n=[...new Set(r)],s=0;this.#e.transaction(()=>{for(let o of n){let i=this.#i.run(o);s+=i.changes}})(),s>0&&this.#n.clear()}#G(e,r=Ka){let n=[],s=e.split(`
|
|
374
|
+
`),o=[],i=[],a="",c=()=>{let l=i.join(`
|
|
375
|
+
`).trim();if(l.length===0)return;let d=this.#ee(o,a),f=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(l)<=r){n.push({title:d,content:l,hasCode:f}),i=[];return}let h=l.split(/\n\n+/),p=[],m=1,g=()=>{if(p.length===0)return;let y=p.join(`
|
|
376
|
+
|
|
377
|
+
`).trim();if(y.length===0)return;let b=h.length>1?`${d} (${m})`:d;m++,n.push({title:b,content:y,hasCode:y.includes("```")}),p=[]};for(let y of h){p.push(y);let b=p.join(`
|
|
378
|
+
|
|
379
|
+
`);Buffer.byteLength(b)>r&&p.length>1&&(p.pop(),g(),p=[y])}g(),i=[]},u=0;for(;u<s.length;){let l=s[u];if(/^[-_*]{3,}\s*$/.test(l)){c(),u++;continue}let d=l.match(/^(#{1,4})\s+(.+)$/);if(d){c();let h=d[1].length,p=d[2].trim();for(;o.length>0&&o[o.length-1].level>=h;)o.pop();o.push({level:h,text:p}),a=p,i.push(l),u++;continue}let f=l.match(/^(`{3,})(.*)?$/);if(f){let h=f[1],p=[l];for(u++;u<s.length;){if(p.push(s[u]),s[u].startsWith(h)&&s[u].trim()===h){u++;break}u++}i.push(...p);continue}i.push(l),u++}return c(),n}#J(e,r){if(Buffer.byteLength(e)<=r)return e;let n="",s=0;for(let o of e){let i=Buffer.byteLength(o);if(s+i>r)break;n+=o,s+=i}return n.length===0?[...e][0]??"":n}#f(e,r,n){let s=[],o=[],i=1,a=()=>{if(o.length===0)return;let c=o.join(`
|
|
380
|
+
`),u=i===1?r:`${r} (${i})`;s.push({title:u,content:c}),i++,o=[]};for(let c of e){if(Buffer.byteLength(c)>n){a();let l=c,d=1;for(;l.length>0;){let f=this.#J(l,n);if(f.length<l.length){let p=f.lastIndexOf(" "),m=f.lastIndexOf(`
|
|
381
|
+
`),g=Math.max(p,m);g>f.length*bN&&(f=f.slice(0,g))}let h=i===1&&d===1?r:`${r} (${i}.${d})`;s.push({title:h,content:f}),l=l.slice(f.length),d++,i++}continue}let u=o.length>0?o.join(`
|
|
382
|
+
`)+`
|
|
383
|
+
`+c:c;Buffer.byteLength(u)>n&&o.length>0&&a(),o.push(c)}return a(),s}#K(e,r,n=Ka){let s=e.split(/\n\s*\n/);if(s.length>=gN&&s.length<=yN&&s.every(u=>Buffer.byteLength(u)<_N))return s.flatMap((u,l)=>{let d=u.trim();if(d.length===0)return[];let f=d.split(`
|
|
384
|
+
`)[0].slice(0,lx)||`Section ${l+1}`;return Buffer.byteLength(d)<=n?[{title:f,content:d}]:this.#f(d.split(`
|
|
385
|
+
`),f,n)});let o=e.split(`
|
|
386
|
+
`);if(o.length<=r)return Buffer.byteLength(e)<=n?[{title:"Output",content:e}]:this.#f(o,"Output",n);let i=[],c=Math.max(r-2,1);for(let u=0;u<o.length;u+=c){let l=o.slice(u,u+r);if(l.length===0)break;let d=u+1,f=Math.min(u+l.length,o.length),h=l[0]?.trim().slice(0,lx),p=l.join(`
|
|
387
|
+
`);if(Buffer.byteLength(p)<=n)i.push({title:h||`Lines ${d}-${f}`,content:p});else{let m=this.#f(l,h||`Lines ${d}-${f}`,n);i.push(...m)}}return i}#U(e,r,n,s){let o=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=s&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:o,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#U(u,[...r,c],n,s);return}n.push({title:o,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#Q(e,r,n,s);return}n.push({title:o,content:i,hasCode:!1})}#X(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],s=r;for(let o of n)if(o in s&&(typeof s[o]=="string"||typeof s[o]=="number"))return o;return null}#Y(e,r,n,s,o){let i=e?`${e} > `:"";if(!o)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[o]);return s.length===1?`${i}${a(s[0])}`:s.length<=3?i+s.map(a).join(", "):`${i}${a(s[0])}\u2026${a(s[s.length-1])}`}#Q(e,r,n,s){let o=r.length>0?r.join(" > "):"(root)",i=this.#X(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#Y(o,c,l,a,i);n.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)>s&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#ee(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}};function Df(t,e){return t===void 0?e:`${t}::${e}`}import{readFileSync as bx,realpathSync as Bf}from"node:fs";import{relative as NN,resolve as In,sep as DN}from"node:path";Pn();import{resolve as Go}from"node:path";import{homedir as Zf}from"node:os";function jr(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Go(Zf(),e.replace(/^~[/\\]?/,"")):Go(e):Go(Zf(),".claude")}function AN(t=process.env){return Go(jr(t),"settings.json")}function Uf(t=process.env){let e=[],r=mt();if(r.platform!=="claude-code"){let s=Rn(r.platform);s&&s.length>0&&e.push(Go(Zf(),...s,"settings.json"))}let n=AN(t);return e.includes(n)||e.push(n),e}function vx(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function zN(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function MN(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function _x(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function LN(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let s=t.slice(0,n),o=t.slice(n+1),i=MN(s),a=_x(o);r=`^${i}(\\s${a})?$`}else r=`^${_x(t)}$`;return new RegExp(r,e?"i":"")}function jN(t,e=!1){let r="",n=0;for(;n<t.length;)t[n]==="*"&&t[n+1]==="*"?n+2<t.length&&t[n+2]==="/"?(r+="(.*/)?",n+=3):(r+=".*",n+=2):t[n]==="*"?(r+="[^/]*",n++):t[n]==="?"?(r+="[^/]",n++):(r+=t[n].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),n++);return new RegExp(`^${r}$`,e?"i":"")}function FN(t,e,r=!1){for(let n of e){let s=vx(n);if(s&&LN(s,r).test(t))return n}return null}function xx(t,e){let r=0;for(let n=e-1;n>=0&&t[n]==="\\";n--)r++;return r%2===1}function ZN(t){let e=[],r="",n=!1,s=!1,o=!1,i=0;for(let a=0;a<t.length;a++){let c=t[a],u=xx(t,a);c==="'"&&!s&&!o&&!u?(n=!n,r+=c):c==='"'&&!n&&!o&&!u?(s=!s,r+=c):c==="`"&&!n&&!s&&!u?(o=!o,r+=c):!n&&!s&&!o?c==="$"&&t[a+1]==="("&&!u?(i++,r+=c+t[a+1],a++):i>0&&c==="("&&!u?(i++,r+=c):c===")"&&i>0&&!u?(i--,r+=c):i===0&&(c===";"||c===`
|
|
388
|
+
`||c==="\r")&&!u?(e.push(r.trim()),r=""):i===0&&c==="|"&&t[a+1]==="|"||i===0&&c==="&"&&t[a+1]==="&"?(e.push(r.trim()),r="",a++):i===0&&c==="&"&&!u||i===0&&c==="|"?(e.push(r.trim()),r=""):r+=c:r+=c}return r.trim()&&e.push(r.trim()),e.filter(a=>a.length>0)}function Sx(t){let e=[],r=!1,n=!1,s=-1,o=[],i=[],a=0;for(let c=0;c<t.length;c++){let u=t[c],l=xx(t,c);if(u==="'"&&!n&&s===-1&&!l)r=!r;else if(u==='"'&&!r&&s===-1&&!l)n=!n;else if(u==="`"&&!r&&!n&&!l)if(s===-1)s=c+1;else{let d=t.slice(s,c);e.push(d),e.push(...Sx(d)),s=-1}else if(!r&&s===-1){if(u==="$"&&t[c+1]==="("&&!l)t[c+2]==="("?(a+=2,c+=2):(o.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=o.pop(),f=t.slice(d,c);e.push(f)}}}return e}function wx(t){let e=[],r=ZN(t);for(let n of r){e.push(n);for(let s of Sx(n))e.push(...wx(s))}return e}function qf(t){let e;try{e=bx(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let s=o=>Array.isArray(o)?o.filter(i=>typeof i=="string"&&vx(i)!==null):[];return{allow:s(n.allow),deny:s(n.deny),ask:s(n.ask)}}function Hf(t,e){let r=[];if(t){let s=In(t,".claude","settings.local.json"),o=qf(s);o&&r.push(o);let i=In(t,".claude","settings.json"),a=qf(i);a&&r.push(a)}let n=e!==void 0?[e]:Uf();for(let s of n){let o=qf(s);o&&r.push(o)}return r}function Qa(t,e,r){return Vf(t,"deny",e,r)}function Vf(t,e,r,n){let s=[],o=a=>{let c;try{c=bx(a,"utf-8")}catch{return null}let u;try{u=JSON.parse(c)}catch{return null}let l=u?.permissions?.[e];if(!Array.isArray(l))return[];let d=[];for(let f of l){if(typeof f!="string")continue;let h=zN(f);h&&h.tool===t&&d.push(h.glob)}return d};if(r){let a=o(In(r,".claude","settings.local.json"));a!==null&&s.push(a);let c=o(In(r,".claude","settings.json"));c!==null&&s.push(c)}let i=n!==void 0?[n]:Uf();for(let a of i){let c=o(a);c!==null&&s.push(c)}return s}function Wf(t,e,r=process.platform==="win32"||process.platform==="darwin"){let n=wx(t);for(let s of n)for(let o of e){let i=FN(s,o.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function Jo(t,e,r=process.platform==="win32"||process.platform==="darwin",n){let s=i=>i.replace(/\\/g,"/"),o=new Set;if(o.add(s(t)),n){let i=In(n,t);o.add(s(i));try{o.add(s(Bf(i)))}catch{}}for(let i of e)for(let a of i){let c=jN(s(a),r);for(let u of o)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function UN(t,e,r=process.platform==="win32"||process.platform==="darwin"){if(!e)return!0;let n=In(e),s=In(e,t),o=(i,a)=>{let c=i,u=a;if(r&&(c=c.toLowerCase(),u=u.toLowerCase()),c===u)return!0;let l=NN(c,u);return l===""?!0:!(l===".."||l.startsWith(".."+DN)||qN(l))};if(!o(n,s))return!1;try{let i=Bf(n),a=Bf(s);if(!o(i,a))return!1}catch{}return!0}function qN(t){if(t.startsWith("/"))return!0;if(t.length>=3&&t[1]===":"&&(t[2]==="\\"||t[2]==="/")){let e=t.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122}return!1}function Ex(t,e,r=[],n=process.platform==="win32"||process.platform==="darwin"){return UN(t,e,n)?{allowed:!0,reason:"inside"}:r.some(s=>s.length>0)&&Jo(t,r,n,e).denied?{allowed:!0,reason:"allow-rule"}:{allowed:!1,reason:"outside"}}var BN={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 HN(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let o=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);o.length>0&&e.push(o.join(" "))}return e}function kx(t,e){let r=BN[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let s of r){s.lastIndex=0;let o;for(;(o=s.exec(t))!==null;){let i=o[o.length-1];i&&n.push(i)}}return e==="python"&&n.push(...HN(t)),n}function Gf(t){let{language:e,exitCode:r,stdout:n,stderr:s}=t,o=e==="shell"&&r===1&&n.trim().length>0;return{isError:!o,output:o?n:`Exit code: ${r}
|
|
389
|
+
|
|
390
|
+
stdout:
|
|
391
|
+
${n}
|
|
392
|
+
|
|
393
|
+
stderr:
|
|
394
|
+
${s}`}}import{execFileSync as VN}from"node:child_process";function WN(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=VN("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function GN(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??WN,n=e(),s=r();return()=>{let o=e();return!(o!==n||o===0||o===1||!Number.isNaN(s)&&s>1&&r()===1)}}var JN=GN();function KN(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let r=Number.parseInt(e,10);return!Number.isFinite(r)||r<=0?3e4:1e3}function XN(t=process.env){let e=Number.parseInt(t.CONTEXT_MODE_BRIDGE_DEPTH??"",10);if(!Number.isFinite(e)||e<=0)return 0;let r=t.CONTEXT_MODE_BRIDGE_IDLE_MS;if(r!==void 0){let n=Number.parseInt(r,10);return Number.isFinite(n)&&n>0?n:0}return 18e4}function YN(t){return`[context-mode] Released an idle MCP helper after ${Math.round(t/1e3)}s of inactivity to free memory; it reconnects automatically on next use. (#854)`}var Ko=Date.now(),ec=0;function Jf(){Ko=Date.now()}function Tx(){ec++,Ko=Date.now()}function $x(){ec>0&&ec--,Ko=Date.now()}function Rx(t){if(!t)return;let e=typeof t.onmessage=="function"?t.onmessage.bind(t):null;e&&(t.onmessage=(r,n)=>{try{Jf()}catch{}return e(r,n)})}function Px(t){let e=t.checkIntervalMs??KN(),r=t.isParentAlive??JN,n=!1,s=()=>{n||(n=!0,t.onShutdown())},o=setInterval(()=>{r()||s()},e);o.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let l of i)process.on(l,s);let a=()=>{r()||s()};process.stdin.isTTY||process.stdin.on("end",a);let c=t.bridgeIdleMs??XN(),u;return c>0&&(Ko=Date.now(),u=setInterval(()=>{ec===0&&Date.now()-Ko>=c&&(process.stderr.write(YN(c)+`
|
|
395
|
+
`),s())},Math.max(1e3,Math.min(Math.floor(c/4),3e4))),u.unref()),()=>{n=!0,clearInterval(o),u&&clearInterval(u);for(let l of i)process.removeListener(l,s);process.stdin.removeListener("end",a)}}function Cx(t,e){if(e<=0)return"";if(t.length<=e)return t;let r=e,n=t.charCodeAt(r-1);return n>=55296&&n<=56319&&(r-=1),t.slice(0,r)}import{createHash as Yo}from"node:crypto";import{execFileSync as QN}from"node:child_process";import{accessSync as eD,constants as tD,existsSync as rc,mkdirSync as rD,realpathSync as nD,renameSync as Xf}from"node:fs";import{homedir as zx}from"node:os";import{dirname as sD,isAbsolute as Mx,join as Fr,resolve as Ss}from"node:path";var nr="CONTEXT_MODE_DIR",Lx="sessions",Ix="content",Zr=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,r,n=nr,s,o,i={}){super(o??uD(e,r,i),{cause:s}),this.name="StorageDirectoryError",this.kind=e,this.path=r,this.overrideEnvVar=n,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},Kf=new Map;function Yf(t){let e=t.env??process.env,r=t.legacySessionDirEnv,n=r?e[r]?.trim():void 0;return n&&r?(t.onLegacySessionDir?.(r,n),n):Fr(oD(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function oD(t,e,r){let n=e?r[e]:void 0;return n&&n.trim()!==""?Ox(n.trim()):Ox(t,zx())}function Ox(t,e){return t.startsWith("~")?Ss(zx(),t.replace(/^~[/\\]?/,"")):Mx(t)?Ss(t):e?Ss(e,t):Ss(t)}function iD(t,e,r){return new Zr(t,e,nr,void 0,[`Invalid ${nr} for context-mode ${t} directory: ${r}`,Ux()].join(`
|
|
396
|
+
`))}function jx(t){let e=process.env[nr];if(e===void 0)return{kind:"unset"};let r=e.trim();if(!r)return{kind:"ignored-empty",ignoredEnvVar:nr,ignoredReason:"empty"};if(!Mx(r))throw iD(t,r,`${nr} must be an absolute path.`);return{kind:"override",root:Ss(r)}}function aD(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function Fx(t,e){let r=jx(t);return r.kind!=="override"?null:{kind:t,path:Fr(r.root,e),envVar:nr,source:"override"}}function cD(t,e,r){return{kind:t,path:Ss(e()),envVar:null,source:"default",...r}}function Qo(t){let e=jx("session");return e.kind==="override"?{kind:"session",path:Fr(e.root,Lx),envVar:nr,source:"override"}:cD("session",t,aD(e))}function Qf(t){let e=Fx("content",Ix);if(e)return e;let r=Qo(t);return{kind:"content",path:Fr(sD(r.path),Ix),envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function em(t){let e=Fx("stats",Lx);if(e)return e;let r=Qo(t);return{kind:"stats",path:r.path,envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function Zx(t){return t.message}function nc(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function sc(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),r=Kf.get(e);if(r instanceof Zr)throw r;if(r===t.path)return r;try{return rD(t.path,{recursive:!0}),eD(t.path,tD.W_OK),Kf.set(e,t.path),t.path}catch(n){let s=new Zr(t.kind,dD(n)??t.path,nr,n,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw Kf.set(e,s),s}}function uD(t,e,r={}){return[`context-mode ${t} directory is not writable: ${e}`,lD(r),Ux()].filter(Boolean).join(`
|
|
397
|
+
`)}function lD(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function Ux(){return`Set ${nr} to a writable absolute path.`}function dD(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}var Xo;function On(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function Ax(t){let e=t;try{e=nD.native(t)}catch{}let r=On(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function qx(t,e){return QN("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function pD(t){let e=qx(t,["rev-parse","--show-toplevel"]);return e.length>0?On(e):null}function fD(t){let e=qx(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?On(e):null}function oc(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(Xo&&Xo.projectDir===t&&Xo.envSuffix===e)return Xo.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=pD(t),s=fD(t);if(n&&s){let o=Ax(n),i=Ax(s);o!==i&&(r=`__${Yo("sha256").update(o).digest("hex").slice(0,8)}`)}}catch{}return Xo={projectDir:t,envSuffix:e,suffix:r},r}function gr(t){return Yo("sha256").update(On(t)).digest("hex").slice(0,16)}function Ut(t){let e=On(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Yo("sha256").update(r).digest("hex").slice(0,16)}function Bx(t){let{projectDir:e,contentDir:r}=t,n=Ut(e),s=Fr(r,`${n}.db`);if(rc(s))return s;let o=gr(e);if(o===n)return s;let i=Fr(r,`${o}.db`);if(rc(i))try{Xf(i,s);for(let a of["-wal","-shm"])try{Xf(i+a,s+a)}catch{}}catch{}return s}function ei(t){return mD({...t,ext:".db"})}function mD(t){let{projectDir:e,sessionsDir:r,ext:n}=t,s=t.suffix??oc(e),o=Ut(e),i=Fr(r,`${o}${s}${n}`);if(rc(i))return i;let a=gr(e);if(a===o)return i;let c=Fr(r,`${a}${s}${n}`);if(rc(c))try{Xf(c,i)}catch{}return i}var Nx=1e3,Dx=5;function tc(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}var D={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",getUsageCursor:"getUsageCursor",setUsageCursor:"setUsageCursor",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"},hD=[["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"]];function Hx(t){let e=t.pragma("table_xinfo(session_events)"),r=new Set(e.map(s=>s.name)),n=!1;for(let[s,o]of hD)r.has(s)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${s} ${o}`),n=!0);return n&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),n}function Vx(t,e){let r=null;try{r=new e(t),Hx(r)}catch{}finally{try{r?.close()}catch{}}}var Zt=class extends Ja{constructor(e){super(e?.dbPath??Qv("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let r=this.db.pragma("table_xinfo(session_events)").find(n=>n.name==="data_hash");r&&r.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
|
|
398
|
+
CREATE TABLE IF NOT EXISTS session_events (
|
|
399
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
400
|
+
session_id TEXT NOT NULL,
|
|
401
|
+
type TEXT NOT NULL,
|
|
402
|
+
category TEXT NOT NULL,
|
|
403
|
+
priority INTEGER NOT NULL DEFAULT 2,
|
|
404
|
+
data TEXT NOT NULL,
|
|
405
|
+
project_dir TEXT NOT NULL DEFAULT '',
|
|
406
|
+
attribution_source TEXT NOT NULL DEFAULT 'unknown',
|
|
407
|
+
attribution_confidence REAL NOT NULL DEFAULT 0,
|
|
408
|
+
bytes_avoided INTEGER NOT NULL DEFAULT 0,
|
|
409
|
+
bytes_returned INTEGER NOT NULL DEFAULT 0,
|
|
410
|
+
source_hook TEXT NOT NULL,
|
|
411
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
412
|
+
data_hash TEXT NOT NULL DEFAULT ''
|
|
413
|
+
);
|
|
414
|
+
|
|
415
|
+
CREATE INDEX IF NOT EXISTS idx_session_events_session ON session_events(session_id);
|
|
416
|
+
CREATE INDEX IF NOT EXISTS idx_session_events_type ON session_events(session_id, type);
|
|
417
|
+
CREATE INDEX IF NOT EXISTS idx_session_events_priority ON session_events(session_id, priority);
|
|
418
|
+
|
|
419
|
+
CREATE TABLE IF NOT EXISTS session_meta (
|
|
420
|
+
session_id TEXT PRIMARY KEY,
|
|
421
|
+
project_dir TEXT NOT NULL,
|
|
422
|
+
started_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
423
|
+
last_event_at TEXT,
|
|
424
|
+
event_count INTEGER NOT NULL DEFAULT 0,
|
|
425
|
+
compact_count INTEGER NOT NULL DEFAULT 0
|
|
426
|
+
);
|
|
427
|
+
|
|
428
|
+
CREATE TABLE IF NOT EXISTS session_resume (
|
|
429
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
430
|
+
session_id TEXT NOT NULL UNIQUE,
|
|
431
|
+
snapshot TEXT NOT NULL,
|
|
432
|
+
event_count INTEGER NOT NULL,
|
|
433
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
434
|
+
consumed INTEGER NOT NULL DEFAULT 0
|
|
435
|
+
);
|
|
436
|
+
|
|
437
|
+
CREATE TABLE IF NOT EXISTS tool_calls (
|
|
438
|
+
session_id TEXT NOT NULL,
|
|
439
|
+
tool TEXT NOT NULL,
|
|
440
|
+
calls INTEGER NOT NULL DEFAULT 0,
|
|
441
|
+
bytes_returned INTEGER NOT NULL DEFAULT 0,
|
|
442
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
443
|
+
PRIMARY KEY (session_id, tool)
|
|
444
|
+
);
|
|
445
|
+
|
|
446
|
+
CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
|
|
447
|
+
`);try{Hx(this.db)}catch{}try{this.db.pragma("table_xinfo(session_meta)").some(r=>r.name==="usage_cursor")||this.db.exec("ALTER TABLE session_meta ADD COLUMN usage_cursor TEXT")}catch{}}prepareStatements(){this.stmts=new Map;let e=(r,n)=>{this.stmts.set(r,this.db.prepare(n))};e(D.insertEvent,`INSERT INTO session_events (
|
|
448
|
+
session_id, type, category, priority, data,
|
|
449
|
+
project_dir, attribution_source, attribution_confidence,
|
|
450
|
+
bytes_avoided, bytes_returned,
|
|
451
|
+
source_hook, data_hash
|
|
452
|
+
)
|
|
453
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),e(D.getEvents,`SELECT id, session_id, type, category, priority, data,
|
|
454
|
+
project_dir, attribution_source, attribution_confidence,
|
|
455
|
+
bytes_avoided, bytes_returned,
|
|
456
|
+
source_hook, created_at, data_hash
|
|
457
|
+
FROM session_events WHERE session_id = ? ORDER BY id ASC LIMIT ?`),e(D.getEventsByType,`SELECT id, session_id, type, category, priority, data,
|
|
458
|
+
project_dir, attribution_source, attribution_confidence,
|
|
459
|
+
bytes_avoided, bytes_returned,
|
|
460
|
+
source_hook, created_at, data_hash
|
|
461
|
+
FROM session_events WHERE session_id = ? AND type = ? ORDER BY id ASC LIMIT ?`),e(D.getEventsByPriority,`SELECT id, session_id, type, category, priority, data,
|
|
462
|
+
project_dir, attribution_source, attribution_confidence,
|
|
463
|
+
bytes_avoided, bytes_returned,
|
|
464
|
+
source_hook, created_at, data_hash
|
|
465
|
+
FROM session_events WHERE session_id = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(D.getEventsByTypeAndPriority,`SELECT id, session_id, type, category, priority, data,
|
|
466
|
+
project_dir, attribution_source, attribution_confidence,
|
|
467
|
+
bytes_avoided, bytes_returned,
|
|
468
|
+
source_hook, created_at, data_hash
|
|
469
|
+
FROM session_events WHERE session_id = ? AND type = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(D.getEventCount,"SELECT COUNT(*) AS cnt FROM session_events WHERE session_id = ?"),e(D.getLatestAttributedProject,`SELECT project_dir
|
|
470
|
+
FROM session_events
|
|
471
|
+
WHERE session_id = ? AND project_dir != ''
|
|
472
|
+
ORDER BY id DESC
|
|
473
|
+
LIMIT 1`),e(D.checkDuplicate,`SELECT 1 FROM (
|
|
474
|
+
SELECT type, data_hash FROM session_events
|
|
475
|
+
WHERE session_id = ? ORDER BY id DESC LIMIT ?
|
|
476
|
+
) AS recent
|
|
477
|
+
WHERE recent.type = ? AND recent.data_hash = ?
|
|
478
|
+
LIMIT 1`),e(D.evictLowestPriority,`DELETE FROM session_events WHERE id = (
|
|
479
|
+
SELECT id FROM session_events WHERE session_id = ?
|
|
480
|
+
ORDER BY priority ASC, id ASC LIMIT 1
|
|
481
|
+
)`),e(D.updateMetaLastEvent,`UPDATE session_meta
|
|
482
|
+
SET last_event_at = datetime('now'), event_count = event_count + 1
|
|
483
|
+
WHERE session_id = ?`),e(D.ensureSession,"INSERT OR IGNORE INTO session_meta (session_id, project_dir) VALUES (?, ?)"),e(D.getSessionStats,`SELECT session_id, project_dir, started_at, last_event_at, event_count, compact_count
|
|
484
|
+
FROM session_meta WHERE session_id = ?`),e(D.getSessionRollup,`SELECT
|
|
485
|
+
COUNT(*) AS tool_calls,
|
|
486
|
+
COALESCE(SUM(CASE WHEN category = 'error' THEN 1 ELSE 0 END), 0) AS errors,
|
|
487
|
+
COUNT(DISTINCT type) AS unique_tools,
|
|
488
|
+
COUNT(DISTINCT CASE WHEN category = 'file' THEN data END) AS unique_files,
|
|
489
|
+
CASE WHEN SUM(CASE WHEN type = 'git_commit' THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END AS has_commit,
|
|
490
|
+
CAST(COALESCE((MAX(strftime('%s', created_at)) - MIN(strftime('%s', created_at))) / 60.0, 0) AS INTEGER) AS duration_min,
|
|
491
|
+
COALESCE(SUM(CASE WHEN type = 'external_ref' THEN 1 ELSE 0 END), 0) AS sources_indexed,
|
|
492
|
+
CAST(COALESCE(SUM(bytes_avoided) / 1024.0, 0) AS INTEGER) AS total_chunks,
|
|
493
|
+
COALESCE(SUM(CASE WHEN type IN ('file_search', 'file_glob') THEN 1 ELSE 0 END), 0) AS search_queries
|
|
494
|
+
FROM session_events
|
|
495
|
+
WHERE session_id = ?`),e(D.getMaxFileEdits,`SELECT COALESCE(MAX(c), 0) AS max_file_edits
|
|
496
|
+
FROM (
|
|
497
|
+
SELECT COUNT(*) AS c
|
|
498
|
+
FROM session_events
|
|
499
|
+
WHERE session_id = ? AND category = 'file' AND type IN ('file_edit', 'file_write')
|
|
500
|
+
GROUP BY data
|
|
501
|
+
)`),e(D.getLatestCommitMessage,`SELECT data
|
|
502
|
+
FROM session_events
|
|
503
|
+
WHERE session_id = ? AND type = 'git_commit'
|
|
504
|
+
ORDER BY id DESC
|
|
505
|
+
LIMIT 1`),e(D.incrementCompactCount,"UPDATE session_meta SET compact_count = compact_count + 1 WHERE session_id = ?"),e(D.getUsageCursor,"SELECT usage_cursor FROM session_meta WHERE session_id = ?"),e(D.setUsageCursor,"UPDATE session_meta SET usage_cursor = ? WHERE session_id = ?"),e(D.upsertResume,`INSERT INTO session_resume (session_id, snapshot, event_count)
|
|
506
|
+
VALUES (?, ?, ?)
|
|
507
|
+
ON CONFLICT(session_id) DO UPDATE SET
|
|
508
|
+
snapshot = excluded.snapshot,
|
|
509
|
+
event_count = excluded.event_count,
|
|
510
|
+
created_at = datetime('now'),
|
|
511
|
+
consumed = 0`),e(D.getResume,"SELECT snapshot, event_count, consumed FROM session_resume WHERE session_id = ?"),e(D.markResumeConsumed,"UPDATE session_resume SET consumed = 1 WHERE session_id = ?"),e(D.claimLatestUnconsumedResume,`UPDATE session_resume
|
|
512
|
+
SET consumed = 1
|
|
513
|
+
WHERE id = (
|
|
514
|
+
SELECT id FROM session_resume
|
|
515
|
+
WHERE consumed = 0
|
|
516
|
+
AND session_id != ?
|
|
517
|
+
ORDER BY created_at DESC, id DESC
|
|
518
|
+
LIMIT 1
|
|
519
|
+
)
|
|
520
|
+
RETURNING session_id, snapshot`),e(D.deleteEvents,"DELETE FROM session_events WHERE session_id = ?"),e(D.deleteMeta,"DELETE FROM session_meta WHERE session_id = ?"),e(D.deleteResume,"DELETE FROM session_resume WHERE session_id = ?"),e(D.searchEvents,`SELECT id, session_id, category, type, data, created_at
|
|
521
|
+
FROM session_events
|
|
522
|
+
WHERE (project_dir = ? OR project_dir = '')
|
|
523
|
+
AND (data LIKE '%' || ? || '%' ESCAPE '\\' OR category LIKE '%' || ? || '%' ESCAPE '\\')
|
|
524
|
+
AND (? IS NULL OR category = ?)
|
|
525
|
+
ORDER BY id ASC
|
|
526
|
+
LIMIT ?`),e(D.getOldSessions,"SELECT session_id FROM session_meta WHERE started_at < datetime('now', ? || ' days')"),e(D.incrementToolCall,`INSERT INTO tool_calls (session_id, tool, calls, bytes_returned)
|
|
527
|
+
VALUES (?, ?, 1, ?)
|
|
528
|
+
ON CONFLICT(session_id, tool) DO UPDATE SET
|
|
529
|
+
calls = calls + 1,
|
|
530
|
+
bytes_returned = bytes_returned + excluded.bytes_returned,
|
|
531
|
+
updated_at = datetime('now')`),e(D.getToolCallTotals,`SELECT COALESCE(SUM(calls), 0) AS calls,
|
|
532
|
+
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
533
|
+
FROM tool_calls WHERE session_id = ?`),e(D.getToolCallByTool,`SELECT tool, calls, bytes_returned
|
|
534
|
+
FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(D.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
535
|
+
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
536
|
+
FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",s,o){let i=Yo("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),a=String(s?.projectDir??r.project_dir??this._getSessionProjectDir(e)).trim(),c=String(s?.source??r.attribution_source??"unknown"),u=Number(s?.confidence??r.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=tc(o?.bytesAvoided),f=tc(o?.bytesReturned),h=this.db.transaction(()=>{if(this.stmt(D.checkDuplicate).get(e,Dx,r.type,i))return;this.stmt(D.getEventCount).get(e).cnt>=Nx&&this.stmt(D.evictLowestPriority).run(e),this.stmt(D.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,l,d,f,n,i),this.stmt(D.updateMetaLastEvent).run(e)});this.withRetry(()=>h())}bulkInsertEvents(e,r,n="PostToolUse",s,o){if(!r||r.length===0)return;if(r.length===1){this.insertEvent(e,r[0],n,s?.[0],o?.[0]);return}let i=r.map((c,u)=>{let l=Yo("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),d=s?.[u],f=String(d?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),h=f===""?"":On(f),p=String(d?.source??c.attribution_source??"unknown"),m=Number(d?.confidence??c.attribution_confidence??0),g=Number.isFinite(m)?Math.max(0,Math.min(1,m)):0,y=o?.[u],b=tc(y?.bytesAvoided),_=tc(y?.bytesReturned);return{event:c,dataHash:l,projectDir:h,attributionSource:p,attributionConfidence:g,bytesAvoided:b,bytesReturned:_}}),a=this.db.transaction(()=>{let c=this.stmt(D.getEventCount).get(e).cnt;for(let u of i)this.stmt(D.checkDuplicate).get(e,Dx,u.event.type,u.dataHash)||(c>=Nx?this.stmt(D.evictLowestPriority).run(e):c++,this.stmt(D.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,n,u.dataHash));this.stmt(D.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,r){let n=r?.limit??1e3,s=r?.type,o=r?.minPriority;return s&&o!==void 0?this.stmt(D.getEventsByTypeAndPriority).all(e,s,o,n):s?this.stmt(D.getEventsByType).all(e,s,n):o!==void 0?this.stmt(D.getEventsByPriority).all(e,o,n):this.stmt(D.getEvents).all(e,n)}getEventCount(e){return this.stmt(D.getEventCount).get(e).cnt}getEventBytesSummary(e){let r=this.stmt(D.getEventBytesSummary).get(e);return{bytesAvoided:Number(r?.bytes_avoided??0),bytesReturned:Number(r?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(D.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,r,n,s){try{let o=e.replace(/[%_]/g,a=>"\\"+a),i=s??null;return this.stmt(D.searchEvents).all(n,o,o,i,i,r)}catch{return[]}}getSessionIdsForProject(e){try{let r=On(e);return this.db.prepare(`SELECT DISTINCT session_id
|
|
537
|
+
FROM session_events
|
|
538
|
+
WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(r).map(s=>s.session_id)}catch{return[]}}ensureSession(e,r){this.stmt(D.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(D.getSessionStats).get(e)??null}getSessionRollup(e){let r=this.stmt(D.getSessionRollup).get(e),n=this.stmt(D.getMaxFileEdits).get(e),s=this.stmt(D.getLatestCommitMessage).get(e),o=this.getSessionStats(e),i=(r?.tool_calls??0)>0?r?.unique_files??0:0,a=r?.errors??0,c=Math.min(i,a);return{tool_calls:r?.tool_calls??0,errors:r?.errors??0,unique_tools:r?.unique_tools??0,unique_files:r?.unique_files??0,max_file_edits:n?.max_file_edits??0,has_commit:r?.has_commit??0,commit_message:s?.data??"",edit_test_cycles:c,duration_min:r?.duration_min??0,compact_count:o?.compact_count??0,sources_indexed:r?.sources_indexed??0,total_chunks:r?.total_chunks??0,search_queries:r?.search_queries??0}}incrementCompactCount(e){this.stmt(D.incrementCompactCount).run(e)}getUsageCursor(e){return this.stmt(D.getUsageCursor).get(e)?.usage_cursor??null}setUsageCursor(e,r){this.stmt(D.setUsageCursor).run(r,e)}upsertResume(e,r,n){this.stmt(D.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(D.getResume).get(e)??null}markResumeConsumed(e){this.stmt(D.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(D.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let s=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(D.incrementToolCall).run(e,r,s)}catch{}}getToolCallStats(e){try{let r=this.stmt(D.getToolCallTotals).get(e),n=this.stmt(D.getToolCallByTool).all(e),s={};for(let o of n)s[o.tool]={calls:o.calls,bytesReturned:o.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:s}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(D.deleteEvents).run(e),this.stmt(D.deleteResume).run(e),this.stmt(D.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(D.getOldSessions).all(r);for(let{session_id:s}of n)this.deleteSession(s);return n.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{existsSync as tm,unlinkSync as gD}from"node:fs";import{join as ti}from"node:path";var yD=["","-wal","-shm"];function rm(t,e){try{return gD(t),e.push(t),!0}catch{return!1}}function ic(t,e){let r=!1;for(let n of yD)rm(`${t}${n}`,e)&&n===""&&(r=!0);return r}function Wx(t){let{projectDir:e,sessionsDir:r,storePath:n,contentDir:s,legacyContentDir:o,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 _=oc(e),x=Ut(e),w=gr(e),I=x===w?[x]:[x,w],R=!1;for(let V of I){let $=ti(r,`${V}${_}.db`);if(!tm($))continue;let T=null;try{T=new Zt({dbPath:$});let F=T.getEvents(a).length;T.deleteSession(a),F>0&&(R=!0)}catch{}finally{try{T?.close()}catch{}}}R&&u.push(`session rows for ${a}`);let M=[];if(n&&tm(n)&&M.push(n),s){let V=Ut(e),$=gr(e),T=V===$?[V]:[V,$];for(let F of T){let de=ti(s,`${F}.db`);tm(de)&&!M.includes(de)&&M.push(de)}}let z=!1;for(let V of M)try{let $=He(),T=new $(V,{timeout:3e4});try{let F=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),F>0&&(z=!0)}finally{try{T.close()}catch{}}}catch{}return z&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let f=!1;if(n&&ic(n,l)&&(f=!0),s){let _=Ut(e),x=gr(e),w=_===x?[_]:[_,x];for(let I of w){let R=ti(s,`${I}.db`);ic(R,l)&&(f=!0)}}if(f&&u.push("knowledge base (FTS5)"),o){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let _=ti(o,`${i}.db`);ic(_,l)}let h=oc(e),p=Ut(e),m=gr(e),g=p===m?[p]:[p,m],y=!1,b=!1;for(let _ of g){let x=ti(r,`${_}${h}`);ic(`${x}.db`,l)&&(y=!0),rm(`${x}-events.md`,l)&&(b=!0),rm(`${x}.cleanup`,l)}return y&&u.push("session events DB"),b&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}import{existsSync as _D}from"node:fs";function nm(t,e){try{if(!_D(t))return;let r=new Zt({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function Gx(t){nm(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function Jx(t){nm(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function Kx(t){nm(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}import{existsSync as Xx}from"node:fs";function Yx(t,e,r){try{if(!Xx(t))return;let n=new Zt({dbPath:t});try{let s=n.getLatestSessionId();if(!s)return;n.incrementToolCall(s,e,r)}finally{n.close()}}catch{}}function Qx(t){try{if(!Xx(t))return null;let e=new Zt({dbPath:t});try{let r=e.getLatestSessionId();if(!r)return null;let n=e.getToolCallStats(r),s={},o={};for(let[a,c]of Object.entries(n.byTool))s[a]=c.calls,o[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(r);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(s).length===0&&Object.keys(o).length===0?{calls:s,bytesReturned:o,sessionStart:i}:{calls:s,bytesReturned:o,sessionStart:i}}finally{e.close()}}catch{return null}}import{appendFileSync as bD,readFileSync as T2,rmSync as $2}from"node:fs";import{tmpdir as vD}from"node:os";import{basename as xD,join as SD}from"node:path";function wD(t,e=vD()){return SD(e,`context-mode-retrieval-${xD(t)}.txt`)}function eS(t,e,r){if(!(!Number.isFinite(e)||e<=0))try{bD(wD(t,r),`${Math.floor(e)}
|
|
539
|
+
`)}catch{}}import{existsSync as sm,readFileSync as ED,readdirSync as kD,statSync as TD}from"node:fs";import{join as ws,isAbsolute as $D}from"node:path";var tS=process.env.DEBUG?.includes("context-mode");function nS(t,e=5,r,n,s){let o=[],i=s?.getInstructionFiles()??["CLAUDE.md"],a=s?.getConfigDir(),u=(a?rS(r,a):null)??n??jr(),l=s?.getMemoryDir(r),d=ws(u,"memory"),f=r?ws(d,Ut(r)):d,h=l?rS(r,l):f,p=[];if(r)for(let m of i){let g=ws(r,m);sm(g)&&p.push({path:g,label:`project/${m}`})}if(u&&u!==r)for(let m of i){let g=ws(u,m);sm(g)&&p.push({path:g,label:`user/${m}`})}if(h&&sm(h))try{let m=kD(h).filter(g=>g.endsWith(".md"));for(let g of m)p.push({path:ws(h,g),label:`memory/${g}`})}catch(m){tS&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${m}
|
|
540
|
+
`)}for(let m of p){if(o.length>=e)break;try{let g;try{if(g=TD(m.path),g.size>1e6)continue}catch{continue}let y=ED(m.path,"utf-8"),b=y.toLowerCase();for(let _ of t){if(o.length>=e)break;let w=_.toLowerCase().split(/\s+/).filter(R=>R.length>=3);if(w.some(R=>{try{return new RegExp(`\\b${R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return b.includes(R)}})){let R=w.reduce((F,de)=>{let nt=b.indexOf(de);return nt>=0&&(F<0||nt<F)?nt:F},-1),M=Math.max(0,R-200),z=Math.min(y.length,R+500),V=y.lastIndexOf(`
|
|
541
|
+
|
|
542
|
+
`,M),$=y.indexOf(`
|
|
543
|
+
|
|
544
|
+
`,z);V>=0&&(M=V+2),$>=0&&(z=$);let T=y.slice(M,z).trim();o.push({title:`[auto-memory] ${m.label}`,content:T,source:m.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){tS&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
|
|
545
|
+
`)}}return o.slice(0,e)}function rS(t,e){return e?$D(e)||!t?e:ws(t,e):t??""}var ac=process.env.DEBUG?.includes("context-mode");function sS(t){let{query:e,limit:r,store:n,sort:s="relevance",source:o,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l,projectScope:d}=t,f=[],h=new Date().toISOString(),p;if(typeof d=="string"&&a)try{p=new Set(a.getSessionIdsForProject(d))}catch(m){ac&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${m}
|
|
546
|
+
`)}try{let m=n.searchWithFallback(e,r,o,i,"like",p);f.push(...m.map(g=>({title:g.title,content:g.content,source:g.source,origin:"current-session",timestamp:g.timestamp||h,rank:g.rank,matchLayer:g.matchLayer,highlighted:g.highlighted,contentType:g.contentType})))}catch(m){ac&&process.stderr.write(`[ctx] ContentStore search failed: ${m}
|
|
547
|
+
`)}if(s==="timeline"){try{if(a){let m=a.searchEvents(e,r,c||"",o);f.push(...m.map(g=>({title:`[${g.category}] ${g.type}`,content:g.data,source:"prior-session",origin:"prior-session",timestamp:g.created_at})))}}catch(m){ac&&process.stderr.write(`[ctx] SessionDB search failed: ${m}
|
|
548
|
+
`)}try{let m=nS([e],r,c,u,l);f.push(...m)}catch(m){ac&&process.stderr.write(`[ctx] auto-memory search failed: ${m}
|
|
549
|
+
`)}}for(let m of f)m.timestamp&&!m.timestamp.includes("T")&&(m.timestamp=m.timestamp.replace(" ","T")+"Z");return s==="timeline"&&f.sort((m,g)=>(m.timestamp||"").localeCompare(g.timestamp||"")),f.slice(0,r)}function RD(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return[t]}return t}function oS(t){let e=t?{project:C.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 C.object({queries:C.preprocess(RD,C.array(C.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:C.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:C.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:C.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:C.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 iS(t,e,r){if(e)return t===void 0?r():t==="global"?null:t}var om=!!process.env.CONTEXT_MODE_PROJECT_DIR;var cc=class{#e;#t=new Map;#r;constructor(e,r=4096){this.#e=e,this.#r=Math.max(1,r)}record(e,r=Date.now()){let n=this.#t.get(e);return(!n||r-n.windowStart>this.#e.windowMs)&&(n={count:0,windowStart:r},this.#t.set(e,n),this.#s()),n.count++,{count:n.count,windowStart:n.windowStart,blocked:n.count>this.#e.blockAfter,softCapped:n.count>this.#e.softCapAfter}}size(){return this.#t.size}#s(){if(this.#t.size<=this.#r)return;let e,r=1/0;for(let[n,s]of this.#t)s.windowStart<r&&(r=s.windowStart,e=n);e!==void 0&&this.#t.delete(e)}};Pn();Lf();function PD(t){let e=[];if(t&&typeof t=="object"){let r=t.command;typeof r=="string"&&e.push(r);let n=t.hooks;if(Array.isArray(n)){for(let s of n)if(s&&typeof s=="object"){let o=s.command;typeof o=="string"&&e.push(o)}}}return e}function CD(t){let e=Mv(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function aS(t,e){let r=new Set,n=t.generateHookConfig(e);for(let s of Object.values(n))if(Array.isArray(s))for(let o of s)for(let i of PD(o)){let a=CD(i);a&&r.add(a)}return[...r]}function cS(t){let e="",r=!1,n=!1,s=!1;for(let c=0;c<t.length;c++){let u=t[c],l=t[c+1];if(s){u==="*"&&l==="/"&&(s=!1,c++);continue}if(n){e+=u,n=!1;continue}if(u==="\\"){e+=u,n=r;continue}if(u==='"'){r=!r,e+=u;continue}if(!r&&u==="/"&&l==="/"){for(;c<t.length&&t[c]!==`
|
|
550
|
+
`;)c++;c<t.length&&(e+=`
|
|
551
|
+
`);continue}if(!r&&u==="/"&&l==="*"){s=!0,c++;continue}e+=u}let o="",i=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];if(a){o+=u,a=!1;continue}if(u==="\\"){o+=u,a=i;continue}if(u==='"'){i=!i,o+=u;continue}if(!i&&u===","){let l=c+1;for(;l<e.length&&(e[l]===" "||e[l]===" "||e[l]==="\r"||e[l]===`
|
|
552
|
+
`);)l++;if(e[l]==="}"||e[l]==="]")continue}o+=u}return o}Pn();import*as Oe from"node:fs";import*as uS from"node:os";import*as Es from"node:path";var ID=["CONTEXT_MODE_PROJECT_DIR"],OD=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"];function uc(t){return t?/[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function AD(t){if(!Oe.existsSync(t.projectsRoot))return;let e,r=0;try{for(let n of Oe.readdirSync(t.projectsRoot)){let s=Es.join(t.projectsRoot,n),o;try{o=Oe.statSync(s)}catch{continue}if(!o.isDirectory())continue;let i;try{i=Oe.readdirSync(s)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=Es.join(s,a);try{let u=Oe.statSync(c).mtimeMs;u>r&&(r=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-r>t.maxAgeMs))try{let n=Oe.openSync(e,"r");try{let s=Buffer.alloc(8192),o=Oe.readSync(n,s,0,s.length,0),i=s.subarray(0,o).toString("utf-8");for(let a of i.split(`
|
|
553
|
+
`).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{Oe.closeSync(n)}}catch{}}function ND(t){let e=t?.codexHome??process.env.CODEX_HOME??Es.join(uS.homedir(),".codex"),r=Es.join(e,"sessions");if(!Oe.existsSync(r))return null;let n=4,s=1e4,o=0,i,a=0,c=(u,l)=>{if(o>=s)return;let d;try{d=Oe.readdirSync(u)}catch{return}d.sort().reverse();for(let f of d){if(o>=s)return;o++;let h=Es.join(u,f),p;try{p=Oe.statSync(h)}catch{continue}if(p.isDirectory()){l<n&&c(h,l+1);continue}if(!p.isFile()||!f.endsWith(".jsonl"))continue;let m=p.mtimeMs;m>a&&(a=m,i=h)}};try{c(r,0)}catch{return null}if(!i||typeof t?.transcriptMaxAgeMs=="number"&&(t.now??Date.now())-a>t.transcriptMaxAgeMs)return null;try{let u=Oe.openSync(i,"r");try{let l=Buffer.alloc(1048576),d=Oe.readSync(u,l,0,l.length,0),f=l.subarray(0,d).toString("utf-8");for(let h of f.split(`
|
|
554
|
+
`).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 uc(m)?null:m}catch{return null}}finally{Oe.closeSync(u)}}catch{return null}return null}function lS(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:s,transcriptMaxAgeMs:o,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...jf(a),...ID]:OD;for(let l of u){let d=e[l];if(d&&!uc(d))return d}if(s){let l=AD({projectsRoot:s,maxAgeMs:o,nowMs:i});if(l&&!uc(l))return l}if(a==="codex"){let l=ND({codexHome:c,transcriptMaxAgeMs:o,now:i});if(l)return l}return n&&!uc(n)?n:r}import{execFileSync as DD}from"node:child_process";import{existsSync as yr,readdirSync as ks,statSync as zD}from"node:fs";import{homedir as hc}from"node:os";import{join as vt,sep as MD}from"node:path";function _S(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let s=0;s<3;s++){if((r[s]??0)>(n[s]??0))return!0;if((r[s]??0)<(n[s]??0))return!1}return!1}var dc={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"},LD={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"},Ts=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,r){let n=e-r,s=e>0?Math.round(n/e*1e3)/10:0;return{rawBytes:e,contextBytes:r,savedBytes:n,savedPercent:s}}static thinkInCodeComparison(e,r){let n=r>0?Math.round(e/r*10)/10:0;return{fileBytes:e,outputBytes:r,ratio:n}}static toolSavings(e){return e.map(r=>({...r,savedBytes:r.rawBytes-r.contextBytes}))}static sandboxIO(e,r){return{inputBytes:e,outputBytes:r}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let r=new Map;for(let s of e){let o;try{o=JSON.parse(s.data)}catch{continue}let i=typeof o.tool_name=="string"?o.tool_name:null;if(!i)continue;let a=r.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,o.truncated!==!0&&o.params&&typeof o.params=="object"){let c=o.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}r.set(i,a)}let n=[];for(let[s,o]of r){let i=null,a=null;if(o.concurrencies.length>0){o.concurrencies.sort((l,d)=>l-d);let c=o.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:s,calls:o.calls,median_concurrency:i,max_concurrency:a})}return n.sort((s,o)=>o.calls-s.calls||s.tool_name.localeCompare(o.tool_name)),n}queryAll(e){let n=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",s=Object.values(e.bytesReturned).reduce((T,F)=>T+F,0),o=Object.values(e.calls).reduce((T,F)=>T+F,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+s,c=a/Math.max(s,1),u=a>0?Math.round((1-s/a)*100):0,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)})),h=((Date.now()-e.sessionStart)/6e4).toFixed(1),p,m=e.cacheMisses??0;if(e.cacheHits>0||e.cacheBytesSaved>0||m>0){let T=a+e.cacheBytesSaved,F=T/Math.max(s,1),de=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),nt=e.cacheHits+m,or=nt>0?e.cacheHits/nt:0;p={hits:e.cacheHits,misses:m,hit_rate:or,bytes_saved:e.cacheBytesSaved,ttl_hours_left:de,total_with_cache:T,total_savings_ratio:F}}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),_=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,x=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),w=x?!x.consumed:!1,I=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),R=new Map;for(let T of I){R.has(T.category)||R.set(T.category,new Set);let F=R.get(T.category);if(F.size<5){let de=T.data;T.category==="file"?de=T.data.split("/").pop()||T.data:(T.category==="prompt"||T.category==="user-prompt")&&(de=de.length>50?de.slice(0,47)+"...":de),de.length>40&&(de=de.slice(0,37)+"..."),F.add(de)}}let M=y.map(T=>({category:T.category,count:T.cnt,label:dc[T.category]||T.category,preview:R.get(T.category)?Array.from(R.get(T.category)).join(", "):"",why:LD[T.category]||"Survives context resets"})),z=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),$=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:dc[T.category]||T.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(s/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:d,total_calls:o,total_bytes_returned:s,kept_out:i,total_processed:a},cache:p,session:{id:n,uptime_min:h},continuity:{total_events:g,by_category:M,compact_count:_,resume_ready:w},projectMemory:{total_events:z.cnt,session_count:z.sessions,by_category:$}}}};function jD(t){let e=t?.home??hc();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(([n,s])=>{let o=vt(e,...s,"context-mode");return{name:n,sessionsDir:vt(o,"sessions"),contentDir:vt(o,"content")}})}function FD(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function ri(t){let e=jr(),r=t?.sessionsDir??vt(e,"context-mode","sessions"),n=t?.memoryRoot??vt(e,"projects"),s=0,o=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(yr(r)){let h=[];try{h=ks(r).filter(p=>p.endsWith(".db"))}catch{}if(h.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():He()}catch{}if(p)for(let m of h){let g=vt(r,m);try{let y=new p(g,{readonly:!0});try{let b=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),_=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();s+=b?.cnt??0,o+=_?.cnt??0;try{let x=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let w of x)w.category&&(u[w.category]=(u[w.category]??0)+(w.cnt??0))}catch{}try{let x=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();x?.bytes&&(i+=x.bytes)}catch{}try{let x=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(x?.t){let w=x.t.endsWith("Z")?x.t:x.t+"Z",I=Date.parse(w);Number.isFinite(I)&&I<a&&(a=I)}}catch{}try{let x=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let w of x)w.p&&c.add(w.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,f={};if(yr(n)){let h=[];try{h=ks(n).filter(p=>{try{return zD(vt(n,p)).isDirectory()}catch{return!1}})}catch{}for(let p of h){let m=vt(n,p,"memory");if(!yr(m))continue;let g=[];try{g=ks(m).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let b=FD(y);f[b]=(f[b]??0)+1}}}}return{totalEvents:s,totalSessions:o,autoMemoryCount:l,autoMemoryProjects:d,autoMemoryByPrefix:f,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function bS(t){let e=t.sessionsDir??vt(hc(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!yr(e))return n;let s=[];try{s=ks(e).filter(_=>!(!_.endsWith(".db")||t.worktreeHash&&!_.startsWith(t.worktreeHash)))}catch{return n}if(s.length===0)return n;let o=null;try{o=t.loadDatabase?t.loadDatabase():He()}catch{return n}if(!o)return n;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,f=0,h=0,p=new Map,m=_=>Math.floor(_/864e5)*864e5;for(let _ of s){let x=vt(e,_),w=!1;try{let I=new o(x,{readonly:!0});try{let R=I.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let z of R)z.category&&(i[z.category]=(i[z.category]??0)+(z.cnt??0),a+=z.cnt??0,w=!0);let M=I.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(M?.mn){let z=Date.parse(M.mn+(M.mn.endsWith("Z")?"":"Z"));Number.isFinite(z)&&z<d&&(d=z)}if(M?.mx){let z=Date.parse(M.mx+(M.mx.endsWith("Z")?"":"Z"));Number.isFinite(z)&&z>f&&(f=z)}try{let z=I.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 V of z){if(!V.sec)continue;let $=parseInt(V.sec,10)*1e3;if(!Number.isFinite($))continue;let T=m($),F=p.get(T)??{count:0,rescueBytes:0};F.count+=V.cnt??0,p.set(T,F)}}catch{}try{let z=I.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(r);if(z?.bytes&&(u+=z.bytes),z?.n&&(l+=z.n),z?.lastSec){let V=parseInt(z.lastSec,10)*1e3;if(Number.isFinite(V)&&V>h&&(h=V),Number.isFinite(V)&&(z?.bytes??0)>0){let $=m(V),T=p.get($)??{count:0,rescueBytes:0};T.rescueBytes=Math.max(T.rescueBytes,z.bytes),p.set($,T)}}}catch{}}finally{I.close()}}catch{}w&&c++}let g=d<f?(f-d)/864e5:0,y=Object.entries(i).filter(([,_])=>_>0).map(([_,x])=>({category:_,count:x,label:dc[_]||_})).sort((_,x)=>x.count-_.count),b=[...p.entries()].sort((_,x)=>_[0]-x[0]).map(([_,x])=>({ms:_,count:x.count,...x.rescueBytes>0?{rescueBytes:x.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:b}}function ZD(t,e,r){if(!t||!e||!yr(e))return 0;let n=null;try{n=r?.loadDatabase?r.loadDatabase():He()}catch{return 0}if(!n)return 0;try{let s=new n(e,{readonly:!0});try{let o=s.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
555
|
+
FROM chunks WHERE session_id = ?`).get(t);return Number(o?.bytes??0)}finally{s.close()}}catch{return 0}}function vS(t,e){if(!t||!yr(t))return 0;let r=null;try{r=e?.loadDatabase?e.loadDatabase():He()}catch{return 0}if(!r)return 0;try{let n=new r(t,{readonly:!0});try{let s=n.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
556
|
+
FROM chunks`).get();return Number(s?.bytes??0)}finally{n.close()}}catch{return 0}}function pc(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},r=t.sessionsDir??vt(hc(),".claude","context-mode","sessions");if(!yr(r))return e;let n=[];try{n=ks(r).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let s=null;try{s=t.loadDatabase?t.loadDatabase():He()}catch{return e}if(!s)return e;let o=0,i=0,a=0,c=0;for(let d of n){let f=vt(r,d);Vx(f,s);try{let h=new s(f,{readonly:!0});try{if(t.sessionId){let p=h.prepare(`SELECT
|
|
557
|
+
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
558
|
+
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
559
|
+
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
560
|
+
FROM session_events WHERE session_id = ?`).get(t.sessionId);p&&(o+=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 WHERE session_id = ?").get(t.sessionId);m?.bytes&&(c+=Number(m.bytes))}catch{}try{let m=h.prepare(`SELECT COALESCE(SUM(bytes_returned), 0) AS bytes FROM tool_calls
|
|
561
|
+
WHERE session_id = ? AND tool IN ('ctx_search', 'ctx_fetch_and_index')`).get(t.sessionId);m?.bytes&&(a+=Number(m.bytes))}catch{}}else if(t.projectDir){let p=h.prepare(`SELECT
|
|
562
|
+
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
563
|
+
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
564
|
+
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
565
|
+
FROM session_events
|
|
566
|
+
WHERE session_id IN (
|
|
567
|
+
SELECT session_id FROM session_meta WHERE project_dir = ?
|
|
568
|
+
)`).get(t.projectDir);p&&(o+=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
|
|
569
|
+
FROM session_resume
|
|
570
|
+
WHERE session_id IN (
|
|
571
|
+
SELECT session_id FROM session_meta WHERE project_dir = ?
|
|
572
|
+
)`).get(t.projectDir);m?.bytes&&(c+=Number(m.bytes))}catch{}try{let m=h.prepare(`SELECT COALESCE(SUM(bytes_returned), 0) AS bytes
|
|
573
|
+
FROM tool_calls
|
|
574
|
+
WHERE session_id IN (
|
|
575
|
+
SELECT session_id FROM session_meta WHERE project_dir = ?
|
|
576
|
+
)
|
|
577
|
+
AND tool IN ('ctx_search', 'ctx_fetch_and_index')`).get(t.projectDir);m?.bytes&&(a+=Number(m.bytes))}catch{}}else{let p=h.prepare(`SELECT
|
|
578
|
+
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
579
|
+
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
580
|
+
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
581
|
+
FROM session_events`).get();p&&(o+=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{}try{let m=h.prepare(`SELECT COALESCE(SUM(bytes_returned), 0) AS bytes FROM tool_calls
|
|
582
|
+
WHERE tool IN ('ctx_search', 'ctx_fetch_and_index')`).get();m?.bytes&&(a+=Number(m.bytes))}catch{}}}finally{h.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=ZD(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let l=Math.floor((o+i+c)/4);return{eventDataBytes:o,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:l}}function im(t){let e=pc({worktreeHash:t.worktreeHash,sessionsDir:t.sessionsDir}),r=pc({sessionId:t.sessionId,worktreeHash:t.worktreeHash,sessionsDir:t.sessionsDir,contentDbPath:t.contentDbPath}),n=r.bytesReturned,s=e.bytesAvoided+e.bytesReturned,o=Math.max(0,s-n);return{eventDataBytes:e.eventDataBytes,bytesAvoided:o,bytesReturned:n,snapshotBytes:e.snapshotBytes,contentBytes:r.contentBytes,totalSavedTokens:Math.floor((e.eventDataBytes+o+e.snapshotBytes)/4)}}var UD={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};function qD(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(!yr(t.sessionsDir))return n;let s=[];try{s=ks(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return n}if(s.length===0)return n;let o=null;try{o=e()}catch{return n}if(!o)return n;let i=new Set,a=new Set;for(let l of s){let d=vt(t.sessionsDir,l);try{let f=new o(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 gc(t){let e=jD({home:t?.home}),r=t?.loadDatabase??He,n={...UD,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},s=[],o=0,i=0,a=0;for(let c of e){if(!yr(c.sessionsDir))continue;let u=qD(c,r,n);s.push(u),o+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:o,totalSessions:i,totalBytes:a,perAdapter:s}}var xS={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},BD={"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 fc(t){return BD[t]??t}function Ve(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 HD(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 lc(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function VD(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!lc(e)&&(e=""),!e){if(process.platform==="darwin"){try{let n=DD("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}e&&!lc(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-")),e&&!lc(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 lc(e)||(e="en-US"),{locale:e,tz:r||"UTC"}}function dS(t){let e=hc();return e?t===e?"~":t.startsWith(e+MD)?"~"+t.slice(e.length):t:t}function WD(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*ni(),s=(y,b=2)=>y.toFixed(b),o=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,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(` $${s(n)} of ${m} tokens your team didn't burn.`):p?g.push(` $${s(n)} of tokens your team didn't burn.`):g.push(` $${s(n)} of Opus 4.7 tokens your team didn't burn.`),g.push(` context-mode kept ${Ve(t)} out of context \u2014 that's ${o} 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 GD(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:s,cwd:o,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],f=e.events*gS,h=Math.round((e.snapshotBytes??0)/4),p=f+h,m=s?.conversation?.totalSavedTokens??0,g=Math.max(p,m),y=(r?.totalEvents??0)*gS,b=Math.round((r?.rescueBytes??0)/4),_=y+b,x=s?.lifetime?.totalSavedTokens??0,w=Math.max(_,x),I=s?.lifetime?.bytesReturned??0,R=s?.lifetime?.bytesAvoided??0,M=I+R>0?Math.max(1,Math.floor(I/4)):Math.max(1,Math.round(w*.02)),z=n?.totalBytes&&n.totalBytes>0?n.totalBytes:w*4,V=s?.conversation?s.conversation.eventDataBytes+s.conversation.bytesAvoided+s.conversation.snapshotBytes:g*4,$=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=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,F=T>0?Math.max(1,Math.round((c-T)/864e5)):0,de=n?.totalSessions??r?.totalSessions??1,nt=n?.perAdapter.filter(Pe=>Pe.isReal).length??0,or;if(n&&nt>=2)or=`across ${nt} AI tools`;else if(n&&nt===1){let Pe=n.perAdapter.find(Ct=>Ct.isReal);or=`in ${Pe?fc(Pe.name):"Claude Code"}`}else or="in Claude Code";F>0?d.push(` Across ${F} days you ran ${qt(de)} conversations ${or}.`):d.push(` You ran ${qt(de)} conversations ${or}.`);let Oc=F>0?z/F:0;d.push(` context-mode kept ${Ve(z)} out of your context window \u2014 about ${Ve(Oc)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let wm=e.firstEventMs&&e.firstEventMs>0?pS(e.firstEventMs,i,a):"";if(wm?d.push(` This conversation started ${wm} in ${dS(o)}.`):d.push(` This conversation lives in ${dS(o)}.`),d.push(` ${$}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Pe=e.lastRescueMs&&e.lastRescueMs>0?pS(e.lastRescueMs,i,a):"",Ct=Math.round(e.snapshotBytes/1024);Pe?d.push(` On ${Pe}, /compact fired \u2014 ${Ct} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${Ct} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let Em=s?.conversation,km=Em?.bytesAvoided??0,Ac=Em?.bytesReturned??0;if(km+Ac===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Pe=km+Ac,Ct=Math.max(1,Ac),It=Math.max(1,Math.floor(Pe/4)),ir=Math.max(1,Math.floor(Ct/4)),Nc=Ur(It,It,32),KS=Ur(ir,It,32),XS=(1-ir/It)*100,YS=Math.max(1,Math.round(It/ir));d.push(` Without context-mode ${Ve(Pe).padStart(8)} ${Nc} ${qt(It).padStart(7)} tokens`),d.push(` With context-mode ${Ve(Ct).padStart(8)} ${KS} ${qt(ir).padStart(7)} tokens`),d.push(` ${XS.toFixed(1)}% kept out of context \xB7 your AI ran ${YS}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Pe=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${Ve(V)} built up \u2014 ${Pe} days, ${e.byDay.length} active:`),d.push(""),d.push(...KD(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 VS=e.byCategory.reduce((Pe,Ct)=>Pe+Ct.count,0).toLocaleString(i);d.push(` ${VS} things \u2014 files, errors, decisions, agent runs:`),d.push("");let WS=e.byCategory[0]?.count??1;for(let Pe of e.byCategory)d.push(` ${Pe.label.padEnd(26)} ${String(Pe.count).padStart(5)} ${Ur(Pe.count,WS,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let Tm=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",$m=T>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(T)):"",Rm=r?.distinctProjects??0,GS=r?.totalEvents??n?.totalEvents??0;if(d.push(` This chat: ${Ve(V)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Tm?` \xB7 started ${Tm}`:""}.`),d.push(` All your work: ${Ve(z)} kept out \xB7 ${GS.toLocaleString(i)} captures across ${Rm} project${Rm===1?"":"s"}${$m?` \xB7 since ${$m}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...WD(z,w,F)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),r&&r.autoMemoryCount>0){d.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let Pe=Object.entries(r.autoMemoryByPrefix).sort((It,ir)=>ir[1]-It[1]),Ct=Pe.length>0?Pe[0][1]:1;for(let[It,ir]of Pe){let Nc=xS[It]??It;d.push(` ${Nc.padEnd(26)} ${String(ir).padStart(2)} ${Ur(ir,Ct,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 JS=u?`v${u}`:"context-mode";return d.push(` ${JS}`),u&&l&&l!=="unknown"&&_S(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),JD(d)}function JD(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 KD(t,e,r){if(t.length===0)return[];let n=[...t].sort((f,h)=>f.ms-h.ms),s=n[0],o=n[n.length-1],i=Math.max(1,o.ms-s.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-s.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(s.ms)} ${u.join("")} ${l(o.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 pS(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let s=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),o=d=>s.find(f=>f.type===d)?.value??"",i=o("day"),a=o("month"),c=o("year"),u=o("hour"),l=o("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${l} (${r})`}function qt(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function ni(){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 Q2=5/1e6;function mc(t){return`$${((Number.isFinite(t)&&t>0?t:0)*ni()).toFixed(2)}`}function Ur(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 fS(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,s=[];s.push("");let o=e?.multiAdapter,i=o?.perAdapter.filter(m=>m.isReal).length??0,a=o?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=o?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let m=i>=2?" everywhere":"";s.push(` All your work${m} \xB7 ${qt(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${qt(c)} conversations`)}else{s.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let m=c===0&&r>0?1:c,g=m===1?"1 session":`${qt(m)} sessions`,y=a*256+r;s.push(` ${qt(a)} events \xB7 ${g} \xB7 ~${mc(y)} saved lifetime`)}s.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:dc[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)s.push(` ${m.label.padEnd(26)} ${String(m.count).padStart(5)} ${Ur(m.count,h,30)}`);let p=Math.max(0,d.length-n);return p>0&&s.push(` ... ${p} more categor${p===1?"y":"ies"}`),s}function mS(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((s,o)=>o[1]-s[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[s,o]of r){let i=xS[s]??s;e.push(` ${i.padEnd(26)} ${String(o).padStart(2)} ${Ur(o,n,20)}`)}return e}function hS(t,e){let r=[],n=mc(t),s=(e?.totalEvents??0)*256+t,o=mc(s);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${o} lifetime`),r.push("\u2500".repeat(65)),r}var gS=256;function yS(t){if(!t)return[];let e=[],r=[];for(let s of t.perAdapter)(s.isReal?e:r).push(s);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let s=16,o=10,i=10,a=16;n.push(` ${"Tool".padEnd(s)}${"Captures".padStart(o)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,l)=>l.dataBytes+l.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let l=u.dataBytes+u.rescueBytes,d=u.eventCount>0?qt(u.eventCount):"\u2014",f=Ve(u.dataBytes),h=Ve(l);n.push(` ${fc(u.name).padEnd(s)}${d.padStart(o)}${f.padStart(i)}${h.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let s=r.map(o=>fc(o.name)).join(", ");n.push(` Skipped (${r.length}): ${s}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function yc(t,e,r,n){let s=[],o=HD(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,l=n?.multiAdapter,d=l?.perAdapter.filter(I=>I.isReal).length??0;if(l&&d>0){let I=l.totalSessions||i?.totalSessions||0,R=i?.firstEventMs??0,M=R>0?Math.max(1,Math.round((Date.now()-R)/864e5)):0,z=M>0?`Across ${M} day${M===1?"":"s"} `:"",V=I>0?`you ran ${qt(I)} conversation${I===1?"":"s"} `:"you ran ",$;if(d>=2)$=`across ${d} AI tools`;else{let T=l.perAdapter.find(F=>F.isReal);$=`in ${T?fc(T.name):"Claude Code"}`}s.push(`${z}${V}${$}.`),s.push("")}if(c&&c.events>0){s.length>0&&(s.length=0);let I=VD(),R=n?.cwd??process.cwd(),M=n?.now??Date.now(),z=n?.locale??I.locale,V=n?.tz??I.tz;return s.push(...GD({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:R,locale:z,tz:V,now:M,version:e,latestVersion:r})),s.join(`
|
|
583
|
+
`)}let f=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),h=t.savings.total_bytes_returned,p=t.savings.total_calls,m=f+h,g=m>0?f/m*100:0,y=Math.round(f/4),b=h>0?Math.max(1,Math.round(m/Math.max(h,1))):0;if(f===0){s.push(`context-mode ${o} ${p} calls`),s.push(""),p===0?s.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):s.push(`${Ve(h)} entered context | 0 tokens saved`),s.push(...fS(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),s.push(...yS(l)),s.push(...mS(i)),s.push(...hS(0,i)),s.push("");let I=e?`v${e}`:"context-mode";return s.push(I),e&&r&&r!=="unknown"&&_S(r,e)&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
|
|
584
|
+
`)}s.push(`${qt(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${o} \xB7 ~${mc(y)} saved (Opus)`),s.push(""),s.push(`Without context-mode |${Ur(m,m)}| ${Ve(m)}`),s.push(`With context-mode |${Ur(h,m)}| ${Ve(h)}`),s.push(""),b>=2?s.push(`${Ve(f)} kept out of your conversation \u2014 ${b}\xD7 longer sessions before compact.`):s.push(`${Ve(f)} kept out of your conversation. Never entered context.`),s.push("");let _=[`${p} calls`];t.cache&&t.cache.hits>0&&_.push(`${t.cache.hits} cache hits (+${Ve(t.cache.bytes_saved)})`),s.push(_.join(" \xB7 "));let x=t.savings.by_tool.filter(I=>I.calls>0);if(x.length>=2){s.push("");let I=x.map(R=>{let M=R.context_kb*1024,z=g<100?M/(1-g/100):M,V=Math.max(0,z-M);return{...R,returnedBytes:M,estimatedSaved:V}}).sort((R,M)=>M.estimatedSaved-R.estimatedSaved);for(let R of I){let M=R.tool.length>22?R.tool.slice(0,19)+"...":R.tool;s.push(` ${M.padEnd(22)} ${String(R.calls).padStart(4)} calls ${Ve(R.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let I=a.filter(R=>R.median_concurrency!=null&&(R.max_concurrency??1)>1);if(I.length>0){s.push(""),s.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let R of I){let M=R.tool_name.replace(/^mcp__.*?__/,"");s.push(` ${M.padEnd(22)} ${R.calls} batches \xB7 ${R.median_concurrency} typical, ${R.max_concurrency} peak`)}}}s.push(...fS(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),s.push(...yS(l)),s.push(...mS(i)),s.push(...hS(y,i)),s.push("");let w=e?`v${e}`:"context-mode";return s.push(w),e&&r&&r!=="unknown"&&r!==e&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
|
|
585
|
+
`)}var xc=Os(nz(import.meta.url)),_r=(()=>{for(let t of["../package.json","./package.json"]){let e=rt(xc,t);if(Ie(e))try{return JSON.parse(oi(e,"utf8")).version}catch{}}return"unknown"})();function MS(){return Ie(rt(xc,"package.json"))?xc:Os(xc)}function az(t){try{let e=process.platform==="win32"?kc("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):kc("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});if(e.status!==0)return t;let r=Mf(String(e.stdout));if(r&&Ie(rt(r,".codex-plugin","hooks.json")))return r}catch{}return t}function LS(t){let e=MS();return t==="codex"?az(e):e}process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
|
|
586
|
+
`)}),process.on("uncaughtException",t=>{try{XD(2,`[context-mode] uncaughtException: ${t?.message??t}
|
|
587
|
+
`)}finally{process.exit(1)}}));var An=Va(),Sc=Bv(An),Se=new Ua({name:"context-mode",version:_r}),cz=[];function uz(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let r=t.platform??mt().platform;if(r!=="opencode"&&r!=="kilo")return!1;let n=t.settings??lz(r);return dz(n)&&pz(n)}function lz(t){let e=t==="kilo"?"kilo":"opencode",r=[rt(`${e}.json`),rt(`${e}.jsonc`),rt(`.${e}`,`${e}.json`),rt(`.${e}`,`${e}.jsonc`),gt(Is(),".config",e,`${e}.json`),gt(Is(),".config",e,`${e}.jsonc`)];for(let n of r)try{if(!Ie(n))continue;return JSON.parse(cS(oi(n,"utf8")))}catch{}return null}function dz(t){let e=t?.plugin;return Array.isArray(e)&&e.some(r=>typeof r=="string"&&r.includes("context-mode"))}function pz(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}var jS=uz(),dm=!1;function fz(t={}){if(dm)return;dm=!0;let e=t.write??(n=>{process.stderr.write(n)}),r=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 ${r}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
|
|
588
|
+
`)}function FB(){dm=!1}function mz(t=Se){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(mn,async()=>({tools:[]}))}var hz=Se.registerTool.bind(Se);Se.registerTool=(...t)=>{let[e,r,n]=t;if(jS){fz();return}let s=gz(e,n);return cz.push({name:e,config:r,handler:s}),t[2]=s,hz(...t)};function gz(t,e){return async r=>{Tx();try{return await e(r)}catch(n){let s=wz(n);if(s)try{return W(t,s)}catch(o){if(o instanceof Zr)return s;throw o}throw n}finally{$x()}}}jS&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&mz(Se);var ym=new iz;async function ZB(t,e){let r=typeof t=="string"?{projectDir:t}:t;return ym.run(r,e)}Se.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Se.server.setRequestHandler(Yn,async()=>({prompts:[]}));Se.server.setRequestHandler(Kn,async()=>({resources:[]}));Se.server.setRequestHandler(Xn,async()=>({resourceTemplates:[]}));function pm(t){if(Array.isArray(t))return t.map(pm);if(t===null||typeof t!="object")return t;let e={};for(let[r,n]of Object.entries(t))if(r!=="additionalProperties"){if(r==="const"){e.enum=[n];continue}e[r]=pm(n)}return e}function yz(t=Se){try{let r=t.server._requestHandlers?.get("tools/list");if(typeof r!="function")return;t.server.setRequestHandler(mn,async(n,s)=>{let o=await r(n,s);if(o&&Array.isArray(o.tools)){for(let i of o.tools)if(!(!i||i.inputSchema==null))try{i.inputSchema=pm(i.inputSchema)}catch{}}return o})}catch{}}var ii=new qo({runtimes:An,projectRoot:()=>ht()}),Ic=gt(gm(),`cm-fs-preload-${process.pid}.js`);Ec(Ic,`(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){}})();
|
|
589
|
+
`);process.on("exit",()=>{try{Cs(Ic)}catch{}});var Bt=null;function qr(){let t=ym.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??_z();if(e)return{sessionId:e}}var _c;function _z(t){let e=Date.now();if(!t?.bypassCache&&_c&&e-_c.checkedAt<2e3)return _c.sid;try{let r=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!r)return;let n=t?.sessionsDir??Ae(),s=ei({projectDir:r,sessionsDir:n});if(!Ie(s))return;let o=He(),i=new o(s,{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&&(_c={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function bz(t){try{let e=Ae();if(!Ie(e))return;let r=OS(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let s=gt(e,n);try{t.index({path:s,source:"session-events",attribution:qr()}),Cs(s)}catch{}}}catch{}}var Ht=null;async function vz(){if(Ht)return Ht;try{let{getAdapter:t}=await Promise.resolve().then(()=>(Pn(),Ff)),e=mt();return await t(e.platform)}catch{return null}}function $s(){if(Ht)return Ht.getSessionDir();try{let t=mt(),e=Rn(t.platform);if(e)return Yf({configDir:gt(...e),configDirEnv:xz(e)})}catch{}return Yf({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function xz(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function Ae(){return sc(Qo($s))}function ht(){let t=ym.getStore();if(t)return t.projectDir;let e,r,n;try{let s=mt().platform;r=s,s==="claude-code"&&(e=gt(Is(),".claude","projects")),s==="codex"&&(n=process.env.CODEX_HOME??gt(Is(),".codex"))}catch{}return lS({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:r,codexHome:n})}function Sz(t){return rz(t)?t:rt(ht(),t)}function Rs(){return ei({projectDir:ht(),sessionsDir:Ae()})}function Tc(){let t=sc(Qf($s));return Bx({projectDir:ht(),contentDir:t})}function sr(){if(!Bt){let t=Tc();Bt=new Ya(t),Bt.setDenyChecker(e=>{try{let r=ht(),n=Qa("Read",r);return Jo(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=Os(Tc());Nf(e,14),Bt.cleanupStaleSources(14);let r=gt(Is(),".context-mode","content");Ie(r)&&Nf(r,0)}catch{}Af()}return bz(Bt),Bt}var te={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};function wz(t){return t instanceof Zr?{content:[{type:"text",text:Zx(t)}],isError:!0}:null}var br=null,bc=0,SS=0,Ez=3,kz=3600*1e3;async function wS(){return new Promise(t=>{let e=oz("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",s=>{n+=s}),r.on("end",()=>{try{let s=JSON.parse(n);t(s.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function Tz(){let t=Ht?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function $z(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let s=0;s<3;s++){if((r[s]??0)>(n[s]??0))return!0;if((r[s]??0)<(n[s]??0))return!1}return!1}function Rz(){return!br||br==="unknown"?!1:$z(br,_r)}function Pz(){if(!Rz())return!1;let t=Date.now();if(bc>=Ez){if(t-SS<kz)return!1;bc=0}return bc===0&&(SS=t),bc++,!0}var ES=!1;function Cz(){if(!ES){ES=!0;try{let t=jr(),e=rt(t,"plugins","installed_plugins.json");if(!Ie(e))return;let r=JSON.parse(oi(e,"utf-8")),n=rt(t,"plugins","cache"),s;try{s=zS(n)}catch{s=n}let o=MS();for(let[i,a]of Object.entries(r.plugins??{}))if(i==="context-mode@context-mode")for(let c of a){let u=c.installPath;if(!u||Ie(u)||!rt(u).startsWith(s+tz))continue;try{DS(u).isSymbolicLink()&&Cs(u)}catch{}let l=Os(u);Ie(l)||QD(l,{recursive:!0}),Ie(o)&&ez(o,u,process.platform==="win32"?"junction":void 0)}}catch{}}}function W(t,e){if(Jf(),Cz(),Pz()&&e.content.length>0){let n=Tz();e.content[0].text=`\u26A0\uFE0F context-mode v${_r} outdated \u2192 v${br} available. Upgrade: ${n}
|
|
590
|
+
|
|
591
|
+
`+e.content[0].text}let r=e.content.reduce((n,s)=>n+Buffer.byteLength(s.text),0);return te.calls[t]=(te.calls[t]||0)+1,te.bytesReturned[t]=(te.bytesReturned[t]||0)+r,$c(),setImmediate(()=>Yx(Rs(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>Gx({sessionDbPath:Rs(),toolName:t,bytesReturned:r})),(t==="ctx_search"||t==="ctx_fetch_and_index")&&setImmediate(()=>eS(Rs(),r)),e}function Vt(t,e="unknown"){te.bytesIndexed+=t,$c(),t>0&&setImmediate(()=>Jx({sessionDbPath:Rs(),source:e,bytesAvoided:t}))}var Iz=500,Oz=2,Az=3e4,Nz=256,fm=0,vc,Dz=/^[A-Za-z0-9._-]+$/;function zz(t){return Dz.test(t)?t:`pid-${process.ppid}`}function FS(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=zz(t),r=sc(em($s));return gt(r,`stats-${e}.json`)}function $c(){let t=Date.now();if(!(t-fm<Iz)){fm=t;try{let e=Object.values(te.bytesReturned).reduce((d,f)=>d+f,0),r=Object.values(te.calls).reduce((d,f)=>d+f,0),n=te.bytesIndexed+te.bytesSandboxed+te.cacheBytesSaved,s=n+e,o=s>0?Math.round((1-e/s)*100):0,i=Math.round(n/4),a=vc?.tokens??0;if(!vc||t-vc.computedAt>Az)try{a=(ri({sessionsDir:Ae()})?.totalEvents??0)*Nz,vc={tokens:a,computedAt:t}}catch{}let c={schemaVersion:Oz,version:_r,updated_at:t,session_start:te.sessionStart,uptime_ms:t-te.sessionStart,total_calls:r,bytes_returned:e,bytes_indexed:te.bytesIndexed,bytes_sandboxed:te.bytesSandboxed,cache_hits:te.cacheHits,cache_bytes_saved:te.cacheBytesSaved,kept_out:n,total_processed:s,reduction_pct:o,tokens_saved:i,dollars_saved_session:+(i*ni()).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*ni()).toFixed(2),by_tool:Object.fromEntries(Object.keys({...te.calls,...te.bytesReturned}).map(d=>[d,{calls:te.calls[d]||0,bytes:te.bytesReturned[d]||0}]))},u=FS(),l=`${u}.tmp`;Ec(l,JSON.stringify(c)),YD(l,u)}catch{}}}function _m(t,e){try{let r=Hf(process.env.CLAUDE_PROJECT_DIR),n=Wf(t,r);if(n.decision==="deny")return W(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function ZS(t,e,r){try{let n=kx(t,e);if(n.length===0)return null;let s=Hf(process.env.CLAUDE_PROJECT_DIR);for(let o of n){let i=Wf(o,s);if(i.decision==="deny")return W(r,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${o}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function Mz(t,e){try{let r=ht(),n=Vf("Read","allow",r);return Ex(t,r,n).allowed?null:W(e,{content:[{type:"text",text:`File access blocked: "${t}" resolves outside the project root (${r}). context-mode confines ${e} to the workspace so it cannot be used to bypass the host's sandbox/permission controls (issue #852). To intentionally process a file outside the project, add a host allow rule, e.g. "permissions": { "allow": ["Read(${t})"] } in your settings.`}],isError:!0})}catch{}return null}function mm(t,e){try{let r=ht(),n=Qa("Read",r),s=Jo(t,n,process.platform==="win32",r);if(s.denied)return W(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${s.matchedPattern}`}],isError:!0})}catch{}return null}var Lz=Sc.join(", "),jz=Wa()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",Fz="",Zz="";function Uz(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===Fz){for(e.push(r),n++;n<t.length&&t[n]!==Zz;)r++,n++;n<t.length&&n++}else r++,n++;return e}function US(t,e,r=1500,n){if(t.length<=r)return t;let s=[];if(n)for(let u of Uz(n))s.push(u);if(s.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;)s.push(f),f=l.indexOf(d,f+1)}}if(s.length===0)return t.slice(0,r)+`
|
|
592
|
+
\u2026`;s.sort((u,l)=>u-l);let o=300,i=[];for(let u of s){let l=Math.max(0,u-o),d=Math.min(t.length,u+o);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>=r)break;let d=t.slice(u,Math.min(l,u+(r-c)));a.push((u>0?"\u2026":"")+d+(l<t.length?"\u2026":"")),c+=d.length}return a.join(`
|
|
593
|
+
|
|
594
|
+
`)}function qz(t,e,r,n=80*1024,s="batch"){let o=[],i=0,a=s==="global"?void 0:r;for(let c of e){if(i>n){o.push(`## ${c}
|
|
595
|
+
(output cap reached \u2014 use ctx_search(queries: ["${c}"]) for details)
|
|
596
|
+
`);continue}let u=t.searchWithFallback(c,3,a,void 0,"exact");if(o.push(`## ${c}`),o.push(""),u.length>0){for(let l of u){let d=US(l.content,c,3e3,l.highlighted);o.push(`### ${l.title}`),o.push(d),o.push(""),i+=d.length+l.title.length}continue}o.push("No matching sections found."),o.push("")}return s==="global"?o.push(`
|
|
597
|
+
> **Scope:** Queries searched the entire persistent index (query_scope: "global").`):o.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"`.'),o}function Bz(t){return`'${t.replace(/'/g,"'\\''")}'`}function Hz(t){return`'${t.replace(/'/g,"''")}'`}function Vz(t,e){let r=`--require ${e}`,n=t.toLowerCase(),s=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${Hz(r)}; `:s==="cmd"||s==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${Bz(r)} `}var kS=500;function qS(t){let e=t.replace(/\s+/g," ").trim();return e.length<=kS?e:e.slice(0,kS)+"\u2026"}var Wz=12e4;function bm(t){if(t!==void 0)return t;if(mt().platform!=="antigravity-cli")return;let e=Number(process.env.CONTEXT_MODE_AGY_EXEC_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:Wz}var TS=2e3;function Gz(t){return t.length<=TS?t:t.slice(0,TS)+`
|
|
598
|
+
\u2026 (truncated)`}function BS(t,e,r){let n=r?`path=${r}
|
|
599
|
+
`:"",s=`\`\`\`${t}
|
|
600
|
+
${Gz(e)}
|
|
601
|
+
\`\`\``;return`${n}${s}
|
|
602
|
+
|
|
603
|
+
`}function $S(t,e,r,n){let s=r||"(no output)",o=s.matchAll(/__CM_FS__:(\d+)/g),i=0;for(let c of o)i+=parseInt(c[1]);i>0&&(n?.(i),s=s.replace(/__CM_FS__:\d+\n?/g,""));let a=qS(e);return`# ${t}
|
|
604
|
+
|
|
605
|
+
$ ${a}
|
|
606
|
+
|
|
607
|
+
${s}
|
|
608
|
+
`}function RS(t){let e=t.stdout||"",r=t.stderr||"";return r?e?`${e}${e.endsWith(`
|
|
609
|
+
`)?"":`
|
|
610
|
+
`}${r}`:r:e}async function Jz(t,e,r){let{timeout:n,concurrency:s,nodeOptsPrefix:o,cwd:i,onFsBytes:a}=e;if(s<=1){let f=[],h=Date.now(),p=!1;for(let m=0;m<t.length;m++){let g=t[m],y;if(n!==void 0){let _=Date.now()-h,x=n-_;if(x<=0){f.push(`# ${g.label}
|
|
611
|
+
|
|
612
|
+
(skipped \u2014 batch timeout exceeded)
|
|
613
|
+
`),p=!0;continue}y=x}let b=await r.execute({language:"shell",code:`${o}${g.command}`,timeout:y,cwd:i});if(f.push($S(g.label,g.command,RS(b),a)),b.timedOut){p=!0;for(let _=m+1;_<t.length;_++)f.push(`# ${t[_].label}
|
|
614
|
+
|
|
615
|
+
(skipped \u2014 batch timeout exceeded)
|
|
616
|
+
`);break}}return{outputs:f,timedOut:p}}let c=t.map(f=>({run:async()=>{let h=await r.execute({language:"shell",code:`${o}${f.command}`,timeout:n,cwd:i}),p=$S(f.label,f.command,RS(h),a);return{output:h.timedOut?p.replace(/\n$/,"")+`
|
|
617
|
+
(timed out after ${n??"?"}ms)
|
|
618
|
+
`:p,timedOut:!!h.timedOut}}})),{settled:u}=await Ef(c,{concurrency:s}),l=new Array(t.length),d=!1;for(let f=0;f<u.length;f++){let h=u[f];if(h.status==="fulfilled")l[f]=h.value.output,h.value.timedOut&&(d=!0);else{let p=h.reason instanceof Error?h.reason.message:String(h.reason);l[f]=`# ${t[f].label}
|
|
619
|
+
|
|
620
|
+
(executor error: ${p})
|
|
621
|
+
`}}return{outputs:l,timedOut:d}}Se.registerTool("ctx_execute",{title:"Run code in a sandbox (executes the supplied code)",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run code in a sandboxed subprocess.${jz} Languages: ${Lz}.
|
|
622
|
+
|
|
623
|
+
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.
|
|
624
|
+
|
|
625
|
+
Concrete shape \u2014 analyze 47 source files without reading any of them:
|
|
626
|
+
ctx_execute(language: "javascript", code: \`
|
|
627
|
+
const fs = require('fs');
|
|
628
|
+
const files = fs.readdirSync('src').filter(f => f.endsWith('.ts'));
|
|
629
|
+
files.forEach(f => {
|
|
630
|
+
const lines = fs.readFileSync('src/'+f,'utf8').split('\\\\n').length;
|
|
631
|
+
console.log(f + ': ' + lines + ' lines');
|
|
632
|
+
});
|
|
633
|
+
\`)
|
|
634
|
+
// 47 files analyzed, 15,314 LoC summarized \u2014 output ~3.6 KB instead of 47 Read() calls = ~700 KB.
|
|
635
|
+
|
|
636
|
+
WHEN:
|
|
637
|
+
- You intend to derive an answer FROM data (filter, count, aggregate, parse, compare, transform) \u2014 do the derivation in code and print only the answer
|
|
638
|
+
- Output shape or size cannot be predicted before execution (recursive finds, repo-wide greps, list endpoints, query results, log scans)
|
|
639
|
+
- You would otherwise read raw output and then mentally compute \u2014 that compute belongs here, in code, where its inputs stay out of your conversation
|
|
640
|
+
- You need to keep a long-running process alive (dev server, watcher, daemon) \u2014 pass \`background: true\` to detach on timeout instead of killing the process
|
|
641
|
+
- The output may legitimately be large but you only want recall-by-topic later \u2014 pass an \`intent\` string; outputs over ~5KB are auto-indexed into the knowledge base and only the section titles + previews come back, retrievable via ctx_search
|
|
642
|
+
|
|
643
|
+
WHEN NOT:
|
|
644
|
+
- Single observational command whose entire short output you intend to consume verbatim (whoami, pwd, git status on a clean tree) \u2014 Bash is simpler
|
|
645
|
+
- File mutations (Edit/Write) or navigation (cd/ls) \u2014 Bash is the right surface
|
|
646
|
+
- You already know the output is one short fixed line and you want to read it as-is
|
|
647
|
+
|
|
648
|
+
RETURNS:
|
|
649
|
+
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.
|
|
650
|
+
|
|
651
|
+
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'))")
|
|
652
|
+
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:C.object({language:C.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:C.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:C.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:C.preprocess(Sm,C.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:C.string().optional().describe("Optional working directory for shell commands. Non-shell languages still execute from their sandbox temp directory."),intent:C.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'.
|
|
653
|
+
|
|
654
|
+
TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,cwd:s,intent:o})=>{if(t==="shell"){let i=_m(e,"execute");if(i)return i}else{let i=ZS(e,t,"execute");if(i)return i}try{let i=e;(t==="javascript"||t==="typescript")&&(i=`
|
|
655
|
+
// FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
|
|
656
|
+
let __cm_fs=0;
|
|
657
|
+
process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
|
|
658
|
+
(function(){
|
|
659
|
+
try{
|
|
660
|
+
var f=typeof require!=='undefined'?require('fs'):null;
|
|
661
|
+
if(!f)return;
|
|
662
|
+
var ors=f.readFileSync;
|
|
663
|
+
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;};
|
|
664
|
+
var orf=f.readFile;
|
|
665
|
+
if(orf)f.readFile=function(){var a=Array.from(arguments),cb=a.pop();orf.apply(this,a.concat([function(e,d){if(!e&&d){if(Buffer.isBuffer(d))__cm_fs+=d.length;else if(typeof d==='string')__cm_fs+=Buffer.byteLength(d);}cb(e,d);}]));};
|
|
666
|
+
}catch{}
|
|
667
|
+
})();
|
|
668
|
+
let __cm_net=0;
|
|
669
|
+
// Report network bytes on process exit \u2014 works with both promise and callback patterns.
|
|
670
|
+
// process.on('exit') fires after all I/O completes, unlike .finally() which fires
|
|
671
|
+
// when __cm_main() resolves (immediately for callback-based http.get without await).
|
|
672
|
+
process.on('exit',()=>{if(__cm_net>0)try{process.stderr.write('__CM_NET__:'+__cm_net+'\\n')}catch{}});
|
|
673
|
+
;(function(__cm_req){
|
|
674
|
+
// Intercept globalThis.fetch
|
|
675
|
+
const __cm_f=globalThis.fetch;
|
|
676
|
+
globalThis.fetch=async(...a)=>{const r=await __cm_f(...a);
|
|
677
|
+
try{const cl=r.clone();const b=await cl.arrayBuffer();__cm_net+=b.byteLength}catch{}
|
|
678
|
+
return r};
|
|
679
|
+
// Shadow CJS require with http/https network tracking.
|
|
680
|
+
const __cm_hc=new Map();
|
|
681
|
+
const __cm_hm=new Set(['http','https','node:http','node:https']);
|
|
682
|
+
function __cm_wf(m,origFn){return function(...a){
|
|
683
|
+
const li=a.length-1;
|
|
684
|
+
if(li>=0&&typeof a[li]==='function'){const oc=a[li];a[li]=function(res){
|
|
685
|
+
res.on('data',function(c){__cm_net+=c.length});oc(res);};}
|
|
686
|
+
const req=origFn.apply(m,a);
|
|
687
|
+
const oOn=req.on.bind(req);
|
|
688
|
+
req.on=function(ev,cb,...r){
|
|
689
|
+
if(ev==='response'){return oOn(ev,function(res){
|
|
690
|
+
res.on('data',function(c){__cm_net+=c.length});cb(res);
|
|
691
|
+
},...r);}
|
|
692
|
+
return oOn(ev,cb,...r);
|
|
693
|
+
};
|
|
694
|
+
return req;
|
|
695
|
+
}}
|
|
696
|
+
var require=__cm_req?function(id){
|
|
697
|
+
const m=__cm_req(id);
|
|
698
|
+
if(!__cm_hm.has(id))return m;
|
|
699
|
+
const k=id.replace('node:','');
|
|
700
|
+
if(__cm_hc.has(k))return __cm_hc.get(k);
|
|
701
|
+
const w=Object.create(m);
|
|
702
|
+
if(typeof m.get==='function')w.get=__cm_wf(m,m.get);
|
|
703
|
+
if(typeof m.request==='function')w.request=__cm_wf(m,m.request);
|
|
704
|
+
__cm_hc.set(k,w);return w;
|
|
705
|
+
}:__cm_req;
|
|
706
|
+
if(__cm_req){if(__cm_req.resolve)require.resolve=__cm_req.resolve;
|
|
707
|
+
if(__cm_req.cache)require.cache=__cm_req.cache;}
|
|
708
|
+
async function __cm_main(){
|
|
709
|
+
${e}
|
|
710
|
+
}
|
|
711
|
+
__cm_main().catch(e=>{console.error(e);process.exitCode=1});${n?`
|
|
712
|
+
setInterval(()=>{},2147483647);`:""}
|
|
713
|
+
})(typeof require!=='undefined'?require:null);`);let a=bm(r),c=await ii.execute({language:t,code:i,timeout:a,background:n,cwd:s}),u=BS(t,e),l=c.stderr?.match(/__CM_NET__:(\d+)/);l&&(te.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&&(te.bytesSandboxed+=parseInt(d[1]),c.stderr=c.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),c.timedOut){let h=c.stdout?.trim();return c.backgrounded&&h?W("ctx_execute",{content:[{type:"text",text:`${u}${h}
|
|
714
|
+
|
|
715
|
+
_(process backgrounded after ${a}ms \u2014 still running)_`}]}):h?W("ctx_execute",{content:[{type:"text",text:`${u}${h}
|
|
716
|
+
|
|
717
|
+
_(timed out after ${a}ms \u2014 partial output shown above)_`}]}):W("ctx_execute",{content:[{type:"text",text:`${u}Execution timed out after ${a}ms
|
|
718
|
+
|
|
719
|
+
stderr:
|
|
720
|
+
${c.stderr}`}],isError:!0})}if(c.exitCode!==0){let{isError:h,output:p}=Gf({language:t,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return o&&o.trim().length>0&&Buffer.byteLength(p)>Rc?(Vt(Buffer.byteLength(p)),W("ctx_execute",{content:[{type:"text",text:`${u}${Ps(p,o,h?`execute:${t}:error`:`execute:${t}`)}`}],isError:h})):Buffer.byteLength(p)>Pc?(Vt(Buffer.byteLength(p)),W("ctx_execute",{content:[{type:"text",text:`${u}${Ps(p,"errors failures exceptions",h?`execute:${t}:error`:`execute:${t}`)}`}],isError:h})):W("ctx_execute",{content:[{type:"text",text:`${u}${p}`}],isError:h})}let f=c.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(f)>Rc)return Vt(Buffer.byteLength(f)),W("ctx_execute",{content:[{type:"text",text:`${u}${Ps(f,o,`execute:${t}`)}`}]});if(Buffer.byteLength(f)>Pc){let h=HS(f,`execute:${t}`),p={...h,content:h.content.map((m,g)=>g===0&&m.type==="text"?{...m,text:`${u}${m.text}`}:m)};return W("ctx_execute",p)}return W("ctx_execute",{content:[{type:"text",text:`${u}${f}`}]})}catch(i){let a=i instanceof Error?i.message:String(i);return W("ctx_execute",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});function HS(t,e){let r=sr();Vt(Buffer.byteLength(t));let n=r.index({content:t,source:e,attribution:qr()});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
|
|
721
|
+
Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}var Rc=5e3,Pc=102400;function Ps(t,e,r,n=5){let s=t.split(`
|
|
722
|
+
`).length,o=Buffer.byteLength(t),i=sr(),a=i.indexPlainText(t,r,void 0,qr()),c=i.searchWithFallback(e,n,r),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let d=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`No sections matched intent "${e}" in ${s}-line output (${(o/1024).toFixed(1)}KB).`];return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to explore the indexed content."),d.join(`
|
|
723
|
+
`)}let l=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`${c.length} sections matched "${e}" (${s} lines, ${(o/1024).toFixed(1)}KB):`,""];for(let d of c){let f=d.content.split(`
|
|
724
|
+
`)[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(`
|
|
725
|
+
`)}Se.registerTool("ctx_execute_file",{title:"Run code over a file (executes code, reads the given path)",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.
|
|
726
|
+
|
|
727
|
+
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.
|
|
728
|
+
|
|
729
|
+
WHEN:
|
|
730
|
+
- You want to KNOW SOMETHING ABOUT a file (line count, matches of a pattern, parsed structure, statistical aggregate) without needing to SEE all of it
|
|
731
|
+
- The file is structured (CSV, JSON, log, code) and a code-level derivation is cheaper than reading verbatim
|
|
732
|
+
- The file is large enough that reading the full content would burn meaningful conversation memory you need for the actual work
|
|
733
|
+
- The derivation may itself produce a large output you want recall-by-topic on later \u2014 pass an \`intent\` string; outputs over ~5KB are auto-indexed and only matching sections come back, retrievable via ctx_search
|
|
734
|
+
|
|
735
|
+
WHEN NOT:
|
|
736
|
+
- You intend to EDIT the file \u2014 use Read so the subsequent Edit can match the exact text
|
|
737
|
+
- You only need one specific line and you know its offset \u2014 Read with offset/limit is the simplest path
|
|
738
|
+
- The file is small AND you will consume all of it for understanding/editing \u2014 Read directly
|
|
739
|
+
|
|
740
|
+
RETURNS:
|
|
741
|
+
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.
|
|
742
|
+
|
|
743
|
+
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'))")
|
|
744
|
+
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:C.object({path:C.string().describe("Absolute file path or relative to project root"),language:C.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:C.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:C.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:C.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:r,timeout:n,intent:s})=>{let o=Mz(t,"ctx_execute_file");if(o)return o;let i=mm(t,"ctx_execute_file");if(i)return i;if(e==="shell"){let a=_m(r,"execute_file");if(a)return a}else{let a=ZS(r,e,"execute_file");if(a)return a}try{let a=bm(n),c=await ii.executeFile({path:t,language:e,code:r,timeout:a}),u=BS(e,r,t);if(c.timedOut)return W("ctx_execute_file",{content:[{type:"text",text:`${u}Timed out processing ${t} after ${a}ms`}],isError:!0});if(c.exitCode!==0){let{isError:d,output:f}=Gf({language:e,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return s&&s.trim().length>0&&Buffer.byteLength(f)>Rc?(Vt(Buffer.byteLength(f)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Ps(f,s,d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):Buffer.byteLength(f)>Pc?(Vt(Buffer.byteLength(f)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Ps(f,"errors failures exceptions",d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):W("ctx_execute_file",{content:[{type:"text",text:`${u}${f}`}],isError:d})}let l=c.stdout||"(no output)";if(s&&s.trim().length>0&&Buffer.byteLength(l)>Rc)return Vt(Buffer.byteLength(l)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Ps(l,s,`file:${t}`)}`}]});if(Buffer.byteLength(l)>Pc){let d=HS(l,`file:${t}`),f={...d,content:d.content.map((h,p)=>p===0&&h.type==="text"?{...h,text:`${u}${h.text}`}:h)};return W("ctx_execute_file",f)}return W("ctx_execute_file",{content:[{type:"text",text:`${u}${l}`}]})}catch(a){let c=a instanceof Error?a.message:String(a);return W("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${c}`}],isError:!0})}});Se.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.
|
|
745
|
+
|
|
746
|
+
WHEN:
|
|
747
|
+
- Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
|
|
748
|
+
- API references (endpoint details, parameter specs, response schemas)
|
|
749
|
+
- MCP tools/list output (exact tool signatures and descriptions)
|
|
750
|
+
- Skill prompts and instructions that are too large to keep verbatim in conversation
|
|
751
|
+
- README files, migration guides, changelog entries
|
|
752
|
+
- Any content with code examples you may need to reference precisely later
|
|
753
|
+
|
|
754
|
+
WHEN NOT:
|
|
755
|
+
- Log files, test output, CSV, or build output \u2014 use ctx_execute_file, which processes in-sandbox without persisting bytes
|
|
756
|
+
- Single-use ephemeral content you will not query later \u2014 keep it inline if it fits, or ctx_execute_file it
|
|
757
|
+
|
|
758
|
+
RETURNS:
|
|
759
|
+
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.
|
|
760
|
+
|
|
761
|
+
EXAMPLE: ctx_index(content: "# React useEffect\\n\\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
|
|
762
|
+
EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:C.object({content:C.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:C.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:C.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')"),include:C.array(C.string()).optional().describe("Directory-only: glob patterns to include (default: all matching extensions)."),exclude:C.array(C.string()).optional().describe("Directory-only: glob patterns to exclude. Merged with defaults (node_modules, .git, dist, build, .next, coverage, .venv, __pycache__, .DS_Store)."),maxDepth:C.number().int().min(0).optional().describe("Directory-only: max recursion depth from root (default: 5)."),maxFiles:C.number().int().min(1).optional().describe("Directory-only: hard cap on files indexed (default: 200) \u2014 FTS5 blow-up guard."),extensions:C.array(C.string()).optional().describe("Directory-only: allowed file extensions (default: .md .mdx .txt .json .yaml .yml .ts .tsx .js .jsx .py .rs .go .sh)."),respectGitignore:C.boolean().optional().describe("Directory-only: apply nearest .gitignore (default: true)."),followSymlinks:C.boolean().optional().describe("Directory-only: follow directory symlinks (default: false \u2014 cycle hazard + escape risk).")})},async({content:t,path:e,source:r,include:n,exclude:s,maxDepth:o,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return W("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let l=mm(e,"ctx_index");if(l)return l}try{let l=e?Sz(e):void 0;if(l&&Ie(l)&&DS(l).isSymbolicLink()){let p;try{p=zS(l)}catch{return W("ctx_index",{content:[{type:"text",text:"Error: symlink target could not be resolved."}]})}if(p!==l){let m=mm(p,"ctx_index");if(m)return m}}if(l&&Ie(l)&&NS(l).isDirectory()){let h=sr(),p=ht(),m=Qa("Read",p),g=process.platform==="win32",y=I=>{try{return Jo(I,m,g,p).denied}catch{return!1}},b=h.indexDirectory({path:l,source:r??l,attribution:qr(),perFileDeny:y,include:n,exclude:s,maxDepth:o,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),_=b.capped?` (cap reached \u2014 only first ${b.filesIndexed} of ${b.totalSeen}+ files; raise maxFiles to index more)`:"",x=b.denied>0?` (${b.denied} file${b.denied===1?"":"s"} blocked by Read deny policy)`:"",w=b.failed>0?` (${b.failed} file${b.failed===1?"":"s"} failed to read)`:"";return W("ctx_index",{content:[{type:"text",text:`Indexed ${b.filesIndexed} file${b.filesIndexed===1?"":"s"} (${b.totalChunks} sections) from directory: ${b.label}${_}${x}${w}
|
|
763
|
+
Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)Vt(Buffer.byteLength(t));else if(l)try{let h=await import("fs");Vt(h.readFileSync(l).byteLength)}catch{}let f=sr().index({content:t,path:l,source:r??l,attribution:qr()});return W("ctx_index",{content:[{type:"text",text:`Indexed ${f.totalChunks} sections (${f.codeChunks} with code) from: ${f.label}
|
|
764
|
+
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 W("ctx_index",{content:[{type:"text",text:`Index error: ${d}`}],isError:!0})}});function vm(t,e){let r=process.env[t];if(!r)return e;let n=Number(r);return Number.isFinite(n)&&n>0?n:e}var Kz=vm("CONTEXT_MODE_SEARCH_WINDOW_MS",6e4),hm=vm("CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER",3),wc=vm("CONTEXT_MODE_SEARCH_BLOCK_AFTER",8),Xz=new cc({windowMs:Kz,softCapAfter:hm,blockAfter:wc});function Yz(){try{return qr()?.sessionId??"__default__"}catch{return"__default__"}}function xm(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return[t]}return t}function Sm(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function Qz(t){let e=xm(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}Se.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:oS(om)},async t=>{try{let e=sr(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return W("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
|
|
765
|
+
|
|
766
|
+
ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
|
|
767
|
+
\u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
|
|
768
|
+
\u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
|
|
769
|
+
\u2022 ctx_index(content, source) \u2014 manually index text content
|
|
770
|
+
|
|
771
|
+
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,s=[];if(Array.isArray(n.queries)&&n.queries.length>0?s.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&s.push(n.query),s.length===0)return W("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:o=3,source:i,contentType:a,project:c}=t,u=iS(c,om,()=>ht()),l=Date.now(),d=Xz.record(Yz(),l),f=d.count;if(d.blocked)return W("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 h=d.softCapped?1:Math.min(o,2),p=40*1024,m=0,g=[],y=null;if(r==="timeline"||typeof u=="string")try{let M=Ae(),z=ht(),V=ei({projectDir:z,sessionsDir:M});Ie(V)&&(y=new Zt({dbPath:V}))}catch{}let _;if(typeof u=="string"&&y)try{_=new Set(y.getSessionIdsForProject(u))}catch{}let x=Ht?.getConfigDir()??jr();try{for(let M of s){if(m>p){g.push(`## ${M}
|
|
772
|
+
(output cap reached)
|
|
773
|
+
`);continue}let z;if(r==="timeline"?z=sS({query:M,limit:h,store:e,sort:r,source:i,contentType:a,sessionDB:y,projectDir:ht(),configDir:x,adapter:Ht??void 0,projectScope:u}):z=e.searchWithFallback(M,h,i,a,"like",_),z.length===0){g.push(`## ${M}
|
|
774
|
+
No results found.`);continue}let V=z.map(($,T)=>{let F=$.origin||"current-session",de=$.timestamp?$.timestamp.slice(0,16).replace("T"," "):"",nt=`--- [${F}${de?" | "+de:""} | ${$.source}] ---`,or=`### ${$.title}`,Oc=US($.content,M,1500,$.highlighted);return`${nt}
|
|
775
|
+
${or}
|
|
776
|
+
|
|
777
|
+
${Oc}`}).join(`
|
|
778
|
+
|
|
779
|
+
`);g.push(`## ${M}
|
|
780
|
+
|
|
781
|
+
${V}`),m+=V.length}}finally{try{y?.close()}catch{}}let w=g.join(`
|
|
782
|
+
|
|
783
|
+
---
|
|
784
|
+
|
|
785
|
+
`);e.lastRefreshCount>0&&(w=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
|
|
786
|
+
|
|
787
|
+
`+w);let I=Math.max(0,wc-f),R=Math.max(0,hm-f);if(f>=hm?w+=`
|
|
788
|
+
|
|
789
|
+
\u26A0 search call #${f}/${wc} in this window. Results limited to ${h}/query. ${I} call(s) remaining before block. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`:w+=`
|
|
790
|
+
|
|
791
|
+
> Throttle: call #${f}/${wc} 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.`,w.trim().length===0){let M=e.listSources(),z=M.length>0?`
|
|
792
|
+
Indexed sources: ${M.map(V=>`"${V.label}" (${V.chunkCount} sections)`).join(", ")}`:"";return W("ctx_search",{content:[{type:"text",text:`No results found.${z}`}]})}return W("ctx_search",{content:[{type:"text",text:w}]})}catch(e){let r=e instanceof Error?e.message:String(e);return W("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});var am=null,cm=null;function eM(){return am||(am=IS(import.meta.url).resolve("turndown")),am}function tM(){return cm||(cm=IS(import.meta.url).resolve("turndown-plugin-gfm")),cm}function rM(t,e){let r=JSON.stringify(eM()),n=JSON.stringify(tM()),s=JSON.stringify(e),o=Cc.toString(),i=Cc.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${o};`:`var ${i} = ${o};
|
|
793
|
+
var classifyIp = ${i};`,c=process.env.CTX_FETCH_STRICT==="1";return`
|
|
794
|
+
const TurndownService = require(${r});
|
|
795
|
+
const { gfm } = require(${n});
|
|
796
|
+
const fs = require('fs');
|
|
797
|
+
const dns = require('no' + 'de:dns');
|
|
798
|
+
const dnsPromises = require('no' + 'de:dns/promises');
|
|
799
|
+
const url = ${JSON.stringify(t)};
|
|
800
|
+
const outputPath = ${s};
|
|
801
|
+
|
|
802
|
+
// Strip proxy env vars from this subprocess only. A configured outbound
|
|
803
|
+
// proxy (HTTP_PROXY / HTTPS_PROXY / ALL_PROXY) would route fetch through
|
|
804
|
+
// an arbitrary target \u2014 DNS resolution happens at the proxy and the
|
|
805
|
+
// in-subprocess DNS rebinding guard never sees the rebound IP. The
|
|
806
|
+
// sandbox fetch path has no legitimate need for an upstream proxy.
|
|
807
|
+
delete process.env.HTTP_PROXY;
|
|
808
|
+
delete process.env.HTTPS_PROXY;
|
|
809
|
+
delete process.env.ALL_PROXY;
|
|
810
|
+
delete process.env.http_proxy;
|
|
811
|
+
delete process.env.https_proxy;
|
|
812
|
+
delete process.env.all_proxy;
|
|
813
|
+
delete process.env.npm_config_proxy;
|
|
814
|
+
delete process.env.npm_config_https_proxy;
|
|
815
|
+
|
|
816
|
+
${a}
|
|
817
|
+
|
|
818
|
+
const STRICT = ${JSON.stringify(c)};
|
|
819
|
+
|
|
820
|
+
// SSRF rebinding defense: every dns.lookup call inside this subprocess
|
|
821
|
+
// (including the one undici performs to connect the fetch socket) is
|
|
822
|
+
// re-validated against the same policy ssrfGuard runs in the parent.
|
|
823
|
+
// Even if a hostname rebinds between the parent's pre-flight check and
|
|
824
|
+
// the subprocess's actual connect, the connect-time lookup re-classifies
|
|
825
|
+
// every returned record and aborts before TCP if any verdict is "block".
|
|
826
|
+
const _origLookup = dns.lookup;
|
|
827
|
+
dns.lookup = function patchedLookup(hostname, options, callback) {
|
|
828
|
+
if (typeof options === 'function') { callback = options; options = {}; }
|
|
829
|
+
if (typeof options === 'number') { options = { family: options }; }
|
|
830
|
+
const wantAll = options && options.all;
|
|
831
|
+
const opts = Object.assign({}, options || {}, { all: true, verbatim: true });
|
|
832
|
+
_origLookup(hostname, opts, function(err, records) {
|
|
833
|
+
if (err) return callback(err);
|
|
834
|
+
if (!Array.isArray(records)) {
|
|
835
|
+
records = [{ address: records, family: (options && options.family) || 4 }];
|
|
836
|
+
}
|
|
837
|
+
for (var i = 0; i < records.length; i++) {
|
|
838
|
+
var verdict = classifyIp(records[i].address);
|
|
839
|
+
if (verdict === 'block' || (STRICT && verdict === 'private')) {
|
|
840
|
+
return callback(new Error(
|
|
841
|
+
'SSRF blocked at connect-time: ' + hostname +
|
|
842
|
+
' resolves to ' + records[i].address +
|
|
843
|
+
' (' + verdict + ')'
|
|
844
|
+
));
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
if (wantAll) callback(null, records);
|
|
848
|
+
else callback(null, records[0].address, records[0].family);
|
|
849
|
+
});
|
|
850
|
+
};
|
|
851
|
+
|
|
852
|
+
// dns/promises is a separate function reference. Patching dns.lookup does
|
|
853
|
+
// NOT affect dnsPromises.lookup. Today undici's connect path uses callback
|
|
854
|
+
// dns.lookup so default fetch is covered, but the invariant is fragile \u2014
|
|
855
|
+
// any future undici switch (or user code calling dnsPromises.lookup
|
|
856
|
+
// directly) would bypass the guard. Patch both to keep the contract.
|
|
857
|
+
const _origPromisesLookup = dnsPromises.lookup;
|
|
858
|
+
dnsPromises.lookup = async function patchedPromisesLookup(hostname, options) {
|
|
859
|
+
const opts = Object.assign({}, options || {}, { all: true, verbatim: true });
|
|
860
|
+
const records = await _origPromisesLookup(hostname, opts);
|
|
861
|
+
const list = Array.isArray(records) ? records : [records];
|
|
862
|
+
for (var i = 0; i < list.length; i++) {
|
|
863
|
+
var verdict = classifyIp(list[i].address);
|
|
864
|
+
if (verdict === 'block' || (STRICT && verdict === 'private')) {
|
|
865
|
+
throw new Error(
|
|
866
|
+
'SSRF blocked at connect-time: ' + hostname +
|
|
867
|
+
' resolves to ' + list[i].address + ' (' + verdict + ')'
|
|
868
|
+
);
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
return options && options.all
|
|
872
|
+
? list
|
|
873
|
+
: { address: list[0].address, family: list[0].family };
|
|
874
|
+
};
|
|
875
|
+
|
|
876
|
+
// dns.resolve4 / dns.resolve6 use a different code path (no getaddrinfo,
|
|
877
|
+
// no /etc/hosts) than dns.lookup \u2014 they must be patched separately or the
|
|
878
|
+
// guard is trivially bypassed by any caller using dns.resolve* directly.
|
|
879
|
+
['resolve4', 'resolve6'].forEach(function patchResolve(name) {
|
|
880
|
+
const _origResolve = dns[name];
|
|
881
|
+
dns[name] = function patchedResolve(hostname, options, cb) {
|
|
882
|
+
if (typeof options === 'function') { cb = options; options = undefined; }
|
|
883
|
+
_origResolve.call(dns, hostname, options || {}, function(err, addrs) {
|
|
884
|
+
if (err) return cb(err);
|
|
885
|
+
var withTtl = options && options.ttl;
|
|
886
|
+
for (var i = 0; i < addrs.length; i++) {
|
|
887
|
+
var ip = withTtl ? addrs[i].address : addrs[i];
|
|
888
|
+
var v = classifyIp(ip);
|
|
889
|
+
if (v === 'block' || (STRICT && v === 'private')) {
|
|
890
|
+
return cb(new Error(
|
|
891
|
+
'SSRF blocked at connect-time: ' + hostname +
|
|
892
|
+
' resolves to ' + ip + ' (' + v + ')'
|
|
893
|
+
));
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
cb(null, addrs);
|
|
897
|
+
});
|
|
898
|
+
};
|
|
899
|
+
});
|
|
900
|
+
|
|
901
|
+
// Generic dns.resolve is a polymorphic dispatcher (rrtype-driven). Internally
|
|
902
|
+
// Node delegates to dns.resolve4/dns.resolve6 for A/AAAA, but the patches
|
|
903
|
+
// above hook the *exported* references \u2014 Node's internal dispatcher holds
|
|
904
|
+
// captured originals and bypasses our patch. Patch the wrapper explicitly:
|
|
905
|
+
// classify A/AAAA records the same way; pass through CNAME/MX/TXT/SRV/etc.
|
|
906
|
+
const _origResolveGeneric = dns.resolve;
|
|
907
|
+
dns.resolve = function patchedResolveGeneric(hostname, rrtype, cb) {
|
|
908
|
+
if (typeof rrtype === 'function') { cb = rrtype; rrtype = 'A'; }
|
|
909
|
+
_origResolveGeneric.call(dns, hostname, rrtype, function(err, records) {
|
|
910
|
+
if (err) return cb(err);
|
|
911
|
+
if ((rrtype === 'A' || rrtype === 'AAAA') && Array.isArray(records)) {
|
|
912
|
+
for (var i = 0; i < records.length; i++) {
|
|
913
|
+
var ip = records[i];
|
|
914
|
+
var v = classifyIp(ip);
|
|
915
|
+
if (v === 'block' || (STRICT && v === 'private')) {
|
|
916
|
+
return cb(new Error(
|
|
917
|
+
'SSRF blocked at connect-time: ' + hostname +
|
|
918
|
+
' resolves to ' + ip + ' (' + v + ')'
|
|
919
|
+
));
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
cb(null, records);
|
|
924
|
+
});
|
|
925
|
+
};
|
|
926
|
+
|
|
927
|
+
function emit(ct, content) {
|
|
928
|
+
// Write content to file to bypass executor stdout truncation (100KB limit).
|
|
929
|
+
// Only the content-type marker goes to stdout.
|
|
930
|
+
fs.writeFileSync(outputPath, content);
|
|
931
|
+
console.log('__CM_CT__:' + ct);
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
// Manual redirect handling: a 3xx Location header can rebind the subprocess
|
|
935
|
+
// fetch to an alternate host the parent's pre-flight ssrfGuard never saw.
|
|
936
|
+
// Even with the connect-time DNS patch, a redirect target that is a literal
|
|
937
|
+
// IP (e.g. http://169.254.169.254/) skips getaddrinfo entirely. Walk the
|
|
938
|
+
// chain manually so every hop runs through classifyIp before the next fetch.
|
|
939
|
+
const MAX_REDIRECTS = 5;
|
|
940
|
+
async function fetchWithManualRedirect(initialUrl) {
|
|
941
|
+
let currentUrl = initialUrl;
|
|
942
|
+
for (let redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount++) {
|
|
943
|
+
const resp = await fetch(currentUrl, { redirect: 'manual' });
|
|
944
|
+
if (resp.status < 300 || resp.status >= 400) return resp;
|
|
945
|
+
const location = resp.headers.get('location') || resp.headers.get('Location');
|
|
946
|
+
if (!location) return resp;
|
|
947
|
+
if (redirectCount === MAX_REDIRECTS) {
|
|
948
|
+
throw new Error('SSRF blocked: redirect chain exceeded ' + MAX_REDIRECTS + ' hops');
|
|
949
|
+
}
|
|
950
|
+
let nextParsed;
|
|
951
|
+
try { nextParsed = new URL(location, currentUrl); } catch (e) {
|
|
952
|
+
throw new Error('SSRF blocked: invalid redirect Location: ' + location);
|
|
953
|
+
}
|
|
954
|
+
if (nextParsed.protocol !== 'http:' && nextParsed.protocol !== 'https:') {
|
|
955
|
+
throw new Error('SSRF blocked: redirect to non-http(s) scheme ' + nextParsed.protocol);
|
|
956
|
+
}
|
|
957
|
+
// If the redirect target is a literal IP, classify it directly \u2014 no DNS
|
|
958
|
+
// lookup will fire and the connect-time guard would never see it.
|
|
959
|
+
const hostname = nextParsed.hostname.replace(/^[|]$/g, '');
|
|
960
|
+
const isIpLiteral = /^[0-9.]+$/.test(hostname) || hostname.includes(':');
|
|
961
|
+
if (isIpLiteral) {
|
|
962
|
+
const verdict = classifyIp(hostname);
|
|
963
|
+
if (verdict === 'block' || (STRICT && verdict === 'private')) {
|
|
964
|
+
throw new Error('SSRF blocked: redirect to ' + hostname + ' (' + verdict + ')');
|
|
965
|
+
}
|
|
966
|
+
} else {
|
|
967
|
+
// Hostname target: resolve and classify every record. The patched
|
|
968
|
+
// dns.lookup also fires on the next fetch's connect, but checking
|
|
969
|
+
// here gives a clearer error and short-circuits before TCP setup.
|
|
970
|
+
const records = await dnsPromises.lookup(hostname, { all: true, verbatim: true });
|
|
971
|
+
for (const rec of records) {
|
|
972
|
+
const verdict = classifyIp(rec.address);
|
|
973
|
+
if (verdict === 'block' || (STRICT && verdict === 'private')) {
|
|
974
|
+
throw new Error(
|
|
975
|
+
'SSRF blocked: redirect target ' + hostname +
|
|
976
|
+
' resolves to ' + rec.address + ' (' + verdict + ')'
|
|
977
|
+
);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
currentUrl = nextParsed.toString();
|
|
982
|
+
}
|
|
983
|
+
throw new Error('SSRF blocked: redirect chain exceeded ' + MAX_REDIRECTS + ' hops');
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
// Subprocess response-body size cap. A malicious or unexpectedly large
|
|
987
|
+
// endpoint reachable through ctx_fetch_and_index would otherwise stream
|
|
988
|
+
// gigabytes into resp.text(), then into outputPath, then into the parent
|
|
989
|
+
// MCP server's heap via readFileSync. 50 MB is far above typical web
|
|
990
|
+
// page / API response sizes (~1-5 MB) but bounded enough to keep parent
|
|
991
|
+
// heap survivable. Cap both early via Content-Length and after the read.
|
|
992
|
+
const MAX_FETCH_BYTES = 50 * 1024 * 1024;
|
|
993
|
+
async function safeText(resp) {
|
|
994
|
+
const cl = parseInt(resp.headers.get('content-length') || '0', 10);
|
|
995
|
+
if (cl > MAX_FETCH_BYTES) {
|
|
996
|
+
throw new Error('Response too large: Content-Length ' + cl + ' exceeds ' + MAX_FETCH_BYTES);
|
|
997
|
+
}
|
|
998
|
+
const text = await resp.text();
|
|
999
|
+
if (text.length > MAX_FETCH_BYTES) {
|
|
1000
|
+
throw new Error('Response too large: ' + text.length + ' bytes exceeds ' + MAX_FETCH_BYTES);
|
|
1001
|
+
}
|
|
1002
|
+
return text;
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
async function main() {
|
|
1006
|
+
const resp = await fetchWithManualRedirect(url);
|
|
1007
|
+
if (!resp.ok) { console.error("HTTP " + resp.status); process.exit(1); }
|
|
1008
|
+
const contentType = resp.headers.get('content-type') || '';
|
|
1009
|
+
|
|
1010
|
+
// --- JSON responses ---
|
|
1011
|
+
if (contentType.includes('application/json') || contentType.includes('+json')) {
|
|
1012
|
+
const text = await safeText(resp);
|
|
1013
|
+
try {
|
|
1014
|
+
const pretty = JSON.stringify(JSON.parse(text), null, 2);
|
|
1015
|
+
emit('json', pretty);
|
|
1016
|
+
} catch {
|
|
1017
|
+
emit('text', text);
|
|
1018
|
+
}
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
// --- HTML responses (default for text/html, application/xhtml+xml) ---
|
|
1023
|
+
if (contentType.includes('text/html') || contentType.includes('application/xhtml')) {
|
|
1024
|
+
const html = await safeText(resp);
|
|
1025
|
+
const td = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced' });
|
|
1026
|
+
td.use(gfm);
|
|
1027
|
+
td.remove(['script', 'style', 'nav', 'header', 'footer', 'noscript']);
|
|
1028
|
+
emit('html', td.turndown(html));
|
|
1029
|
+
return;
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
// --- Everything else: plain text, CSV, XML, etc. ---
|
|
1033
|
+
const text = await safeText(resp);
|
|
1034
|
+
emit('text', text);
|
|
1035
|
+
}
|
|
1036
|
+
main();
|
|
1037
|
+
`}var nM=1440*60*1e3,PS=3072;function sM(t){if(t===0)return"0ms";let e=1440*60*1e3,r=3600*1e3,n=60*1e3;return t%e===0?`${t/e}d`:t%r===0?`${t/r}h`:t%n===0?`${t/n}m`:`${t}ms`}async function oM(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let r=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:n}=await import("node:dns/promises"),s=await n(e.hostname,{all:!0,verbatim:!0});for(let o of s){let i=Cc(o.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${o.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&r)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${o.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(n){let s=n?.code??"",o=s==="ETIMEOUT"||s==="ETIMEDOUT"||s==="EAI_AGAIN"||s==="ENETUNREACH"||s==="EPERM",i=n instanceof Error?n.message:String(n),a=o?" \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 Cc(t){let e=t.indexOf("%"),r=e===-1?t:t.slice(0,e),n=r.toLowerCase();if(n.includes(":")){let a=n.match(/^::ffff:([\d.]+)$/);return a?Cc(a[1]):n==="::"||n.startsWith("fe8")||n.startsWith("fe9")||n.startsWith("fea")||n.startsWith("feb")||n.startsWith("ff")?"block":n==="::1"||n.startsWith("fc")||n.startsWith("fd")?"private":"public"}if(!r.includes("."))return"block";let s=r.split(".").map(a=>parseInt(a,10));if(s.length!==4||s.some(a=>isNaN(a)||a<0||a>255))return"block";let[o,i]=s;return o===169&&i===254||o===0||o>=224?"block":o===127||o===10||o===172&&i>=16&&i<=31||o===192&&i===168?"private":"public"}async function iM(t,e,r,n){let s=await oM(t);if(s)return s;if(!r&&n!==0){let i=sr(),a=Df(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=n??nM;if(l<d){let f=Math.floor(l/36e5),h=Math.floor(l/(60*1e3)),p=f>0?`${f}h ago`:h>0?`${h}m ago`:"just now",m=c.chunkCount*1600;return{kind:"cached",label:c.label,chunkCount:c.chunkCount,estimatedBytes:m,ageStr:p,ttlStr:sM(d)}}}}let o=gt(gm(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=rM(t,o),a=await ii.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=NS(o).size;if(d>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${d} bytes exceeds cap 52428800`,reason:"read"};u=oi(o,"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{AS(o)}catch{}}}function aM(t){let e=sr(),r=Df(t.source,t.url),n=qr(),s;t.header==="__CM_CT__:json"?s=e.indexJSON(t.markdown,r,void 0,n):t.header==="__CM_CT__:text"?s=e.indexPlainText(t.markdown,r,void 0,n):s=e.index({content:t.markdown,source:r,attribution:n}),Vt(Buffer.byteLength(t.markdown));let o=t.markdown.length>PS?Cx(t.markdown,PS)+`
|
|
1038
|
+
|
|
1039
|
+
\u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:s.label,totalChunks:s.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:o}}Se.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.
|
|
1040
|
+
|
|
1041
|
+
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.
|
|
1042
|
+
|
|
1043
|
+
WHEN:
|
|
1044
|
+
- You need web content (docs, changelogs, API references, spec pages) and the raw page bytes should NOT enter your conversation
|
|
1045
|
+
- Multi-URL research (library evaluation, migration scans, doc comparisons): pass the \`requests\` array and a \`concurrency\` value 2-8 for parallel I/O
|
|
1046
|
+
- You want repeat lookups against the same URL to be cheap (TTL cache hits return only a hint, no re-fetch)
|
|
1047
|
+
- You want a long-lived cache window (override \`ttl\` upward for stable specs) or a guaranteed-fresh fetch (\`ttl: 0\` or \`force: true\`)
|
|
1048
|
+
|
|
1049
|
+
WHEN NOT:
|
|
1050
|
+
- You already have the content locally \u2014 store it via the inline index tool
|
|
1051
|
+
- The page is SPA-rendered (JavaScript-required to materialize content) \u2014 this is a plain HTTP fetch, no headless browser
|
|
1052
|
+
|
|
1053
|
+
RETURNS:
|
|
1054
|
+
Per-source preview windows extracted around indexable headings plus indexing metadata (chunk counts, source labels, cache state). Raw content is NOT echoed back \u2014 retrieve any section on-demand via ctx_search(source: "<label>"). Concurrency parallelizes the fetch phase up to your chosen value (capped by the host's logical CPU count); the FTS5 write phase always runs serially because SQLite is a single-writer store. Net latency = max(fetch latency across the pool) + sum(per-source index write time). Cache hits skip both phases and return a small freshness hint instead of re-fetching. Use 4-8 for stable I/O-bound batches; lower the value when the target host enforces a per-IP rate limit you cannot raise.
|
|
1055
|
+
|
|
1056
|
+
EXAMPLE: ctx_fetch_and_index(
|
|
1057
|
+
requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
|
|
1058
|
+
concurrency: 5
|
|
1059
|
+
)`,inputSchema:C.object({url:C.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:C.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:C.preprocess(xm,C.array(C.object({url:C.string().describe("URL to fetch"),source:C.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:C.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:C.preprocess(Sm,C.boolean()).optional().describe("Skip cache and re-fetch even if content was recently indexed"),ttl:C.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:r,concurrency:n,force:s,ttl:o})=>{let i=r||(t?[{url:t,source:e}]:[]);if(i.length===0)return W("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=!r&&i.length===1,c=n??1,u=i.map($=>({run:()=>iM($.url,$.source,s,o)})),{settled:l,effectiveConcurrency:d,capped:f}=await Ef(u,{concurrency:c,capByCpuCount:!a&&c>1}),h=[];for(let $=0;$<l.length;$++){let T=l[$];if(T.status==="rejected"){let de=T.reason instanceof Error?T.reason.message:String(T.reason);h.push({kind:"job_error",url:i[$].url,error:de});continue}let F=T.value;if(F.kind==="cached"){te.cacheHits++,te.cacheBytesSaved+=F.estimatedBytes;let de=F.estimatedBytes,nt=F.label;setImmediate(()=>Kx({sessionDbPath:Rs(),source:nt,bytesAvoided:de})),h.push({kind:"cached",label:F.label,chunkCount:F.chunkCount,ageStr:F.ageStr,ttlStr:F.ttlStr})}else F.kind==="fetch_error"?h.push({kind:"fetch_error",url:F.url,error:F.error,reason:F.reason}):(te.cacheMisses++,h.push({kind:"fetched",indexed:aM(F)}))}if(a){let $=h[0];if($.kind==="cached")return W("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${$.label}** \u2014 ${$.chunkCount} sections, indexed ${$.ageStr} (fresh, TTL: ${$.ttlStr}).
|
|
1060
|
+
To refresh: call ctx_fetch_and_index again with \`force: true\`.
|
|
1061
|
+
|
|
1062
|
+
You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
|
|
1063
|
+
Use: ctx_search(queries: [...], source: "${$.label}")`}]});if($.kind==="fetched"){let T=($.indexed.totalBytes/1024).toFixed(1),F=[`Fetched and indexed **${$.indexed.totalChunks} sections** (${T}KB) from: ${$.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${$.indexed.label}") for specific lookups.`,"","---","",$.indexed.preview].join(`
|
|
1064
|
+
`);return W("ctx_fetch_and_index",{content:[{type:"text",text:F}]})}if($.kind==="fetch_error"){let T=$.reason==="empty"?`Fetched ${$.url} but got empty content`:$.reason==="read"?`Fetched ${$.url} but could not read subprocess output`:$.reason==="exit"?`Failed to fetch ${$.url}: ${$.error}`:`Fetch error: ${$.error}`;return W("ctx_fetch_and_index",{content:[{type:"text",text:T}],isError:!0})}return W("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${$.error}`}],isError:!0})}let p=384,m=[],g=0,y=0,b=0,_=0,x=0,w=[];for(let $ of h)if($.kind==="cached")b++,m.push(`- [cache] ${$.label} \u2014 ${$.chunkCount} sections (${$.ageStr}, TTL: ${$.ttlStr})`);else if($.kind==="fetched"){_++,g+=$.indexed.totalChunks,y+=$.indexed.totalBytes;let T=($.indexed.totalBytes/1024).toFixed(1);m.push(`- [new] ${$.indexed.label} \u2014 ${$.indexed.totalChunks} sections (${T}KB)`);let F=$.indexed.preview.length>p?$.indexed.preview.slice(0,p).trimEnd()+"\u2026":$.indexed.preview;w.push(`### ${$.indexed.label}
|
|
1065
|
+
|
|
1066
|
+
${F}`)}else x++,m.push(`- [err] ${$.url}: ${$.error}`);let I=(y/1024).toFixed(1),R=f?` cap=${d}/${sz().length}cpu`:"",M=($,T,F)=>`${$} ${$===1?T:F}`,V=[`fetched ${i.length} c=${d}${R}. ok=${_} cache=${b} err=${x}. ${M(g,"section","sections")} ${I}KB.`,"",...m,"",'ctx_search(queries: [...], source: "<label>") for full content.',...w.length>0?["","---","",...w]:[]].join(`
|
|
1067
|
+
`);return W("ctx_fetch_and_index",{content:[{type:"text",text:V}],isError:x===i.length})});Se.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.
|
|
1068
|
+
|
|
1069
|
+
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).
|
|
1070
|
+
|
|
1071
|
+
WHEN:
|
|
1072
|
+
- You have 3+ related commands you would otherwise run sequentially (multi-issue lookups, git log + git diff + git blame, multi-file reads, multi-region cloud queries)
|
|
1073
|
+
- You want to gather AND query in one round trip \u2014 pass \`queries\` so the matching sections come back inline
|
|
1074
|
+
- You want to parallelize I/O-bound work \u2014 pass \`concurrency\` 2-8 (network calls, gh CLI, cloud APIs, multi-repo git reads)
|
|
1075
|
+
- The combined output is large enough that piping it through ctx_search later would itself be expensive \u2014 let auto-index + inline queries do both in one shot
|
|
1076
|
+
|
|
1077
|
+
WHEN NOT:
|
|
1078
|
+
- Single command with no follow-up query \u2014 run it in the sandbox tool directly
|
|
1079
|
+
- CPU-bound or stateful commands \u2014 keep concurrency at 1 (npm test, build, lint, port-binding servers, lock-file holders, anything that races on the same resource)
|
|
1080
|
+
|
|
1081
|
+
RETURNS:
|
|
1082
|
+
Auto-indexed section list per command label, plus top matches per query (when \`queries\` is passed). Raw output is NOT echoed in full \u2014 only the matched windows. Concurrency>1 switches each command to its own per-command timeout (no shared budget); concurrency=1 preserves the legacy shared-budget cascading-skip-on-timeout path. Use 4-8 for I/O-bound batches; keep at 1 for CPU work or shared-state commands; lower the value when target hosts enforce per-IP rate limits.
|
|
1083
|
+
|
|
1084
|
+
EXAMPLE: ctx_batch_execute(
|
|
1085
|
+
commands: [
|
|
1086
|
+
{label: "issue 1", command: "gh issue view 1"},
|
|
1087
|
+
{label: "issue 2", command: "gh issue view 2"},
|
|
1088
|
+
{label: "summarize", command: "echo done"}
|
|
1089
|
+
],
|
|
1090
|
+
queries: ["root cause", "proposed fix"],
|
|
1091
|
+
concurrency: 2
|
|
1092
|
+
)`,inputSchema:C.object({commands:C.preprocess(Qz,C.array(C.object({label:C.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:C.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:C.preprocess(xm,C.array(C.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:C.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:C.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:C.string().optional().describe("Optional working directory for all shell commands in this batch."),query_scope:C.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:r,concurrency:n,cwd:s,query_scope:o})=>{for(let i of t){let a=_m(i.command,"batch_execute");if(a)return a}try{let i=Vz(An.shell,Ic),a=bm(r),{outputs:c,timedOut:u}=await Jz(t,{timeout:a,concurrency:n,nodeOptsPrefix:i,cwd:s,onFsBytes:R=>{te.bytesSandboxed+=R}},ii),l=c.join(`
|
|
1093
|
+
`),d=Buffer.byteLength(l),f=l.split(`
|
|
1094
|
+
`).length;if(u&&c.length===0)return W("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${a}ms. No output captured.`}],isError:!0});Vt(d);let h=sr(),p=`batch:${t.map(R=>R.label).join(",").slice(0,80)}`,m=h.index({content:l,source:p,attribution:qr()}),g=["## Commands",""];for(let R of t)g.push(`- ${R.label}: \`${qS(R.command)}\``);let y=h.getChunksBySource(m.sourceId),b=["## Indexed Sections",""],_=[];for(let R of y){let M=Buffer.byteLength(R.content);b.push(`- ${R.title} (${(M/1024).toFixed(1)}KB)`),_.push(R.title)}let x=qz(h,e,p,void 0,o),w=h.getDistinctiveTerms?h.getDistinctiveTerms(m.sourceId):[],I=[`Executed ${t.length} commands (${f} lines, ${(d/1024).toFixed(1)}KB). Indexed ${m.totalChunks} sections. Searched ${e.length} queries.`,"",...g,"",...b,"",...x,w.length>0?`
|
|
1095
|
+
Searchable terms for follow-up: ${w.join(", ")}`:""].join(`
|
|
1096
|
+
`);return W("ctx_batch_execute",{content:[{type:"text",text:I}]})}catch(i){let a=i instanceof Error?i.message:String(i);return W("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${a}`}],isError:!0})}});function um(t,e){if(!Ie(e))return;let r=0;try{for(let n of OS(e))if(!(!n.startsWith("stats-")||!n.endsWith(".json")))try{let s=JSON.parse(oi(gt(e,n),"utf-8"));r+=(s?.bytes_sandboxed??0)+(s?.bytes_indexed??0)}catch{}}catch{}if(r>0){let n=(t.rescueBytes??0)/4;t.totalEvents=Math.round((r/4+n)/256)}}function CS(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}Se.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:C.object({})},async()=>{let t;try{let e=ht(),r=Ut(e),n=ei({projectDir:e,sessionsDir:Ae()});if(Ie(n)){let s=He(),o=new s(n,{readonly:!0});try{let i=new Ts(o),a=i.queryAll(te),c=i.getMcpToolUsage(),u=ri({sessionsDir:Ae()}),l;try{l=gc()}catch{}let d,f;try{let p=process.env.CLAUDE_SESSION_ID;if(p||(p=o.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),p){d=bS({sessionId:p,sessionsDir:Ae(),worktreeHash:r});let m=Tc(),g;try{let x=He(),w=(await import("node:fs")).readdirSync(Ae()).filter(R=>R.endsWith(".db")&&(!r||R.startsWith(r))),I;for(let R of w)try{let M=new x((await import("node:path")).join(Ae(),R),{readonly:!0});try{let z=M.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(p);if(z?.project_dir){I=z.project_dir;break}}finally{M.close()}}catch{}g=im({sessionId:p,worktreeHash:r,sessionsDir:Ae(),contentDbPath:m})}catch{g=im({sessionId:p,worktreeHash:r,sessionsDir:Ae(),contentDbPath:m})}let y=pc({sessionsDir:Ae()}),b=vS(m),_={...y,contentBytes:y.contentBytes+b,bytesAvoided:y.bytesAvoided+b,totalSavedTokens:Math.floor((y.eventDataBytes+y.bytesAvoided+b+y.snapshotBytes)/4)};f={conversation:g,lifetime:_}}}catch{}Ht?.name==="Pi"&&um(u,Ae());let h;try{h=sr().getIndexState()}catch{}t=yc(a,_r,br,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:f,indexState:h,cwd:e})}finally{o.close()}}else{let o=new Ts(CS()).queryAll(te),i=ri({sessionsDir:Ae()});Ht?.name==="Pi"&&um(i,Ae());let a;try{a=gc()}catch{}let c;try{c=sr().getIndexState()}catch{}t=yc(o,_r,br,{lifetime:i,multiAdapter:a,indexState:c})}}catch{let r=new Ts(CS()).queryAll(te),n;try{n=ri({sessionsDir:Ae()})}catch{}Ht?.name==="Pi"&&n&&um(n,Ae());let s;try{s=gc()}catch{}t=yc(r,_r,br,n||s?{lifetime:n,multiAdapter:s}:void 0)}return W("ctx_stats",{content:[{type:"text",text:t}]})});Se.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:C.object({})},async()=>{let t=["context-mode doctor",""],e;try{e=mt(Se.server.getClientVersion()??void 0).platform}catch{e=mt().platform}let r=LS(e),n=11,s=(Sc.length/n*100).toFixed(0);t.push(`[OK] Runtimes: ${Sc.length}/${n} (${s}%) \u2014 ${Sc.join(", ")}`),Wa()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let o=Qo($s),i=Qf($s),a=em($s);t.push(`[OK] Storage sessions: ${o.path} (${nc(o)})`),t.push(`[OK] Storage content: ${i.path} (${nc(i)})`),t.push(`[OK] Storage stats: ${a.path} (${nc(a)})`);{let u=new qo({runtimes:An});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=He();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 vz();if(c){for(let l of c.validateHooks(r)){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=aS(c,r);u.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let l of u){let d=rt(r,l);Ie(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${_r}`),W("ctx_doctor",{content:[{type:"text",text:t.join(`
|
|
1097
|
+
`)}]})});Se.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:C.object({})},async()=>{let t="",e,r;try{let c=Se.server.getClientVersion(),u=mt(c??void 0);r=u.platform,t=` --platform ${u.platform}`,e=vf(u.platform)&&An.javascript?{platform:u.platform,jsRuntime:An.javascript}:void 0}catch{try{r=mt().platform}catch{}}let n=LS(r),s=rt(n,"cli.bundle.mjs"),o=rt(n,"build","cli.js");try{let c=Ae(),u=gt(Os(c),"insight-cache");Ie(u)&&(lM(4747),AS(u,{recursive:!0,force:!0}))}catch{}let i;if(Ie(s))i=`${Ha(s,e)} upgrade${t}`;else if(Ie(o))i=`${Ha(o,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(n)};`,'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(`
|
|
1098
|
+
`),l=rt(n,".ctx-upgrade-inline.mjs"),{writeFileSync:d}=await import("node:fs");d(l,u),i=Ha(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(`
|
|
1099
|
+
`);return W("ctx_upgrade",{content:[{type:"text",text:a}]})});Se.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.
|
|
1100
|
+
|
|
1101
|
+
WHEN:
|
|
1102
|
+
- User explicitly asks to clear a specific session ('purge this session', 'wipe this conversation')
|
|
1103
|
+
- User explicitly asks to reset the whole project ('reset everything', 'wipe the knowledge base')
|
|
1104
|
+
|
|
1105
|
+
WHEN NOT:
|
|
1106
|
+
- User says 'reset', 'clear', or 'wipe' without naming a scope -> ask which scope before calling
|
|
1107
|
+
- User wants to free memory or improve performance -> recommend ctx_stats first, do not purge
|
|
1108
|
+
|
|
1109
|
+
SCOPES (pass exactly one):
|
|
1110
|
+
- Per-session: ctx_purge(confirm: true, sessionId: "<uuid>") deletes that session's events (auto-captured decisions, errors, plans, user prompts, rejected approaches, etc.) and per-session FTS5 chunks; sibling sessions and stats file are preserved.
|
|
1111
|
+
- Per-project: ctx_purge(confirm: true, scope: "project") wipes FTS5 knowledge base, every session DB row, events markdown, and resets the stats file. Use ctx_stats first to preview category counts before purging.
|
|
1112
|
+
|
|
1113
|
+
CONTRACT:
|
|
1114
|
+
- confirm:true is required; confirm:false returns 'purge cancelled'.
|
|
1115
|
+
- sessionId and scope:'project' together return 'ambiguous - pick one'.
|
|
1116
|
+
- scope:'session' without sessionId throws (sessionId required).
|
|
1117
|
+
- Bare {confirm:true} is deprecated: maps to scope:'project' with a stderr warning; will hard-error in a future major.
|
|
1118
|
+
|
|
1119
|
+
RETURNS:
|
|
1120
|
+
A summary of removed rows + the resolved scope.
|
|
1121
|
+
|
|
1122
|
+
EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
|
|
1123
|
+
EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:C.object({confirm:C.preprocess(Sm,C.boolean()).describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:C.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:C.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:r})=>{if(e&&r==="project")return W("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 W("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let n=r??(e?"session":"project");!r&&!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 s;try{s=Tc()}catch{}if(Bt){try{Bt.cleanup()}catch{}Bt=null}let o=s?Os(s):void 0,{deleted:i}=Wx({projectDir:ht(),sessionsDir:Ae(),storePath:s,contentDir:o,legacyContentDir:gt(Is(),".context-mode","content"),contentHash:gr(ht()),scope:n,sessionId:e});if(n==="project"){te.calls={},te.bytesReturned={},te.bytesIndexed=0,te.bytesSandboxed=0,te.cacheHits=0,te.cacheBytesSaved=0,te.sessionStart=Date.now(),i.push("session stats");try{let c=FS();Ie(c)&&Cs(c)}catch{}}let a=n==="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 W("ctx_purge",{content:[{type:"text",text:a}]})});var si=5e3;function cM(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 uM(t,e=process.platform,r=kc){let n=cM(t,e),s=[];for(let{cmd:o,args:i}of n)try{let a=r(o,i,{stdio:"ignore",timeout:si});if(!a.error&&a.status===0)return{ok:!0,method:o};let c=a.error?.message??`status=${a.status===null?"signaled":a.status}`;s.push(`${o}: ${c}`)}catch(a){s.push(`${o}: ${a instanceof Error?a.message:String(a)}`)}return{ok:!1,method:"none",reason:s.join("; ")}}function lM(t,e=process.platform,r=kc){let n={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return n.errors.push(`invalid port: ${t}`),n;try{if(e==="win32"){let s=r("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:si});if(s.error)return n.errors.push(`netstat: ${s.error.message}`),n;if(s.status!==0||typeof s.stdout!="string")return n;let o=`:${t}`,i=new Set;for(let a of s.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let l=u[0],d=u[1],f=u[2],h=u[u.length-1];l==="TCP"&&d.endsWith(o)&&(f!=="0.0.0.0:0"&&f!=="[::]:0"||/^\d+$/.test(h)&&i.add(h))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:si});c.error||c.status!==0?n.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):n.killedPids.push(a)}catch(c){n.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let s=r("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:si});if(s.error)return n.errors.push(`lsof: ${s.error.message}`),n;if(s.status!==0||typeof s.stdout!="string")return n;let o=s.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of o){n.attemptedPids.push(i);try{let a=r("kill",[i],{stdio:"ignore",timeout:si});a.error||a.status!==0?n.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):n.killedPids.push(i)}catch(a){n.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(s){n.errors.push(s instanceof Error?s.message:String(s))}return n}var lm="https://context-mode.com/insight";Se.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:C.object({})},async()=>{let t=uM(lm),e=t.ok?`Opening Insight in your browser: ${lm}`:`Could not auto-open your browser (${t.reason}).
|
|
1124
|
+
Open Insight manually: ${lm}`;return W("ctx_insight",{content:[{type:"text",text:e}]})});async function dM(){let t=Af();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?gm():"/tmp",r=gt(e,`context-mode-mcp-ready-${process.pid}`),n,s=()=>{ii.cleanupBackgrounded(),Bt&&Bt.close();try{Cs(Ic)}catch{}try{Cs(r)}catch{}n&&clearInterval(n)},o=async()=>{try{fm=0,$c()}catch{}s(),process.exit(0)};process.on("exit",s),process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),Px({onShutdown:()=>o()});let i=new Ba;await Se.connect(i),Rx(i);try{Ec(r,String(process.pid))}catch{}n=setInterval(()=>{try{Ec(r,String(process.pid))}catch{}},3e4),n.unref();try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(Pn(),Ff)),u=Se.server.getClientVersion(),l=a(u??void 0);Ht=await c(l.platform),u&&console.error(`MCP client: ${u.name} v${u.version} \u2192 ${l.platform}`)}catch{}try{let a=Qx(Rs());if(a){for(let[c,u]of Object.entries(a.calls))te.calls[c]=u;for(let[c,u]of Object.entries(a.bytesReturned))te.bytesReturned[c]=u;a.sessionStart>0&&(te.sessionStart=a.sessionStart)}}catch{}wS().then(a=>{a!=="unknown"&&(br=a)}),setInterval(()=>{wS().then(a=>{a!=="unknown"&&(br=a)})},3600*1e3).unref(),setInterval(()=>$c(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${_r} running on stdio`),console.error(`Detected runtimes:
|
|
1125
|
+
${qv(An)}`),Wa()||(console.error(`
|
|
1126
|
+
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}yz();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&dM().catch(t=>{console.error("Fatal:",t),process.exit(1)});export{Wz as AGY_DEFAULT_EXEC_TIMEOUT_MS,cz as REGISTERED_CTX_TOOLS,FB as __resetSuppressionDiagnosticForTests,cM as browserOpenArgv,Vz as buildBatchNodeOptionsPrefix,rM as buildFetchCode,Cc as classifyIp,qr as currentAttribution,fz as emitSuppressionDiagnostic,US as extractSnippet,qz as formatBatchQueryResults,ht as getProjectDir,yz as installStrictClientSchemaCompat,lM as killProcessOnPort,uM as openBrowserSync,Uz as positionsFromHighlight,mz as registerEmptyToolsListHandler,bm as resolveExecTimeout,_z as resolveSessionIdFromSessionDB,Jz as runBatchCommands,pm as sanitizeSchemaForStrictClients,Se as server,uz as shouldSuppressMcpToolsForNativePluginHost,ZB as withProjectDirOverride};
|